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.
33 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;
40 use std::ops::ControlFlow;
42 /// This trait is implemented for every type that can be folded.
43 /// Basically, every type that has a corresponding method in `TypeFolder`.
45 /// To implement this conveniently, use the derive macro located in librustc_macros.
46 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
47 fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self;
48 fn fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
49 self.super_fold_with(folder)
52 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<()>;
53 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<()> {
54 self.super_visit_with(visitor)
57 /// Returns `true` if `self` has any late-bound regions that are either
58 /// bound by `binder` or bound by some binder outside of `binder`.
59 /// If `binder` is `ty::INNERMOST`, this indicates whether
60 /// there are any late-bound regions that appear free.
61 fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
62 self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder }).is_break()
65 /// Returns `true` if this `self` has any regions that escape `binder` (and
66 /// hence are not bound by it).
67 fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
68 self.has_vars_bound_at_or_above(binder.shifted_in(1))
71 fn has_escaping_bound_vars(&self) -> bool {
72 self.has_vars_bound_at_or_above(ty::INNERMOST)
75 fn has_type_flags(&self, flags: TypeFlags) -> bool {
76 self.visit_with(&mut HasTypeFlagsVisitor { flags }).is_break()
78 fn has_projections(&self) -> bool {
79 self.has_type_flags(TypeFlags::HAS_PROJECTION)
81 fn has_opaque_types(&self) -> bool {
82 self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
84 fn references_error(&self) -> bool {
85 self.has_type_flags(TypeFlags::HAS_ERROR)
87 fn has_param_types_or_consts(&self) -> bool {
88 self.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_CT_PARAM)
90 fn has_infer_regions(&self) -> bool {
91 self.has_type_flags(TypeFlags::HAS_RE_INFER)
93 fn has_infer_types(&self) -> bool {
94 self.has_type_flags(TypeFlags::HAS_TY_INFER)
96 fn has_infer_types_or_consts(&self) -> bool {
97 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER)
99 fn needs_infer(&self) -> bool {
100 self.has_type_flags(TypeFlags::NEEDS_INFER)
102 fn has_placeholders(&self) -> bool {
104 TypeFlags::HAS_RE_PLACEHOLDER
105 | TypeFlags::HAS_TY_PLACEHOLDER
106 | TypeFlags::HAS_CT_PLACEHOLDER,
109 fn needs_subst(&self) -> bool {
110 self.has_type_flags(TypeFlags::NEEDS_SUBST)
112 /// "Free" regions in this context means that it has any region
113 /// that is not (a) erased or (b) late-bound.
114 fn has_free_regions(&self) -> bool {
115 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
118 fn has_erased_regions(&self) -> bool {
119 self.has_type_flags(TypeFlags::HAS_RE_ERASED)
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 /// Indicates whether this value still has parameters/placeholders/inference variables
140 /// which could be replaced later, in a way that would change the results of `impl`
142 fn still_further_specializable(&self) -> bool {
143 self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
146 /// A visitor that does not recurse into types, works like `fn walk_shallow` in `Ty`.
147 fn visit_tys_shallow(&self, visit: impl FnMut(Ty<'tcx>) -> ControlFlow<()>) -> ControlFlow<()> {
148 pub struct Visitor<F>(F);
150 impl<'tcx, F: FnMut(Ty<'tcx>) -> ControlFlow<()>> TypeVisitor<'tcx> for Visitor<F> {
151 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<()> {
156 self.visit_with(&mut Visitor(visit))
160 impl TypeFoldable<'tcx> for hir::Constness {
161 fn super_fold_with<F: TypeFolder<'tcx>>(self, _: &mut F) -> Self {
164 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> ControlFlow<()> {
165 ControlFlow::CONTINUE
169 /// The `TypeFolder` trait defines the actual *folding*. There is a
170 /// method defined for every foldable type. Each of these has a
171 /// default implementation that does an "identity" fold. Within each
172 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
174 pub trait TypeFolder<'tcx>: Sized {
175 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
177 fn fold_binder<T>(&mut self, t: Binder<T>) -> Binder<T>
179 T: TypeFoldable<'tcx>,
181 t.super_fold_with(self)
184 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
185 t.super_fold_with(self)
188 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
189 r.super_fold_with(self)
192 fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
193 c.super_fold_with(self)
197 pub trait TypeVisitor<'tcx>: Sized {
198 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<()> {
199 t.super_visit_with(self)
202 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<()> {
203 t.super_visit_with(self)
206 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<()> {
207 r.super_visit_with(self)
210 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<()> {
211 c.super_visit_with(self)
214 fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<()> {
215 p.super_visit_with(self)
219 ///////////////////////////////////////////////////////////////////////////
220 // Some sample folders
222 pub struct BottomUpFolder<'tcx, F, G, H>
224 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
225 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
226 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
228 pub tcx: TyCtxt<'tcx>,
234 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
236 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
237 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
238 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
240 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
244 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
245 let t = ty.super_fold_with(self);
249 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
250 let r = r.super_fold_with(self);
254 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
255 let ct = ct.super_fold_with(self);
260 ///////////////////////////////////////////////////////////////////////////
263 impl<'tcx> TyCtxt<'tcx> {
264 /// Folds the escaping and free regions in `value` using `f`, and
265 /// sets `skipped_regions` to true if any late-bound region was found
267 pub fn fold_regions<T>(
270 skipped_regions: &mut bool,
271 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
274 T: TypeFoldable<'tcx>,
276 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
279 /// Invoke `callback` on every region appearing free in `value`.
280 pub fn for_each_free_region(
282 value: &impl TypeFoldable<'tcx>,
283 mut callback: impl FnMut(ty::Region<'tcx>),
285 self.any_free_region_meets(value, |r| {
291 /// Returns `true` if `callback` returns true for every region appearing free in `value`.
292 pub fn all_free_regions_meet(
294 value: &impl TypeFoldable<'tcx>,
295 mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
297 !self.any_free_region_meets(value, |r| !callback(r))
300 /// Returns `true` if `callback` returns true for some region appearing free in `value`.
301 pub fn any_free_region_meets(
303 value: &impl TypeFoldable<'tcx>,
304 callback: impl FnMut(ty::Region<'tcx>) -> bool,
306 struct RegionVisitor<F> {
307 /// The index of a binder *just outside* the things we have
308 /// traversed. If we encounter a bound region bound by this
309 /// binder or one outer to it, it appears free. Example:
312 /// for<'a> fn(for<'b> fn(), T)
314 /// | | | | here, would be shifted in 1
315 /// | | | here, would be shifted in 2
316 /// | | here, would be `INNERMOST` shifted in by 1
317 /// | here, initially, binder would be `INNERMOST`
320 /// You see that, initially, *any* bound value is free,
321 /// because we've not traversed any binders. As we pass
322 /// through a binder, we shift the `outer_index` by 1 to
323 /// account for the new binder that encloses us.
324 outer_index: ty::DebruijnIndex,
328 impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
330 F: FnMut(ty::Region<'tcx>) -> bool,
332 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<()> {
333 self.outer_index.shift_in(1);
334 let result = t.as_ref().skip_binder().visit_with(self);
335 self.outer_index.shift_out(1);
339 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<()> {
341 ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
342 ControlFlow::CONTINUE
345 if (self.callback)(r) {
348 ControlFlow::CONTINUE
354 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<()> {
355 // We're only interested in types involving regions
356 if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) {
357 ty.super_visit_with(self)
359 ControlFlow::CONTINUE
364 value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback }).is_break()
368 /// Folds over the substructure of a type, visiting its component
369 /// types and all regions that occur *free* within it.
371 /// That is, `Ty` can contain function or method types that bind
372 /// regions at the call site (`ReLateBound`), and occurrences of
373 /// regions (aka "lifetimes") that are bound within a type are not
374 /// visited by this folder; only regions that occur free will be
375 /// visited by `fld_r`.
377 pub struct RegionFolder<'a, 'tcx> {
379 skipped_regions: &'a mut bool,
381 /// Stores the index of a binder *just outside* the stuff we have
382 /// visited. So this begins as INNERMOST; when we pass through a
383 /// binder, it is incremented (via `shift_in`).
384 current_index: ty::DebruijnIndex,
386 /// Callback invokes for each free region. The `DebruijnIndex`
387 /// points to the binder *just outside* the ones we have passed
390 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
393 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
397 skipped_regions: &'a mut bool,
398 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
399 ) -> RegionFolder<'a, 'tcx> {
400 RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
404 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
405 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
409 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: ty::Binder<T>) -> ty::Binder<T> {
410 self.current_index.shift_in(1);
411 let t = t.super_fold_with(self);
412 self.current_index.shift_out(1);
416 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
418 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
420 "RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
421 r, self.current_index
423 *self.skipped_regions = true;
428 "RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
429 r, self.current_index
431 (self.fold_region_fn)(r, self.current_index)
437 ///////////////////////////////////////////////////////////////////////////
438 // Bound vars replacer
440 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
441 struct BoundVarReplacer<'a, 'tcx> {
444 /// As with `RegionFolder`, represents the index of a binder *just outside*
445 /// the ones we have visited.
446 current_index: ty::DebruijnIndex,
448 fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
449 fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
450 fld_c: &'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a),
453 impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
454 fn new<F, G, H>(tcx: TyCtxt<'tcx>, fld_r: &'a mut F, fld_t: &'a mut G, fld_c: &'a mut H) -> Self
456 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
457 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
458 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
460 BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
464 impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
465 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
469 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: ty::Binder<T>) -> ty::Binder<T> {
470 self.current_index.shift_in(1);
471 let t = t.super_fold_with(self);
472 self.current_index.shift_out(1);
476 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
478 ty::Bound(debruijn, bound_ty) => {
479 if debruijn == self.current_index {
480 let fld_t = &mut self.fld_t;
481 let ty = fld_t(bound_ty);
482 ty::fold::shift_vars(self.tcx, &ty, self.current_index.as_u32())
488 if !t.has_vars_bound_at_or_above(self.current_index) {
489 // Nothing more to substitute.
492 t.super_fold_with(self)
498 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
500 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
501 let fld_r = &mut self.fld_r;
502 let region = fld_r(br);
503 if let ty::ReLateBound(debruijn1, br) = *region {
504 // If the callback returns a late-bound region,
505 // that region should always use the INNERMOST
506 // debruijn index. Then we adjust it to the
508 assert_eq!(debruijn1, ty::INNERMOST);
509 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
518 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
519 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty } = *ct {
520 if debruijn == self.current_index {
521 let fld_c = &mut self.fld_c;
522 let ct = fld_c(bound_const, ty);
523 ty::fold::shift_vars(self.tcx, &ct, self.current_index.as_u32())
528 if !ct.has_vars_bound_at_or_above(self.current_index) {
529 // Nothing more to substitute.
532 ct.super_fold_with(self)
538 impl<'tcx> TyCtxt<'tcx> {
539 /// Replaces all regions bound by the given `Binder` with the
540 /// results returned by the closure; the closure is expected to
541 /// return a free region (relative to this binder), and hence the
542 /// binder is removed in the return type. The closure is invoked
543 /// once for each unique `BoundRegion`; multiple references to the
544 /// same `BoundRegion` will reuse the previous result. A map is
545 /// returned at the end with each bound region and the free region
546 /// that replaced it.
548 /// This method only replaces late bound regions and the result may still
549 /// contain escaping bound types.
550 pub fn replace_late_bound_regions<T, F>(
554 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
556 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
557 T: TypeFoldable<'tcx>,
559 // identity for bound types and consts
560 let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
561 let fld_c = |bound_ct, ty| {
562 self.mk_const(ty::Const { val: ty::ConstKind::Bound(ty::INNERMOST, bound_ct), ty })
564 self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t, fld_c)
567 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
568 /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
569 /// closure replaces escaping bound consts.
570 pub fn replace_escaping_bound_vars<T, F, G, H>(
576 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
578 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
579 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
580 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
581 T: TypeFoldable<'tcx>,
583 use rustc_data_structures::fx::FxHashMap;
585 let mut region_map = BTreeMap::new();
586 let mut type_map = FxHashMap::default();
587 let mut const_map = FxHashMap::default();
589 if !value.has_escaping_bound_vars() {
590 (value.clone(), region_map)
592 let mut real_fld_r = |br| *region_map.entry(br).or_insert_with(|| fld_r(br));
595 |bound_ty| *type_map.entry(bound_ty).or_insert_with(|| fld_t(bound_ty));
598 |bound_ct, ty| *const_map.entry(bound_ct).or_insert_with(|| fld_c(bound_ct, ty));
601 BoundVarReplacer::new(self, &mut real_fld_r, &mut real_fld_t, &mut real_fld_c);
602 let result = value.fold_with(&mut replacer);
607 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
608 /// closure replaces bound regions while the `fld_t` closure replaces bound
610 pub fn replace_bound_vars<T, F, G, H>(
616 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
618 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
619 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
620 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
621 T: TypeFoldable<'tcx>,
623 self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t, fld_c)
626 /// Replaces any late-bound regions bound in `value` with
627 /// free variants attached to `all_outlive_scope`.
628 pub fn liberate_late_bound_regions<T>(self, all_outlive_scope: DefId, value: ty::Binder<T>) -> T
630 T: TypeFoldable<'tcx>,
632 self.replace_late_bound_regions(value, |br| {
633 self.mk_region(ty::ReFree(ty::FreeRegion {
634 scope: all_outlive_scope,
641 /// Returns a set of all late-bound regions that are constrained
642 /// by `value`, meaning that if we instantiate those LBR with
643 /// variables and equate `value` with something else, those
644 /// variables will also be equated.
645 pub fn collect_constrained_late_bound_regions<T>(
648 ) -> FxHashSet<ty::BoundRegion>
650 T: TypeFoldable<'tcx>,
652 self.collect_late_bound_regions(value, true)
655 /// Returns a set of all late-bound regions that appear in `value` anywhere.
656 pub fn collect_referenced_late_bound_regions<T>(
659 ) -> FxHashSet<ty::BoundRegion>
661 T: TypeFoldable<'tcx>,
663 self.collect_late_bound_regions(value, false)
666 fn collect_late_bound_regions<T>(
669 just_constraint: bool,
670 ) -> FxHashSet<ty::BoundRegion>
672 T: TypeFoldable<'tcx>,
674 let mut collector = LateBoundRegionsCollector::new(just_constraint);
675 let result = value.as_ref().skip_binder().visit_with(&mut collector);
676 assert!(result.is_continue()); // should never have stopped early
680 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
681 /// method lookup and a few other places where precise region relationships are not required.
682 pub fn erase_late_bound_regions<T>(self, value: Binder<T>) -> T
684 T: TypeFoldable<'tcx>,
686 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
689 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
690 /// assigned starting at 0 and increasing monotonically in the order traversed
691 /// by the fold operation.
693 /// The chief purpose of this function is to canonicalize regions so that two
694 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
695 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
696 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
697 pub fn anonymize_late_bound_regions<T>(self, sig: Binder<T>) -> Binder<T>
699 T: TypeFoldable<'tcx>,
703 self.replace_late_bound_regions(sig, |_| {
704 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)));
713 ///////////////////////////////////////////////////////////////////////////
716 // Shifts the De Bruijn indices on all escaping bound vars by a
717 // fixed amount. Useful in substitution or when otherwise introducing
718 // a binding level that is not intended to capture the existing bound
719 // vars. See comment on `shift_vars_through_binders` method in
720 // `subst.rs` for more details.
722 struct Shifter<'tcx> {
724 current_index: ty::DebruijnIndex,
729 pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
730 Shifter { tcx, current_index: ty::INNERMOST, amount }
734 impl TypeFolder<'tcx> for Shifter<'tcx> {
735 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
739 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: ty::Binder<T>) -> ty::Binder<T> {
740 self.current_index.shift_in(1);
741 let t = t.super_fold_with(self);
742 self.current_index.shift_out(1);
746 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
748 ty::ReLateBound(debruijn, br) => {
749 if self.amount == 0 || debruijn < self.current_index {
752 let debruijn = debruijn.shifted_in(self.amount);
753 let shifted = ty::ReLateBound(debruijn, br);
754 self.tcx.mk_region(shifted)
761 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
763 ty::Bound(debruijn, bound_ty) => {
764 if self.amount == 0 || debruijn < self.current_index {
767 let debruijn = debruijn.shifted_in(self.amount);
768 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
772 _ => ty.super_fold_with(self),
776 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
777 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct {
778 if self.amount == 0 || debruijn < self.current_index {
781 let debruijn = debruijn.shifted_in(self.amount);
782 self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty })
785 ct.super_fold_with(self)
790 pub fn shift_region<'tcx>(
792 region: ty::Region<'tcx>,
794 ) -> ty::Region<'tcx> {
796 ty::ReLateBound(debruijn, br) if amount > 0 => {
797 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
803 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
805 T: TypeFoldable<'tcx>,
807 debug!("shift_vars(value={:?}, amount={})", value, amount);
809 value.fold_with(&mut Shifter::new(tcx, amount))
812 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
813 /// bound region or a bound type.
815 /// So, for example, consider a type like the following, which has two binders:
817 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
818 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
819 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
821 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
822 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
823 /// fn type*, that type has an escaping region: `'a`.
825 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
826 /// we already use the term "free var". It refers to the regions or types that we use to represent
827 /// bound regions or type params on a fn definition while we are type checking its body.
829 /// To clarify, conceptually there is no particular difference between
830 /// an "escaping" var and a "free" var. However, there is a big
831 /// difference in practice. Basically, when "entering" a binding
832 /// level, one is generally required to do some sort of processing to
833 /// a bound var, such as replacing it with a fresh/placeholder
834 /// var, or making an entry in the environment to represent the
835 /// scope to which it is attached, etc. An escaping var represents
836 /// a bound var for which this processing has not yet been done.
837 struct HasEscapingVarsVisitor {
838 /// Anything bound by `outer_index` or "above" is escaping.
839 outer_index: ty::DebruijnIndex,
842 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
843 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<()> {
844 self.outer_index.shift_in(1);
845 let result = t.super_visit_with(self);
846 self.outer_index.shift_out(1);
850 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<()> {
851 // If the outer-exclusive-binder is *strictly greater* than
852 // `outer_index`, that means that `t` contains some content
853 // bound at `outer_index` or above (because
854 // `outer_exclusive_binder` is always 1 higher than the
855 // content in `t`). Therefore, `t` has some escaping vars.
856 if t.outer_exclusive_binder > self.outer_index {
859 ControlFlow::CONTINUE
863 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<()> {
864 // If the region is bound by `outer_index` or anything outside
865 // of outer index, then it escapes the binders we have
867 if r.bound_at_or_above_binder(self.outer_index) {
870 ControlFlow::CONTINUE
874 fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> ControlFlow<()> {
875 // we don't have a `visit_infer_const` callback, so we have to
876 // hook in here to catch this case (annoying...), but
877 // otherwise we do want to remember to visit the rest of the
878 // const, as it has types/regions embedded in a lot of other
881 ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => ControlFlow::BREAK,
882 _ => ct.super_visit_with(self),
886 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<()> {
887 if predicate.inner.outer_exclusive_binder > self.outer_index {
890 ControlFlow::CONTINUE
895 // FIXME: Optimize for checking for infer flags
896 struct HasTypeFlagsVisitor {
897 flags: ty::TypeFlags,
900 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
901 fn visit_ty(&mut self, t: Ty<'_>) -> ControlFlow<()> {
903 "HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}",
908 if t.flags().intersects(self.flags) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
911 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<()> {
912 let flags = r.type_flags();
913 debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
914 if flags.intersects(self.flags) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
917 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<()> {
918 let flags = FlagComputation::for_const(c);
919 debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
920 if flags.intersects(self.flags) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
923 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<()> {
925 "HasTypeFlagsVisitor: predicate={:?} predicate.flags={:?} self.flags={:?}",
926 predicate, predicate.inner.flags, self.flags
928 if predicate.inner.flags.intersects(self.flags) {
931 ControlFlow::CONTINUE
936 /// Collects all the late-bound regions at the innermost binding level
938 struct LateBoundRegionsCollector {
939 current_index: ty::DebruijnIndex,
940 regions: FxHashSet<ty::BoundRegion>,
942 /// `true` if we only want regions that are known to be
943 /// "constrained" when you equate this type with another type. In
944 /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
945 /// them constraints `'a == 'b`. But if you have `<&'a u32 as
946 /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
947 /// types may mean that `'a` and `'b` don't appear in the results,
948 /// so they are not considered *constrained*.
949 just_constrained: bool,
952 impl LateBoundRegionsCollector {
953 fn new(just_constrained: bool) -> Self {
954 LateBoundRegionsCollector {
955 current_index: ty::INNERMOST,
956 regions: Default::default(),
962 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
963 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<()> {
964 self.current_index.shift_in(1);
965 let result = t.super_visit_with(self);
966 self.current_index.shift_out(1);
970 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<()> {
971 // if we are only looking for "constrained" region, we have to
972 // ignore the inputs to a projection, as they may not appear
973 // in the normalized form
974 if self.just_constrained {
975 if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
976 return ControlFlow::CONTINUE;
980 t.super_visit_with(self)
983 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<()> {
984 // if we are only looking for "constrained" region, we have to
985 // ignore the inputs of an unevaluated const, as they may not appear
986 // in the normalized form
987 if self.just_constrained {
988 if let ty::ConstKind::Unevaluated(..) = c.val {
989 return ControlFlow::CONTINUE;
993 c.super_visit_with(self)
996 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<()> {
997 if let ty::ReLateBound(debruijn, br) = *r {
998 if debruijn == self.current_index {
999 self.regions.insert(br);
1002 ControlFlow::CONTINUE