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 rustc_data_structures::sso::SsoHashSet;
39 use std::collections::BTreeMap;
41 use std::ops::ControlFlow;
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) -> ControlFlow<V::BreakTy>;
54 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
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 }).is_break()
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 }).break_value() == Some(FoundFlags)
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)
148 impl TypeFoldable<'tcx> for hir::Constness {
149 fn super_fold_with<F: TypeFolder<'tcx>>(self, _: &mut F) -> Self {
152 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> ControlFlow<V::BreakTy> {
153 ControlFlow::CONTINUE
157 /// The `TypeFolder` trait defines the actual *folding*. There is a
158 /// method defined for every foldable type. Each of these has a
159 /// default implementation that does an "identity" fold. Within each
160 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
162 pub trait TypeFolder<'tcx>: Sized {
163 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
165 fn fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T>
167 T: TypeFoldable<'tcx>,
169 t.super_fold_with(self)
172 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
173 t.super_fold_with(self)
176 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
177 r.super_fold_with(self)
180 fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
181 c.super_fold_with(self)
185 pub trait TypeVisitor<'tcx>: Sized {
188 fn visit_binder<T: TypeFoldable<'tcx>>(
191 ) -> ControlFlow<Self::BreakTy> {
192 t.super_visit_with(self)
195 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
196 t.super_visit_with(self)
199 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
200 r.super_visit_with(self)
203 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
204 c.super_visit_with(self)
207 fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
208 p.super_visit_with(self)
212 ///////////////////////////////////////////////////////////////////////////
213 // Some sample folders
215 pub struct BottomUpFolder<'tcx, F, G, H>
217 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
218 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
219 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
221 pub tcx: TyCtxt<'tcx>,
227 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
229 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
230 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
231 H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
233 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
237 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
238 let t = ty.super_fold_with(self);
242 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
243 let r = r.super_fold_with(self);
247 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
248 let ct = ct.super_fold_with(self);
253 ///////////////////////////////////////////////////////////////////////////
256 impl<'tcx> TyCtxt<'tcx> {
257 /// Folds the escaping and free regions in `value` using `f`, and
258 /// sets `skipped_regions` to true if any late-bound region was found
260 pub fn fold_regions<T>(
263 skipped_regions: &mut bool,
264 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
267 T: TypeFoldable<'tcx>,
269 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
272 /// Invoke `callback` on every region appearing free in `value`.
273 pub fn for_each_free_region(
275 value: &impl TypeFoldable<'tcx>,
276 mut callback: impl FnMut(ty::Region<'tcx>),
278 self.any_free_region_meets(value, |r| {
284 /// Returns `true` if `callback` returns true for every region appearing free in `value`.
285 pub fn all_free_regions_meet(
287 value: &impl TypeFoldable<'tcx>,
288 mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
290 !self.any_free_region_meets(value, |r| !callback(r))
293 /// Returns `true` if `callback` returns true for some region appearing free in `value`.
294 pub fn any_free_region_meets(
296 value: &impl TypeFoldable<'tcx>,
297 callback: impl FnMut(ty::Region<'tcx>) -> bool,
299 struct RegionVisitor<F> {
300 /// The index of a binder *just outside* the things we have
301 /// traversed. If we encounter a bound region bound by this
302 /// binder or one outer to it, it appears free. Example:
305 /// for<'a> fn(for<'b> fn(), T)
307 /// | | | | here, would be shifted in 1
308 /// | | | here, would be shifted in 2
309 /// | | here, would be `INNERMOST` shifted in by 1
310 /// | here, initially, binder would be `INNERMOST`
313 /// You see that, initially, *any* bound value is free,
314 /// because we've not traversed any binders. As we pass
315 /// through a binder, we shift the `outer_index` by 1 to
316 /// account for the new binder that encloses us.
317 outer_index: ty::DebruijnIndex,
321 impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
323 F: FnMut(ty::Region<'tcx>) -> bool,
327 fn visit_binder<T: TypeFoldable<'tcx>>(
330 ) -> ControlFlow<Self::BreakTy> {
331 self.outer_index.shift_in(1);
332 let result = t.as_ref().skip_binder().visit_with(self);
333 self.outer_index.shift_out(1);
337 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
339 ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
340 ControlFlow::CONTINUE
343 if (self.callback)(r) {
346 ControlFlow::CONTINUE
352 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
353 // We're only interested in types involving regions
354 if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) {
355 ty.super_visit_with(self)
357 ControlFlow::CONTINUE
362 value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback }).is_break()
366 /// Folds over the substructure of a type, visiting its component
367 /// types and all regions that occur *free* within it.
369 /// That is, `Ty` can contain function or method types that bind
370 /// regions at the call site (`ReLateBound`), and occurrences of
371 /// regions (aka "lifetimes") that are bound within a type are not
372 /// visited by this folder; only regions that occur free will be
373 /// visited by `fld_r`.
375 pub struct RegionFolder<'a, 'tcx> {
377 skipped_regions: &'a mut bool,
379 /// Stores the index of a binder *just outside* the stuff we have
380 /// visited. So this begins as INNERMOST; when we pass through a
381 /// binder, it is incremented (via `shift_in`).
382 current_index: ty::DebruijnIndex,
384 /// Callback invokes for each free region. The `DebruijnIndex`
385 /// points to the binder *just outside* the ones we have passed
388 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
391 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
395 skipped_regions: &'a mut bool,
396 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
397 ) -> RegionFolder<'a, 'tcx> {
398 RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
402 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
403 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
407 fn fold_binder<T: TypeFoldable<'tcx>>(
409 t: ty::Binder<'tcx, T>,
410 ) -> ty::Binder<'tcx, T> {
411 self.current_index.shift_in(1);
412 let t = t.super_fold_with(self);
413 self.current_index.shift_out(1);
417 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
419 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
421 "RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
422 r, self.current_index
424 *self.skipped_regions = true;
429 "RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
430 r, self.current_index
432 (self.fold_region_fn)(r, self.current_index)
438 ///////////////////////////////////////////////////////////////////////////
439 // Bound vars replacer
441 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
442 struct BoundVarReplacer<'a, 'tcx> {
445 /// As with `RegionFolder`, represents the index of a binder *just outside*
446 /// the ones we have visited.
447 current_index: ty::DebruijnIndex,
449 fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
450 fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
451 fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a)>,
454 impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
457 fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
458 fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
459 fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a)>,
461 BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
465 impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
466 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
470 fn fold_binder<T: TypeFoldable<'tcx>>(
472 t: ty::Binder<'tcx, T>,
473 ) -> ty::Binder<'tcx, T> {
474 self.current_index.shift_in(1);
475 let t = t.super_fold_with(self);
476 self.current_index.shift_out(1);
480 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
482 ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => {
483 if let Some(fld_t) = self.fld_t.as_mut() {
484 let ty = fld_t(bound_ty);
485 return 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 return t.super_fold_with(self);
496 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
498 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
499 if let Some(fld_r) = self.fld_r.as_mut() {
500 let region = fld_r(br);
501 return if let ty::ReLateBound(debruijn1, br) = *region {
502 // If the callback returns a late-bound region,
503 // that region should always use the INNERMOST
504 // debruijn index. Then we adjust it to the
506 assert_eq!(debruijn1, ty::INNERMOST);
507 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
518 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
520 ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty }
521 if debruijn == self.current_index =>
523 if let Some(fld_c) = self.fld_c.as_mut() {
524 let ct = fld_c(bound_const, ty);
525 return 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 return ct.super_fold_with(self);
537 impl<'tcx> TyCtxt<'tcx> {
538 /// Replaces all regions bound by the given `Binder` with the
539 /// results returned by the closure; the closure is expected to
540 /// return a free region (relative to this binder), and hence the
541 /// binder is removed in the return type. The closure is invoked
542 /// once for each unique `BoundRegionKind`; multiple references to the
543 /// same `BoundRegionKind` will reuse the previous result. A map is
544 /// returned at the end with each bound region and the free region
545 /// that replaced it.
547 /// This method only replaces late bound regions and the result may still
548 /// contain escaping bound types.
549 pub fn replace_late_bound_regions<T, F>(
551 value: Binder<'tcx, T>,
553 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
555 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
556 T: TypeFoldable<'tcx>,
558 let mut region_map = BTreeMap::new();
560 |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
561 let value = value.skip_binder();
562 let value = if !value.has_escaping_bound_vars() {
565 let mut replacer = BoundVarReplacer::new(self, Some(&mut real_fld_r), None, None);
566 value.fold_with(&mut replacer)
571 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
572 /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
573 /// closure replaces escaping bound consts.
574 pub fn replace_escaping_bound_vars<T, F, G, H>(
582 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
583 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
584 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
585 T: TypeFoldable<'tcx>,
587 if !value.has_escaping_bound_vars() {
591 BoundVarReplacer::new(self, Some(&mut fld_r), Some(&mut fld_t), Some(&mut fld_c));
592 value.fold_with(&mut replacer)
596 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
597 /// closure replaces bound regions while the `fld_t` closure replaces bound
599 pub fn replace_bound_vars<T, F, G, H>(
601 value: Binder<'tcx, T>,
605 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
607 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
608 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
609 H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
610 T: TypeFoldable<'tcx>,
612 let mut region_map = BTreeMap::new();
613 let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
614 let value = self.replace_escaping_bound_vars(value.skip_binder(), real_fld_r, fld_t, fld_c);
618 /// Replaces any late-bound regions bound in `value` with
619 /// free variants attached to `all_outlive_scope`.
620 pub fn liberate_late_bound_regions<T>(
622 all_outlive_scope: DefId,
623 value: ty::Binder<'tcx, T>,
626 T: TypeFoldable<'tcx>,
628 self.replace_late_bound_regions(value, |br| {
629 self.mk_region(ty::ReFree(ty::FreeRegion {
630 scope: all_outlive_scope,
631 bound_region: br.kind,
637 pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
639 T: TypeFoldable<'tcx>,
641 self.replace_escaping_bound_vars(
644 self.mk_region(ty::ReLateBound(
647 var: ty::BoundVar::from_usize(r.var.as_usize() + bound_vars),
653 self.mk_ty(ty::Bound(
656 var: ty::BoundVar::from_usize(t.var.as_usize() + bound_vars),
662 self.mk_const(ty::Const {
663 val: ty::ConstKind::Bound(
665 ty::BoundVar::from_usize(c.as_usize() + bound_vars),
673 /// Returns a set of all late-bound regions that are constrained
674 /// by `value`, meaning that if we instantiate those LBR with
675 /// variables and equate `value` with something else, those
676 /// variables will also be equated.
677 pub fn collect_constrained_late_bound_regions<T>(
679 value: &Binder<'tcx, T>,
680 ) -> FxHashSet<ty::BoundRegionKind>
682 T: TypeFoldable<'tcx>,
684 self.collect_late_bound_regions(value, true)
687 /// Returns a set of all late-bound regions that appear in `value` anywhere.
688 pub fn collect_referenced_late_bound_regions<T>(
690 value: &Binder<'tcx, T>,
691 ) -> FxHashSet<ty::BoundRegionKind>
693 T: TypeFoldable<'tcx>,
695 self.collect_late_bound_regions(value, false)
698 fn collect_late_bound_regions<T>(
700 value: &Binder<'tcx, T>,
701 just_constraint: bool,
702 ) -> FxHashSet<ty::BoundRegionKind>
704 T: TypeFoldable<'tcx>,
706 let mut collector = LateBoundRegionsCollector::new(just_constraint);
707 let result = value.as_ref().skip_binder().visit_with(&mut collector);
708 assert!(result.is_continue()); // should never have stopped early
712 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
713 /// method lookup and a few other places where precise region relationships are not required.
714 pub fn erase_late_bound_regions<T>(self, value: Binder<'tcx, T>) -> T
716 T: TypeFoldable<'tcx>,
718 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
721 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
722 /// assigned starting at 0 and increasing monotonically in the order traversed
723 /// by the fold operation.
725 /// The chief purpose of this function is to canonicalize regions so that two
726 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
727 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
728 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
729 pub fn anonymize_late_bound_regions<T>(self, sig: Binder<'tcx, T>) -> Binder<'tcx, T>
731 T: TypeFoldable<'tcx>,
735 .replace_late_bound_regions(sig, |_| {
736 let br = ty::BoundRegion {
737 var: ty::BoundVar::from_u32(counter),
738 kind: ty::BrAnon(counter),
740 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
745 let bound_vars = self.mk_bound_variable_kinds(
746 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
748 Binder::bind_with_vars(inner, bound_vars)
752 pub struct BoundVarsCollector<'tcx> {
753 binder_index: ty::DebruijnIndex,
754 vars: BTreeMap<u32, ty::BoundVariableKind>,
755 // We may encounter the same variable at different levels of binding, so
756 // this can't just be `Ty`
757 visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
760 impl<'tcx> BoundVarsCollector<'tcx> {
761 pub fn new() -> Self {
763 binder_index: ty::INNERMOST,
764 vars: BTreeMap::new(),
765 visited: SsoHashSet::default(),
769 pub fn into_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx ty::List<ty::BoundVariableKind> {
770 let max = self.vars.iter().map(|(k, _)| *k).max().unwrap_or_else(|| 0);
772 if let None = self.vars.get(&i) {
773 panic!("Unknown variable: {:?}", i);
777 tcx.mk_bound_variable_kinds(self.vars.into_iter().map(|(_, v)| v))
781 impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
784 fn visit_binder<T: TypeFoldable<'tcx>>(
787 ) -> ControlFlow<Self::BreakTy> {
788 self.binder_index.shift_in(1);
789 let result = t.super_visit_with(self);
790 self.binder_index.shift_out(1);
794 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
795 if t.outer_exclusive_binder < self.binder_index
796 || !self.visited.insert((self.binder_index, t))
798 return ControlFlow::CONTINUE;
800 use std::collections::btree_map::Entry;
802 ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
803 match self.vars.entry(bound_ty.var.as_u32()) {
804 Entry::Vacant(entry) => {
805 entry.insert(ty::BoundVariableKind::Ty(bound_ty.kind));
807 Entry::Occupied(entry) => match entry.get() {
808 ty::BoundVariableKind::Ty(_) => {}
809 _ => bug!("Conflicting bound vars"),
817 t.super_visit_with(self)
820 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
822 ty::ReLateBound(index, _br) if *index == self.binder_index => {
823 // If you hit this, you should be using `Binder::bind_with_vars` or `Binder::rebind`
824 bug!("Trying to collect bound vars with a bound region: {:?} {:?}", index, _br)
830 r.super_visit_with(self)
834 pub struct ValidateBoundVars<'tcx> {
835 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
836 binder_index: ty::DebruijnIndex,
837 // We may encounter the same variable at different levels of binding, so
838 // this can't just be `Ty`
839 visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
842 impl<'tcx> ValidateBoundVars<'tcx> {
843 pub fn new(bound_vars: &'tcx ty::List<ty::BoundVariableKind>) -> Self {
846 binder_index: ty::INNERMOST,
847 visited: SsoHashSet::default(),
852 impl<'tcx> TypeVisitor<'tcx> for ValidateBoundVars<'tcx> {
855 fn visit_binder<T: TypeFoldable<'tcx>>(
858 ) -> ControlFlow<Self::BreakTy> {
859 self.binder_index.shift_in(1);
860 let result = t.super_visit_with(self);
861 self.binder_index.shift_out(1);
865 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
866 if t.outer_exclusive_binder < self.binder_index
867 || !self.visited.insert((self.binder_index, t))
869 return ControlFlow::BREAK;
872 ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
873 if self.bound_vars.len() <= bound_ty.var.as_usize() {
874 bug!("Not enough bound vars: {:?} not found in {:?}", t, self.bound_vars);
876 let list_var = self.bound_vars[bound_ty.var.as_usize()];
878 ty::BoundVariableKind::Ty(kind) => {
879 if kind != bound_ty.kind {
881 "Mismatched type kinds: {:?} doesn't var in list {:?}",
888 bug!("Mismatched bound variable kinds! Expected type, found {:?}", list_var)
896 t.super_visit_with(self)
899 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
901 ty::ReLateBound(index, br) if *index == self.binder_index => {
902 if self.bound_vars.len() <= br.var.as_usize() {
903 bug!("Not enough bound vars: {:?} not found in {:?}", *br, self.bound_vars);
905 let list_var = self.bound_vars[br.var.as_usize()];
907 ty::BoundVariableKind::Region(kind) => {
910 "Mismatched region kinds: {:?} doesn't match var ({:?}) in list ({:?})",
918 "Mismatched bound variable kinds! Expected region, found {:?}",
927 r.super_visit_with(self)
931 ///////////////////////////////////////////////////////////////////////////
934 // Shifts the De Bruijn indices on all escaping bound vars by a
935 // fixed amount. Useful in substitution or when otherwise introducing
936 // a binding level that is not intended to capture the existing bound
937 // vars. See comment on `shift_vars_through_binders` method in
938 // `subst.rs` for more details.
940 struct Shifter<'tcx> {
942 current_index: ty::DebruijnIndex,
947 pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
948 Shifter { tcx, current_index: ty::INNERMOST, amount }
952 impl TypeFolder<'tcx> for Shifter<'tcx> {
953 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
957 fn fold_binder<T: TypeFoldable<'tcx>>(
959 t: ty::Binder<'tcx, T>,
960 ) -> ty::Binder<'tcx, T> {
961 self.current_index.shift_in(1);
962 let t = t.super_fold_with(self);
963 self.current_index.shift_out(1);
967 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
969 ty::ReLateBound(debruijn, br) => {
970 if self.amount == 0 || debruijn < self.current_index {
973 let debruijn = debruijn.shifted_in(self.amount);
974 let shifted = ty::ReLateBound(debruijn, br);
975 self.tcx.mk_region(shifted)
982 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
984 ty::Bound(debruijn, bound_ty) => {
985 if self.amount == 0 || debruijn < self.current_index {
988 let debruijn = debruijn.shifted_in(self.amount);
989 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
993 _ => ty.super_fold_with(self),
997 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
998 if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct {
999 if self.amount == 0 || debruijn < self.current_index {
1002 let debruijn = debruijn.shifted_in(self.amount);
1003 self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty })
1006 ct.super_fold_with(self)
1011 pub fn shift_region<'tcx>(
1013 region: ty::Region<'tcx>,
1015 ) -> ty::Region<'tcx> {
1017 ty::ReLateBound(debruijn, br) if amount > 0 => {
1018 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
1024 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
1026 T: TypeFoldable<'tcx>,
1028 debug!("shift_vars(value={:?}, amount={})", value, amount);
1030 value.fold_with(&mut Shifter::new(tcx, amount))
1033 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1034 struct FoundEscapingVars;
1036 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
1037 /// bound region or a bound type.
1039 /// So, for example, consider a type like the following, which has two binders:
1041 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
1042 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1043 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
1045 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1046 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1047 /// fn type*, that type has an escaping region: `'a`.
1049 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
1050 /// we already use the term "free var". It refers to the regions or types that we use to represent
1051 /// bound regions or type params on a fn definition while we are type checking its body.
1053 /// To clarify, conceptually there is no particular difference between
1054 /// an "escaping" var and a "free" var. However, there is a big
1055 /// difference in practice. Basically, when "entering" a binding
1056 /// level, one is generally required to do some sort of processing to
1057 /// a bound var, such as replacing it with a fresh/placeholder
1058 /// var, or making an entry in the environment to represent the
1059 /// scope to which it is attached, etc. An escaping var represents
1060 /// a bound var for which this processing has not yet been done.
1061 struct HasEscapingVarsVisitor {
1062 /// Anything bound by `outer_index` or "above" is escaping.
1063 outer_index: ty::DebruijnIndex,
1066 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
1067 type BreakTy = FoundEscapingVars;
1069 fn visit_binder<T: TypeFoldable<'tcx>>(
1071 t: &Binder<'tcx, T>,
1072 ) -> ControlFlow<Self::BreakTy> {
1073 self.outer_index.shift_in(1);
1074 let result = t.super_visit_with(self);
1075 self.outer_index.shift_out(1);
1080 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1081 // If the outer-exclusive-binder is *strictly greater* than
1082 // `outer_index`, that means that `t` contains some content
1083 // bound at `outer_index` or above (because
1084 // `outer_exclusive_binder` is always 1 higher than the
1085 // content in `t`). Therefore, `t` has some escaping vars.
1086 if t.outer_exclusive_binder > self.outer_index {
1087 ControlFlow::Break(FoundEscapingVars)
1089 ControlFlow::CONTINUE
1094 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1095 // If the region is bound by `outer_index` or anything outside
1096 // of outer index, then it escapes the binders we have
1098 if r.bound_at_or_above_binder(self.outer_index) {
1099 ControlFlow::Break(FoundEscapingVars)
1101 ControlFlow::CONTINUE
1105 fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1106 // we don't have a `visit_infer_const` callback, so we have to
1107 // hook in here to catch this case (annoying...), but
1108 // otherwise we do want to remember to visit the rest of the
1109 // const, as it has types/regions embedded in a lot of other
1112 ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => {
1113 ControlFlow::Break(FoundEscapingVars)
1115 _ => ct.super_visit_with(self),
1120 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1121 if predicate.inner.outer_exclusive_binder > self.outer_index {
1122 ControlFlow::Break(FoundEscapingVars)
1124 ControlFlow::CONTINUE
1129 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1132 // FIXME: Optimize for checking for infer flags
1133 struct HasTypeFlagsVisitor {
1134 flags: ty::TypeFlags,
1137 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
1138 type BreakTy = FoundFlags;
1141 fn visit_ty(&mut self, t: Ty<'_>) -> ControlFlow<Self::BreakTy> {
1143 "HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}",
1148 if t.flags().intersects(self.flags) {
1149 ControlFlow::Break(FoundFlags)
1151 ControlFlow::CONTINUE
1156 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1157 let flags = r.type_flags();
1158 debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
1159 if flags.intersects(self.flags) {
1160 ControlFlow::Break(FoundFlags)
1162 ControlFlow::CONTINUE
1167 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1168 let flags = FlagComputation::for_const(c);
1169 debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
1170 if flags.intersects(self.flags) {
1171 ControlFlow::Break(FoundFlags)
1173 ControlFlow::CONTINUE
1178 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1180 "HasTypeFlagsVisitor: predicate={:?} predicate.flags={:?} self.flags={:?}",
1181 predicate, predicate.inner.flags, self.flags
1183 if predicate.inner.flags.intersects(self.flags) {
1184 ControlFlow::Break(FoundFlags)
1186 ControlFlow::CONTINUE
1191 /// Collects all the late-bound regions at the innermost binding level
1192 /// into a hash set.
1193 struct LateBoundRegionsCollector {
1194 current_index: ty::DebruijnIndex,
1195 regions: FxHashSet<ty::BoundRegionKind>,
1197 /// `true` if we only want regions that are known to be
1198 /// "constrained" when you equate this type with another type. In
1199 /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
1200 /// them constraints `'a == 'b`. But if you have `<&'a u32 as
1201 /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
1202 /// types may mean that `'a` and `'b` don't appear in the results,
1203 /// so they are not considered *constrained*.
1204 just_constrained: bool,
1207 impl LateBoundRegionsCollector {
1208 fn new(just_constrained: bool) -> Self {
1209 LateBoundRegionsCollector {
1210 current_index: ty::INNERMOST,
1211 regions: Default::default(),
1217 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
1218 fn visit_binder<T: TypeFoldable<'tcx>>(
1220 t: &Binder<'tcx, T>,
1221 ) -> ControlFlow<Self::BreakTy> {
1222 self.current_index.shift_in(1);
1223 let result = t.super_visit_with(self);
1224 self.current_index.shift_out(1);
1228 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1229 // if we are only looking for "constrained" region, we have to
1230 // ignore the inputs to a projection, as they may not appear
1231 // in the normalized form
1232 if self.just_constrained {
1233 if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
1234 return ControlFlow::CONTINUE;
1238 t.super_visit_with(self)
1241 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1242 // if we are only looking for "constrained" region, we have to
1243 // ignore the inputs of an unevaluated const, as they may not appear
1244 // in the normalized form
1245 if self.just_constrained {
1246 if let ty::ConstKind::Unevaluated(..) = c.val {
1247 return ControlFlow::CONTINUE;
1251 c.super_visit_with(self)
1254 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1255 if let ty::ReLateBound(debruijn, br) = *r {
1256 if debruijn == self.current_index {
1257 self.regions.insert(br.kind);
1260 ControlFlow::CONTINUE