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::structural_impls::PredicateVisitor;
35 use crate::ty::{self, flags::FlagComputation, Binder, Ty, TyCtxt, TypeFlags};
37 use rustc_hir::def_id::DefId;
39 use rustc_data_structures::fx::FxHashSet;
40 use std::collections::BTreeMap;
43 /// This trait is implemented for every type that can be folded.
44 /// Basically, every type that has a corresponding method in `TypeFolder`.
46 /// To implement this conveniently, use the derive macro located in librustc_macros.
47 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
48 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self;
49 fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
50 self.super_fold_with(folder)
53 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool;
54 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
55 self.super_visit_with(visitor)
58 /// Returns `true` if `self` has any late-bound regions that are either
59 /// bound by `binder` or bound by some binder outside of `binder`.
60 /// If `binder` is `ty::INNERMOST`, this indicates whether
61 /// there are any late-bound regions that appear free.
62 fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
63 self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder })
66 /// Returns `true` if this `self` has any regions that escape `binder` (and
67 /// hence are not bound by it).
68 fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
69 self.has_vars_bound_at_or_above(binder.shifted_in(1))
72 fn has_escaping_bound_vars(&self) -> bool {
73 self.has_vars_bound_at_or_above(ty::INNERMOST)
76 fn has_type_flags(&self, flags: TypeFlags) -> bool {
77 self.visit_with(&mut HasTypeFlagsVisitor { flags })
79 fn has_projections(&self) -> bool {
80 self.has_type_flags(TypeFlags::HAS_PROJECTION)
82 fn has_opaque_types(&self) -> bool {
83 self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
85 fn references_error(&self) -> bool {
86 self.has_type_flags(TypeFlags::HAS_ERROR)
88 fn has_param_types_or_consts(&self) -> bool {
89 self.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_CT_PARAM)
91 fn has_infer_regions(&self) -> bool {
92 self.has_type_flags(TypeFlags::HAS_RE_INFER)
94 fn has_infer_types(&self) -> bool {
95 self.has_type_flags(TypeFlags::HAS_TY_INFER)
97 fn has_infer_types_or_consts(&self) -> bool {
98 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER)
100 fn needs_infer(&self) -> bool {
101 self.has_type_flags(TypeFlags::NEEDS_INFER)
103 fn has_placeholders(&self) -> bool {
105 TypeFlags::HAS_RE_PLACEHOLDER
106 | TypeFlags::HAS_TY_PLACEHOLDER
107 | TypeFlags::HAS_CT_PLACEHOLDER,
110 fn needs_subst(&self) -> bool {
111 self.has_type_flags(TypeFlags::NEEDS_SUBST)
113 /// "Free" regions in this context means that it has any region
114 /// that is not (a) erased or (b) late-bound.
115 fn has_free_regions(&self) -> bool {
116 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
119 fn has_erased_regions(&self) -> bool {
120 self.has_type_flags(TypeFlags::HAS_RE_ERASED)
123 /// True if there are any un-erased free regions.
124 fn has_erasable_regions(&self) -> bool {
125 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
128 /// Indicates whether this value references only 'global'
129 /// generic parameters that are the same regardless of what fn we are
130 /// in. This is used for caching.
131 fn is_global(&self) -> bool {
132 !self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
135 /// True if there are any late-bound regions
136 fn has_late_bound_regions(&self) -> bool {
137 self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
140 /// Indicates whether this value still has parameters/placeholders/inference variables
141 /// which could be replaced later, in a way that would change the results of `impl`
143 fn still_further_specializable(&self) -> bool {
144 self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
147 /// A visitor that does not recurse into types, works like `fn walk_shallow` in `Ty`.
148 fn visit_tys_shallow(&self, visit: impl FnMut(Ty<'tcx>) -> bool) -> bool {
149 pub struct Visitor<F>(F);
151 impl<'tcx, F: FnMut(Ty<'tcx>) -> bool> TypeVisitor<'tcx> for Visitor<F> {
152 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
157 self.visit_with(&mut Visitor(visit))
161 impl TypeFoldable<'tcx> for hir::Constness {
162 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
165 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
170 /// The `TypeFolder` trait defines the actual *folding*. There is a
171 /// method defined for every foldable type. Each of these has a
172 /// default implementation that does an "identity" fold. Within each
173 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
175 pub trait TypeFolder<'tcx>: Sized {
176 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
178 fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
180 T: TypeFoldable<'tcx>,
182 t.super_fold_with(self)
185 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
186 t.super_fold_with(self)
189 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
190 r.super_fold_with(self)
193 fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
194 c.super_fold_with(self)
198 pub trait TypeVisitor<'tcx>: Sized {
199 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
200 t.super_visit_with(self)
203 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
204 t.super_visit_with(self)
207 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
208 r.super_visit_with(self)
211 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
212 c.super_visit_with(self)
216 ///////////////////////////////////////////////////////////////////////////
217 // Some sample folders
219 pub struct BottomUpFolder<'tcx, F, G, H>
221 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
222 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
223 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
225 pub tcx: TyCtxt<'tcx>,
231 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
233 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
234 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
235 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
237 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
241 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
242 let t = ty.super_fold_with(self);
246 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
247 let r = r.super_fold_with(self);
251 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
252 let ct = ct.super_fold_with(self);
257 ///////////////////////////////////////////////////////////////////////////
260 impl<'tcx> TyCtxt<'tcx> {
261 /// Folds the escaping and free regions in `value` using `f`, and
262 /// sets `skipped_regions` to true if any late-bound region was found
264 pub fn fold_regions<T>(
267 skipped_regions: &mut bool,
268 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
271 T: TypeFoldable<'tcx>,
273 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
276 /// Invoke `callback` on every region appearing free in `value`.
277 pub fn for_each_free_region(
279 value: &impl TypeFoldable<'tcx>,
280 mut callback: impl FnMut(ty::Region<'tcx>),
282 self.any_free_region_meets(value, |r| {
288 /// Returns `true` if `callback` returns true for every region appearing free in `value`.
289 pub fn all_free_regions_meet(
291 value: &impl TypeFoldable<'tcx>,
292 mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
294 !self.any_free_region_meets(value, |r| !callback(r))
297 /// Returns `true` if `callback` returns true for some region appearing free in `value`.
298 pub fn any_free_region_meets(
300 value: &impl TypeFoldable<'tcx>,
301 callback: impl FnMut(ty::Region<'tcx>) -> bool,
303 return value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback });
305 struct RegionVisitor<F> {
306 /// The index of a binder *just outside* the things we have
307 /// traversed. If we encounter a bound region bound by this
308 /// binder or one outer to it, it appears free. Example:
311 /// for<'a> fn(for<'b> fn(), T)
313 /// | | | | here, would be shifted in 1
314 /// | | | here, would be shifted in 2
315 /// | | here, would be `INNERMOST` shifted in by 1
316 /// | here, initially, binder would be `INNERMOST`
319 /// You see that, initially, *any* bound value is free,
320 /// because we've not traversed any binders. As we pass
321 /// through a binder, we shift the `outer_index` by 1 to
322 /// account for the new binder that encloses us.
323 outer_index: ty::DebruijnIndex,
327 impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
329 F: FnMut(ty::Region<'tcx>) -> bool,
331 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
332 self.outer_index.shift_in(1);
333 let result = t.as_ref().skip_binder().visit_with(self);
334 self.outer_index.shift_out(1);
338 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
340 ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
341 false // ignore bound regions, keep visiting
343 _ => (self.callback)(r),
347 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
348 // We're only interested in types involving regions
349 if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) {
350 ty.super_visit_with(self)
352 false // keep visiting
359 /// Folds over the substructure of a type, visiting its component
360 /// types and all regions that occur *free* within it.
362 /// That is, `Ty` can contain function or method types that bind
363 /// regions at the call site (`ReLateBound`), and occurrences of
364 /// regions (aka "lifetimes") that are bound within a type are not
365 /// visited by this folder; only regions that occur free will be
366 /// visited by `fld_r`.
368 pub struct RegionFolder<'a, 'tcx> {
370 skipped_regions: &'a mut bool,
372 /// Stores the index of a binder *just outside* the stuff we have
373 /// visited. So this begins as INNERMOST; when we pass through a
374 /// binder, it is incremented (via `shift_in`).
375 current_index: ty::DebruijnIndex,
377 /// Callback invokes for each free region. The `DebruijnIndex`
378 /// points to the binder *just outside* the ones we have passed
381 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
384 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
388 skipped_regions: &'a mut bool,
389 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
390 ) -> RegionFolder<'a, 'tcx> {
391 RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
395 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
396 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
400 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
401 self.current_index.shift_in(1);
402 let t = t.super_fold_with(self);
403 self.current_index.shift_out(1);
407 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
409 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
411 "RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
412 r, self.current_index
414 *self.skipped_regions = true;
419 "RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
420 r, self.current_index
422 (self.fold_region_fn)(r, self.current_index)
428 ///////////////////////////////////////////////////////////////////////////
429 // Bound vars replacer
431 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
432 struct BoundVarReplacer<'a, 'tcx> {
435 /// As with `RegionFolder`, represents the index of a binder *just outside*
436 /// the ones we have visited.
437 current_index: ty::DebruijnIndex,
439 fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
440 fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
441 fld_c: &'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a),
444 impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
445 fn new<F, G, H>(tcx: TyCtxt<'tcx>, fld_r: &'a mut F, fld_t: &'a mut G, fld_c: &'a mut H) -> Self
447 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
448 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
449 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
451 BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
455 impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
456 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
460 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
461 self.current_index.shift_in(1);
462 let t = t.super_fold_with(self);
463 self.current_index.shift_out(1);
467 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
469 ty::Bound(debruijn, bound_ty) => {
470 if debruijn == self.current_index {
471 let fld_t = &mut self.fld_t;
472 let ty = fld_t(bound_ty);
473 ty::fold::shift_vars(self.tcx, &ty, self.current_index.as_u32())
479 if !t.has_vars_bound_at_or_above(self.current_index) {
480 // Nothing more to substitute.
483 t.super_fold_with(self)
489 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
491 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
492 let fld_r = &mut self.fld_r;
493 let region = fld_r(br);
494 if let ty::ReLateBound(debruijn1, br) = *region {
495 // If the callback returns a late-bound region,
496 // that region should always use the INNERMOST
497 // debruijn index. Then we adjust it to the
499 assert_eq!(debruijn1, ty::INNERMOST);
500 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
509 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
510 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty } = *ct {
511 if debruijn == self.current_index {
512 let fld_c = &mut self.fld_c;
513 let ct = fld_c(bound_const, ty);
514 ty::fold::shift_vars(self.tcx, &ct, self.current_index.as_u32())
519 if !ct.has_vars_bound_at_or_above(self.current_index) {
520 // Nothing more to substitute.
523 ct.super_fold_with(self)
529 impl<'tcx> TyCtxt<'tcx> {
530 /// Replaces all regions bound by the given `Binder` with the
531 /// results returned by the closure; the closure is expected to
532 /// return a free region (relative to this binder), and hence the
533 /// binder is removed in the return type. The closure is invoked
534 /// once for each unique `BoundRegion`; multiple references to the
535 /// same `BoundRegion` will reuse the previous result. A map is
536 /// returned at the end with each bound region and the free region
537 /// that replaced it.
539 /// This method only replaces late bound regions and the result may still
540 /// contain escaping bound types.
541 pub fn replace_late_bound_regions<T, F>(
545 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
547 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
548 T: TypeFoldable<'tcx>,
550 // identity for bound types and consts
551 let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
552 let fld_c = |bound_ct, ty| {
553 self.mk_const(ty::Const { val: ty::ConstKind::Bound(ty::INNERMOST, bound_ct), ty })
555 self.replace_escaping_bound_vars(value.as_ref().skip_binder(), fld_r, fld_t, fld_c)
558 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
559 /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
560 /// closure replaces escaping bound consts.
561 pub fn replace_escaping_bound_vars<T, F, G, H>(
567 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
569 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
570 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
571 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
572 T: TypeFoldable<'tcx>,
574 use rustc_data_structures::fx::FxHashMap;
576 let mut region_map = BTreeMap::new();
577 let mut type_map = FxHashMap::default();
578 let mut const_map = FxHashMap::default();
580 if !value.has_escaping_bound_vars() {
581 (value.clone(), region_map)
583 let mut real_fld_r = |br| *region_map.entry(br).or_insert_with(|| fld_r(br));
586 |bound_ty| *type_map.entry(bound_ty).or_insert_with(|| fld_t(bound_ty));
589 |bound_ct, ty| *const_map.entry(bound_ct).or_insert_with(|| fld_c(bound_ct, ty));
592 BoundVarReplacer::new(self, &mut real_fld_r, &mut real_fld_t, &mut real_fld_c);
593 let result = value.fold_with(&mut replacer);
598 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
599 /// closure replaces bound regions while the `fld_t` closure replaces bound
601 pub fn replace_bound_vars<T, F, G, H>(
607 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
609 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
610 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
611 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
612 T: TypeFoldable<'tcx>,
614 self.replace_escaping_bound_vars(value.as_ref().skip_binder(), fld_r, fld_t, fld_c)
617 /// Replaces any late-bound regions bound in `value` with
618 /// free variants attached to `all_outlive_scope`.
619 pub fn liberate_late_bound_regions<T>(
621 all_outlive_scope: DefId,
622 value: &ty::Binder<T>,
625 T: TypeFoldable<'tcx>,
627 self.replace_late_bound_regions(value, |br| {
628 self.mk_region(ty::ReFree(ty::FreeRegion {
629 scope: all_outlive_scope,
636 /// Returns a set of all late-bound regions that are constrained
637 /// by `value`, meaning that if we instantiate those LBR with
638 /// variables and equate `value` with something else, those
639 /// variables will also be equated.
640 pub fn collect_constrained_late_bound_regions<T>(
643 ) -> FxHashSet<ty::BoundRegion>
645 T: TypeFoldable<'tcx>,
647 self.collect_late_bound_regions(value, true)
650 /// Returns a set of all late-bound regions that appear in `value` anywhere.
651 pub fn collect_referenced_late_bound_regions<T>(
654 ) -> FxHashSet<ty::BoundRegion>
656 T: TypeFoldable<'tcx>,
658 self.collect_late_bound_regions(value, false)
661 fn collect_late_bound_regions<T>(
664 just_constraint: bool,
665 ) -> FxHashSet<ty::BoundRegion>
667 T: TypeFoldable<'tcx>,
669 let mut collector = LateBoundRegionsCollector::new(just_constraint);
670 let result = value.as_ref().skip_binder().visit_with(&mut collector);
671 assert!(!result); // should never have stopped early
675 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
676 /// method lookup and a few other places where precise region relationships are not required.
677 pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
679 T: TypeFoldable<'tcx>,
681 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
684 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
685 /// assigned starting at 1 and increasing monotonically in the order traversed
686 /// by the fold operation.
688 /// The chief purpose of this function is to canonicalize regions so that two
689 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
690 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
691 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
692 pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
694 T: TypeFoldable<'tcx>,
698 self.replace_late_bound_regions(sig, |_| {
700 self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)))
707 ///////////////////////////////////////////////////////////////////////////
710 // Shifts the De Bruijn indices on all escaping bound vars by a
711 // fixed amount. Useful in substitution or when otherwise introducing
712 // a binding level that is not intended to capture the existing bound
713 // vars. See comment on `shift_vars_through_binders` method in
714 // `subst.rs` for more details.
716 struct Shifter<'tcx> {
718 current_index: ty::DebruijnIndex,
723 pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
724 Shifter { tcx, current_index: ty::INNERMOST, amount }
728 impl TypeFolder<'tcx> for Shifter<'tcx> {
729 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
733 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
734 self.current_index.shift_in(1);
735 let t = t.super_fold_with(self);
736 self.current_index.shift_out(1);
740 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
742 ty::ReLateBound(debruijn, br) => {
743 if self.amount == 0 || debruijn < self.current_index {
746 let debruijn = debruijn.shifted_in(self.amount);
747 let shifted = ty::ReLateBound(debruijn, br);
748 self.tcx.mk_region(shifted)
755 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
757 ty::Bound(debruijn, bound_ty) => {
758 if self.amount == 0 || debruijn < self.current_index {
761 let debruijn = debruijn.shifted_in(self.amount);
762 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
766 _ => ty.super_fold_with(self),
770 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
771 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct {
772 if self.amount == 0 || debruijn < self.current_index {
775 let debruijn = debruijn.shifted_in(self.amount);
776 self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty })
779 ct.super_fold_with(self)
784 pub fn shift_region<'tcx>(
786 region: ty::Region<'tcx>,
788 ) -> ty::Region<'tcx> {
790 ty::ReLateBound(debruijn, br) if amount > 0 => {
791 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
797 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: &T, amount: u32) -> T
799 T: TypeFoldable<'tcx>,
801 debug!("shift_vars(value={:?}, amount={})", value, amount);
803 value.fold_with(&mut Shifter::new(tcx, amount))
806 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
807 /// bound region or a bound type.
809 /// So, for example, consider a type like the following, which has two binders:
811 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
812 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
813 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
815 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
816 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
817 /// fn type*, that type has an escaping region: `'a`.
819 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
820 /// we already use the term "free var". It refers to the regions or types that we use to represent
821 /// bound regions or type params on a fn definition while we are type checking its body.
823 /// To clarify, conceptually there is no particular difference between
824 /// an "escaping" var and a "free" var. However, there is a big
825 /// difference in practice. Basically, when "entering" a binding
826 /// level, one is generally required to do some sort of processing to
827 /// a bound var, such as replacing it with a fresh/placeholder
828 /// var, or making an entry in the environment to represent the
829 /// scope to which it is attached, etc. An escaping var represents
830 /// a bound var for which this processing has not yet been done.
831 struct HasEscapingVarsVisitor {
832 /// Anything bound by `outer_index` or "above" is escaping.
833 outer_index: ty::DebruijnIndex,
836 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
837 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
838 self.outer_index.shift_in(1);
839 let result = t.super_visit_with(self);
840 self.outer_index.shift_out(1);
844 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
845 // If the outer-exclusive-binder is *strictly greater* than
846 // `outer_index`, that means that `t` contains some content
847 // bound at `outer_index` or above (because
848 // `outer_exclusive_binder` is always 1 higher than the
849 // content in `t`). Therefore, `t` has some escaping vars.
850 t.outer_exclusive_binder > self.outer_index
853 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
854 // If the region is bound by `outer_index` or anything outside
855 // of outer index, then it escapes the binders we have
857 r.bound_at_or_above_binder(self.outer_index)
860 fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> bool {
861 // we don't have a `visit_infer_const` callback, so we have to
862 // hook in here to catch this case (annoying...), but
863 // otherwise we do want to remember to visit the rest of the
864 // const, as it has types/regions embedded in a lot of other
867 ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => true,
868 _ => ct.super_visit_with(self),
873 impl<'tcx> PredicateVisitor<'tcx> for HasEscapingVarsVisitor {
874 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> bool {
875 predicate.inner.outer_exclusive_binder > self.outer_index
879 // FIXME: Optimize for checking for infer flags
880 struct HasTypeFlagsVisitor {
881 flags: ty::TypeFlags,
884 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
885 fn visit_ty(&mut self, t: Ty<'_>) -> bool {
887 "HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}",
892 t.flags().intersects(self.flags)
895 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
896 let flags = r.type_flags();
897 debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
898 flags.intersects(self.flags)
901 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
902 let flags = FlagComputation::for_const(c);
903 debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
904 flags.intersects(self.flags)
908 impl<'tcx> PredicateVisitor<'tcx> for HasTypeFlagsVisitor {
909 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> bool {
911 "HasTypeFlagsVisitor: predicate={:?} predicate.flags={:?} self.flags={:?}",
912 predicate, predicate.inner.flags, self.flags
914 predicate.inner.flags.intersects(self.flags)
917 /// Collects all the late-bound regions at the innermost binding level
919 struct LateBoundRegionsCollector {
920 current_index: ty::DebruijnIndex,
921 regions: FxHashSet<ty::BoundRegion>,
923 /// `true` if we only want regions that are known to be
924 /// "constrained" when you equate this type with another type. In
925 /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
926 /// them constraints `'a == 'b`. But if you have `<&'a u32 as
927 /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
928 /// types may mean that `'a` and `'b` don't appear in the results,
929 /// so they are not considered *constrained*.
930 just_constrained: bool,
933 impl LateBoundRegionsCollector {
934 fn new(just_constrained: bool) -> Self {
935 LateBoundRegionsCollector {
936 current_index: ty::INNERMOST,
937 regions: Default::default(),
943 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
944 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
945 self.current_index.shift_in(1);
946 let result = t.super_visit_with(self);
947 self.current_index.shift_out(1);
951 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
952 // if we are only looking for "constrained" region, we have to
953 // ignore the inputs to a projection, as they may not appear
954 // in the normalized form
955 if self.just_constrained {
956 if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
961 t.super_visit_with(self)
964 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
965 // if we are only looking for "constrained" region, we have to
966 // ignore the inputs of an unevaluated const, as they may not appear
967 // in the normalized form
968 if self.just_constrained {
969 if let ty::ConstKind::Unevaluated(..) = c.val {
974 c.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);