1 //! A generalized traversal mechanism for complex data structures that contain
4 //! There are two types of traversal.
5 //! - Folding. This is a modifying traversal. It consumes the data structure,
6 //! producing a (possibly) modified version of it. Both fallible and
7 //! infallible versions are available. The name is potentially
8 //! confusing, because this traversal is more like `Iterator::map` than
10 //! - Visiting. This is a read-only traversal of the data structure.
12 //! These traversals have limited flexibility. Only a small number of "types of
13 //! interest" within the complex data structures can receive custom
14 //! modification (when folding) or custom visitation (when visiting). These are
15 //! the ones containing the most important type-related information, such as
16 //! `Ty`, `Predicate`, `Region`, and `Const`.
18 //! There are two traits involved in each traversal type.
19 //! - The first trait is `TypeFoldable`, which is implemented once for many
20 //! types. This includes both (a) types of interest, and (b) all other
21 //! relevant types, including generic containers like `Vec` and `Option`. It
22 //! defines a "skeleton" of how they should be traversed, for both folding
24 //! - The second trait is `TypeFolder`/`FallibleTypeFolder` (for
25 //! infallible/fallible folding traversals) or `TypeVisitor` (for visiting
26 //! traversals). One of these is implemented for each folder/visitor. This
27 //! defines how types of interest are handled.
29 //! This means each traversal is a mixture of (a) generic traversal operations,
30 //! and (b) custom fold/visit operations that are specific to the
32 //! - The `TypeFoldable` impls handle most of the traversal, and call into
33 //! `TypeFolder`/`FallibleTypeFolder`/`TypeVisitor` when they encounter a
35 //! - A `TypeFolder`/`FallibleTypeFolder`/`TypeVisitor` may also call back into
36 //! a `TypeFoldable` impl, because (a) the types of interest are recursive
37 //! and can contain other types of interest, and (b) each folder/visitor
38 //! might provide custom handling only for some types of interest, or only
39 //! for some variants of each type of interest, and then use default
40 //! traversal for the remaining cases.
42 //! For example, if you have `struct S(Ty, U)` where `S: TypeFoldable` and `U:
43 //! TypeFoldable`, and an instance `S(ty, u)`, it would be visited like so:
45 //! s.visit_with(visitor) calls
46 //! - s.super_visit_with(visitor) calls
47 //! - ty.visit_with(visitor) calls
48 //! - visitor.visit_ty(ty) may call
49 //! - ty.super_visit_with(visitor)
50 //! - u.visit_with(visitor)
53 use crate::ty::{self, flags::FlagComputation, Binder, Ty, TyCtxt, TypeFlags};
54 use rustc_hir::def_id::DefId;
56 use rustc_data_structures::fx::FxHashSet;
57 use rustc_data_structures::sso::SsoHashSet;
58 use std::collections::BTreeMap;
60 use std::ops::ControlFlow;
62 /// This trait is implemented for every type that can be folded/visited,
63 /// providing the skeleton of the traversal.
65 /// To implement this conveniently, use the derive macro located in
67 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
68 /// The main entry point for folding. To fold a value `t` with a folder `f`
69 /// call: `t.try_fold_with(f)`.
71 /// For types of interest (such as `Ty`), this default is overridden with a
72 /// method that calls a folder method specifically for that type (such as
73 /// `F::try_fold_ty`). This is where control transfers from `TypeFoldable`
76 /// For other types, this default is used.
77 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
78 self.try_super_fold_with(folder)
81 /// A convenient alternative to `try_fold_with` for use with infallible
82 /// folders. Do not override this method, to ensure coherence with
84 fn fold_with<F: TypeFolder<'tcx, Error = !>>(self, folder: &mut F) -> Self {
85 self.try_fold_with(folder).into_ok()
88 /// Traverses the type in question, typically by calling `try_fold_with` on
89 /// each field/element. This is true even for types of interest such as
90 /// `Ty`. This should only be called within `TypeFolder` methods, when
91 /// non-custom traversals are desired for types of interest.
92 fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
95 ) -> Result<Self, F::Error>;
97 /// A convenient alternative to `try_super_fold_with` for use with
98 /// infallible folders. Do not override this method, to ensure coherence
99 /// with `try_super_fold_with`.
100 fn super_fold_with<F: TypeFolder<'tcx, Error = !>>(self, folder: &mut F) -> Self {
101 self.try_super_fold_with(folder).into_ok()
104 /// The entry point for visiting. To visit a value `t` with a visitor `v`
105 /// call: `t.visit_with(v)`.
107 /// For types of interest (such as `Ty`), this default is overridden with a
108 /// method that calls a visitor method specifically for that type (such as
109 /// `V::visit_ty`). This is where control transfers from `TypeFoldable` to
112 /// For other types, this default is used.
113 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
114 self.super_visit_with(visitor)
117 /// Traverses the type in question, typically by calling `visit_with` on
118 /// each field/element. This is true even for types of interest such as
119 /// `Ty`. This should only be called within `TypeVisitor` methods, when
120 /// non-custom traversals are desired for types of interest.
121 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy>;
123 /// Returns `true` if `self` has any late-bound regions that are either
124 /// bound by `binder` or bound by some binder outside of `binder`.
125 /// If `binder` is `ty::INNERMOST`, this indicates whether
126 /// there are any late-bound regions that appear free.
127 fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
128 self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder }).is_break()
131 /// Returns `true` if this `self` has any regions that escape `binder` (and
132 /// hence are not bound by it).
133 fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
134 self.has_vars_bound_at_or_above(binder.shifted_in(1))
137 fn has_escaping_bound_vars(&self) -> bool {
138 self.has_vars_bound_at_or_above(ty::INNERMOST)
141 #[instrument(level = "trace")]
142 fn has_type_flags(&self, flags: TypeFlags) -> bool {
143 self.visit_with(&mut HasTypeFlagsVisitor { flags }).break_value() == Some(FoundFlags)
145 fn has_projections(&self) -> bool {
146 self.has_type_flags(TypeFlags::HAS_PROJECTION)
148 fn has_opaque_types(&self) -> bool {
149 self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
151 fn references_error(&self) -> bool {
152 self.has_type_flags(TypeFlags::HAS_ERROR)
154 fn has_param_types_or_consts(&self) -> bool {
155 self.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_CT_PARAM)
157 fn has_infer_regions(&self) -> bool {
158 self.has_type_flags(TypeFlags::HAS_RE_INFER)
160 fn has_infer_types(&self) -> bool {
161 self.has_type_flags(TypeFlags::HAS_TY_INFER)
163 fn has_infer_types_or_consts(&self) -> bool {
164 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER)
166 fn needs_infer(&self) -> bool {
167 self.has_type_flags(TypeFlags::NEEDS_INFER)
169 fn has_placeholders(&self) -> bool {
171 TypeFlags::HAS_RE_PLACEHOLDER
172 | TypeFlags::HAS_TY_PLACEHOLDER
173 | TypeFlags::HAS_CT_PLACEHOLDER,
176 fn needs_subst(&self) -> bool {
177 self.has_type_flags(TypeFlags::NEEDS_SUBST)
179 /// "Free" regions in this context means that it has any region
180 /// that is not (a) erased or (b) late-bound.
181 fn has_free_regions(&self) -> bool {
182 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
185 fn has_erased_regions(&self) -> bool {
186 self.has_type_flags(TypeFlags::HAS_RE_ERASED)
189 /// True if there are any un-erased free regions.
190 fn has_erasable_regions(&self) -> bool {
191 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
194 /// Indicates whether this value references only 'global'
195 /// generic parameters that are the same regardless of what fn we are
196 /// in. This is used for caching.
197 fn is_global(&self) -> bool {
198 !self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
201 /// True if there are any late-bound regions
202 fn has_late_bound_regions(&self) -> bool {
203 self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
206 /// Indicates whether this value still has parameters/placeholders/inference variables
207 /// which could be replaced later, in a way that would change the results of `impl`
209 fn still_further_specializable(&self) -> bool {
210 self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
214 /// This trait is implemented for every folding traversal. There is a fold
215 /// method defined for every type of interest. Each such method has a default
216 /// that does an "identity" fold.
218 /// If this folder is fallible (and therefore its [`Error`][`TypeFolder::Error`]
219 /// associated type is something other than the default `!`) then
220 /// [`FallibleTypeFolder`] should be implemented manually. Otherwise,
221 /// a blanket implementation of [`FallibleTypeFolder`] will defer to
222 /// the infallible methods of this trait to ensure that the two APIs
224 pub trait TypeFolder<'tcx>: Sized {
227 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
229 fn fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T>
231 T: TypeFoldable<'tcx>,
232 Self: TypeFolder<'tcx, Error = !>,
234 t.super_fold_with(self)
237 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx>
239 Self: TypeFolder<'tcx, Error = !>,
241 t.super_fold_with(self)
244 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx>
246 Self: TypeFolder<'tcx, Error = !>,
248 r.super_fold_with(self)
251 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx>
253 Self: TypeFolder<'tcx, Error = !>,
255 c.super_fold_with(self)
258 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx>
260 Self: TypeFolder<'tcx, Error = !>,
262 p.super_fold_with(self)
265 fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx>
267 Self: TypeFolder<'tcx, Error = !>,
269 bug!("most type folders should not be folding MIR datastructures: {:?}", c)
273 /// This trait is implemented for every folding traversal. There is a fold
274 /// method defined for every type of interest. Each such method has a default
275 /// that does an "identity" fold.
277 /// A blanket implementation of this trait (that defers to the relevant
278 /// method of [`TypeFolder`]) is provided for all infallible folders in
279 /// order to ensure the two APIs are coherent.
280 pub trait FallibleTypeFolder<'tcx>: TypeFolder<'tcx> {
281 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
283 T: TypeFoldable<'tcx>,
285 t.try_super_fold_with(self)
288 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
289 t.try_super_fold_with(self)
292 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
293 r.try_super_fold_with(self)
296 fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
297 c.try_super_fold_with(self)
300 fn try_fold_predicate(
302 p: ty::Predicate<'tcx>,
303 ) -> Result<ty::Predicate<'tcx>, Self::Error> {
304 p.try_super_fold_with(self)
307 fn try_fold_mir_const(
309 c: mir::ConstantKind<'tcx>,
310 ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
311 bug!("most type folders should not be folding MIR datastructures: {:?}", c)
315 // This blanket implementation of the fallible trait for infallible folders
316 // delegates to infallible methods to ensure coherence.
317 impl<'tcx, F> FallibleTypeFolder<'tcx> for F
319 F: TypeFolder<'tcx, Error = !>,
321 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
323 T: TypeFoldable<'tcx>,
325 Ok(self.fold_binder(t))
328 fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
332 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
333 Ok(self.fold_region(r))
336 fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
337 Ok(self.fold_const(c))
340 fn try_fold_predicate(
342 p: ty::Predicate<'tcx>,
343 ) -> Result<ty::Predicate<'tcx>, Self::Error> {
344 Ok(self.fold_predicate(p))
347 fn try_fold_mir_const(
349 c: mir::ConstantKind<'tcx>,
350 ) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
351 Ok(self.fold_mir_const(c))
355 /// This trait is implemented for every visiting traversal. There is a visit
356 /// method defined for every type of interest. Each such method has a default
357 /// that recurses into the type's fields in a non-custom fashion.
358 pub trait TypeVisitor<'tcx>: Sized {
361 fn visit_binder<T: TypeFoldable<'tcx>>(
364 ) -> ControlFlow<Self::BreakTy> {
365 t.super_visit_with(self)
368 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
369 t.super_visit_with(self)
372 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
373 r.super_visit_with(self)
376 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
377 c.super_visit_with(self)
380 fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow<Self::BreakTy> {
381 uv.super_visit_with(self)
384 fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
385 p.super_visit_with(self)
389 ///////////////////////////////////////////////////////////////////////////
390 // Some sample folders
392 pub struct BottomUpFolder<'tcx, F, G, H>
394 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
395 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
396 H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
398 pub tcx: TyCtxt<'tcx>,
404 impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
406 F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
407 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
408 H: FnMut(ty::Const<'tcx>) -> ty::Const<'tcx>,
410 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
414 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
415 let t = ty.super_fold_with(self);
419 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
420 let r = r.super_fold_with(self);
424 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
425 let ct = ct.super_fold_with(self);
430 ///////////////////////////////////////////////////////////////////////////
433 impl<'tcx> TyCtxt<'tcx> {
434 /// Folds the escaping and free regions in `value` using `f`, and
435 /// sets `skipped_regions` to true if any late-bound region was found
437 pub fn fold_regions<T>(
440 skipped_regions: &mut bool,
441 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
444 T: TypeFoldable<'tcx>,
446 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
449 /// Invoke `callback` on every region appearing free in `value`.
450 pub fn for_each_free_region(
452 value: &impl TypeFoldable<'tcx>,
453 mut callback: impl FnMut(ty::Region<'tcx>),
455 self.any_free_region_meets(value, |r| {
461 /// Returns `true` if `callback` returns true for every region appearing free in `value`.
462 pub fn all_free_regions_meet(
464 value: &impl TypeFoldable<'tcx>,
465 mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
467 !self.any_free_region_meets(value, |r| !callback(r))
470 /// Returns `true` if `callback` returns true for some region appearing free in `value`.
471 pub fn any_free_region_meets(
473 value: &impl TypeFoldable<'tcx>,
474 callback: impl FnMut(ty::Region<'tcx>) -> bool,
476 struct RegionVisitor<F> {
477 /// The index of a binder *just outside* the things we have
478 /// traversed. If we encounter a bound region bound by this
479 /// binder or one outer to it, it appears free. Example:
482 /// for<'a> fn(for<'b> fn(), T)
484 /// | | | | here, would be shifted in 1
485 /// | | | here, would be shifted in 2
486 /// | | here, would be `INNERMOST` shifted in by 1
487 /// | here, initially, binder would be `INNERMOST`
490 /// You see that, initially, *any* bound value is free,
491 /// because we've not traversed any binders. As we pass
492 /// through a binder, we shift the `outer_index` by 1 to
493 /// account for the new binder that encloses us.
494 outer_index: ty::DebruijnIndex,
498 impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
500 F: FnMut(ty::Region<'tcx>) -> bool,
504 fn visit_binder<T: TypeFoldable<'tcx>>(
507 ) -> ControlFlow<Self::BreakTy> {
508 self.outer_index.shift_in(1);
509 let result = t.as_ref().skip_binder().visit_with(self);
510 self.outer_index.shift_out(1);
514 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
516 ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
517 ControlFlow::CONTINUE
520 if (self.callback)(r) {
523 ControlFlow::CONTINUE
529 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
530 // We're only interested in types involving regions
531 if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) {
532 ty.super_visit_with(self)
534 ControlFlow::CONTINUE
539 value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback }).is_break()
543 /// Folds over the substructure of a type, visiting its component
544 /// types and all regions that occur *free* within it.
546 /// That is, `Ty` can contain function or method types that bind
547 /// regions at the call site (`ReLateBound`), and occurrences of
548 /// regions (aka "lifetimes") that are bound within a type are not
549 /// visited by this folder; only regions that occur free will be
550 /// visited by `fld_r`.
552 pub struct RegionFolder<'a, 'tcx> {
554 skipped_regions: &'a mut bool,
556 /// Stores the index of a binder *just outside* the stuff we have
557 /// visited. So this begins as INNERMOST; when we pass through a
558 /// binder, it is incremented (via `shift_in`).
559 current_index: ty::DebruijnIndex,
561 /// Callback invokes for each free region. The `DebruijnIndex`
562 /// points to the binder *just outside* the ones we have passed
565 &'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
568 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
572 skipped_regions: &'a mut bool,
573 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
574 ) -> RegionFolder<'a, 'tcx> {
575 RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
579 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
580 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
584 fn fold_binder<T: TypeFoldable<'tcx>>(
586 t: ty::Binder<'tcx, T>,
587 ) -> ty::Binder<'tcx, T> {
588 self.current_index.shift_in(1);
589 let t = t.super_fold_with(self);
590 self.current_index.shift_out(1);
594 #[instrument(skip(self), level = "debug")]
595 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
597 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
598 debug!(?self.current_index, "skipped bound region");
599 *self.skipped_regions = true;
603 debug!(?self.current_index, "folding free region");
604 (self.fold_region_fn)(r, self.current_index)
610 ///////////////////////////////////////////////////////////////////////////
611 // Bound vars replacer
613 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
614 struct BoundVarReplacer<'a, 'tcx> {
617 /// As with `RegionFolder`, represents the index of a binder *just outside*
618 /// the ones we have visited.
619 current_index: ty::DebruijnIndex,
621 fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
622 fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
623 fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx> + 'a)>,
626 impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
629 fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>,
630 fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>,
631 fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx> + 'a)>,
633 BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
637 impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
638 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
642 fn fold_binder<T: TypeFoldable<'tcx>>(
644 t: ty::Binder<'tcx, T>,
645 ) -> ty::Binder<'tcx, T> {
646 self.current_index.shift_in(1);
647 let t = t.super_fold_with(self);
648 self.current_index.shift_out(1);
652 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
654 ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => {
655 if let Some(fld_t) = self.fld_t.as_mut() {
656 let ty = fld_t(bound_ty);
657 return ty::fold::shift_vars(self.tcx, ty, self.current_index.as_u32());
660 _ if t.has_vars_bound_at_or_above(self.current_index) => {
661 return t.super_fold_with(self);
668 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
670 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
671 if let Some(fld_r) = self.fld_r.as_mut() {
672 let region = fld_r(br);
673 return if let ty::ReLateBound(debruijn1, br) = *region {
674 // If the callback returns a late-bound region,
675 // that region should always use the INNERMOST
676 // debruijn index. Then we adjust it to the
678 assert_eq!(debruijn1, ty::INNERMOST);
679 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
690 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
692 ty::ConstKind::Bound(debruijn, bound_const) if debruijn == self.current_index => {
693 if let Some(fld_c) = self.fld_c.as_mut() {
694 let ct = fld_c(bound_const, ct.ty());
695 return ty::fold::shift_vars(self.tcx, ct, self.current_index.as_u32());
698 _ if ct.has_vars_bound_at_or_above(self.current_index) => {
699 return ct.super_fold_with(self);
707 impl<'tcx> TyCtxt<'tcx> {
708 /// Replaces all regions bound by the given `Binder` with the
709 /// results returned by the closure; the closure is expected to
710 /// return a free region (relative to this binder), and hence the
711 /// binder is removed in the return type. The closure is invoked
712 /// once for each unique `BoundRegionKind`; multiple references to the
713 /// same `BoundRegionKind` will reuse the previous result. A map is
714 /// returned at the end with each bound region and the free region
715 /// that replaced it.
717 /// This method only replaces late bound regions and the result may still
718 /// contain escaping bound types.
719 pub fn replace_late_bound_regions<T, F>(
721 value: Binder<'tcx, T>,
723 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
725 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
726 T: TypeFoldable<'tcx>,
728 let mut region_map = BTreeMap::new();
730 |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
731 let value = value.skip_binder();
732 let value = if !value.has_escaping_bound_vars() {
735 let mut replacer = BoundVarReplacer::new(self, Some(&mut real_fld_r), None, None);
736 value.fold_with(&mut replacer)
741 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
742 /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
743 /// closure replaces escaping bound consts.
744 pub fn replace_escaping_bound_vars<T, F, G, H>(
752 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
753 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
754 H: FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx>,
755 T: TypeFoldable<'tcx>,
757 if !value.has_escaping_bound_vars() {
761 BoundVarReplacer::new(self, Some(&mut fld_r), Some(&mut fld_t), Some(&mut fld_c));
762 value.fold_with(&mut replacer)
766 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
767 /// closure replaces bound regions while the `fld_t` closure replaces bound
769 pub fn replace_bound_vars<T, F, G, H>(
771 value: Binder<'tcx, T>,
775 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
777 F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
778 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
779 H: FnMut(ty::BoundVar, Ty<'tcx>) -> ty::Const<'tcx>,
780 T: TypeFoldable<'tcx>,
782 let mut region_map = BTreeMap::new();
783 let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br));
784 let value = self.replace_escaping_bound_vars(value.skip_binder(), real_fld_r, fld_t, fld_c);
788 /// Replaces any late-bound regions bound in `value` with
789 /// free variants attached to `all_outlive_scope`.
790 pub fn liberate_late_bound_regions<T>(
792 all_outlive_scope: DefId,
793 value: ty::Binder<'tcx, T>,
796 T: TypeFoldable<'tcx>,
798 self.replace_late_bound_regions(value, |br| {
799 self.mk_region(ty::ReFree(ty::FreeRegion {
800 scope: all_outlive_scope,
801 bound_region: br.kind,
807 pub fn shift_bound_var_indices<T>(self, bound_vars: usize, value: T) -> T
809 T: TypeFoldable<'tcx>,
811 self.replace_escaping_bound_vars(
814 self.mk_region(ty::ReLateBound(
817 var: ty::BoundVar::from_usize(r.var.as_usize() + bound_vars),
823 self.mk_ty(ty::Bound(
826 var: ty::BoundVar::from_usize(t.var.as_usize() + bound_vars),
832 self.mk_const(ty::ConstS {
833 val: ty::ConstKind::Bound(
835 ty::BoundVar::from_usize(c.as_usize() + bound_vars),
843 /// Returns a set of all late-bound regions that are constrained
844 /// by `value`, meaning that if we instantiate those LBR with
845 /// variables and equate `value` with something else, those
846 /// variables will also be equated.
847 pub fn collect_constrained_late_bound_regions<T>(
849 value: &Binder<'tcx, T>,
850 ) -> FxHashSet<ty::BoundRegionKind>
852 T: TypeFoldable<'tcx>,
854 self.collect_late_bound_regions(value, true)
857 /// Returns a set of all late-bound regions that appear in `value` anywhere.
858 pub fn collect_referenced_late_bound_regions<T>(
860 value: &Binder<'tcx, T>,
861 ) -> FxHashSet<ty::BoundRegionKind>
863 T: TypeFoldable<'tcx>,
865 self.collect_late_bound_regions(value, false)
868 fn collect_late_bound_regions<T>(
870 value: &Binder<'tcx, T>,
871 just_constraint: bool,
872 ) -> FxHashSet<ty::BoundRegionKind>
874 T: TypeFoldable<'tcx>,
876 let mut collector = LateBoundRegionsCollector::new(just_constraint);
877 let result = value.as_ref().skip_binder().visit_with(&mut collector);
878 assert!(result.is_continue()); // should never have stopped early
882 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
883 /// method lookup and a few other places where precise region relationships are not required.
884 pub fn erase_late_bound_regions<T>(self, value: Binder<'tcx, T>) -> T
886 T: TypeFoldable<'tcx>,
888 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
891 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
892 /// assigned starting at 0 and increasing monotonically in the order traversed
893 /// by the fold operation.
895 /// The chief purpose of this function is to canonicalize regions so that two
896 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
897 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
898 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
899 pub fn anonymize_late_bound_regions<T>(self, sig: Binder<'tcx, T>) -> Binder<'tcx, T>
901 T: TypeFoldable<'tcx>,
905 .replace_late_bound_regions(sig, |_| {
906 let br = ty::BoundRegion {
907 var: ty::BoundVar::from_u32(counter),
908 kind: ty::BrAnon(counter),
910 let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br));
915 let bound_vars = self.mk_bound_variable_kinds(
916 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
918 Binder::bind_with_vars(inner, bound_vars)
922 pub struct ValidateBoundVars<'tcx> {
923 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
924 binder_index: ty::DebruijnIndex,
925 // We may encounter the same variable at different levels of binding, so
926 // this can't just be `Ty`
927 visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
930 impl<'tcx> ValidateBoundVars<'tcx> {
931 pub fn new(bound_vars: &'tcx ty::List<ty::BoundVariableKind>) -> Self {
934 binder_index: ty::INNERMOST,
935 visited: SsoHashSet::default(),
940 impl<'tcx> TypeVisitor<'tcx> for ValidateBoundVars<'tcx> {
943 fn visit_binder<T: TypeFoldable<'tcx>>(
946 ) -> ControlFlow<Self::BreakTy> {
947 self.binder_index.shift_in(1);
948 let result = t.super_visit_with(self);
949 self.binder_index.shift_out(1);
953 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
954 if t.outer_exclusive_binder() < self.binder_index
955 || !self.visited.insert((self.binder_index, t))
957 return ControlFlow::BREAK;
960 ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
961 if self.bound_vars.len() <= bound_ty.var.as_usize() {
962 bug!("Not enough bound vars: {:?} not found in {:?}", t, self.bound_vars);
964 let list_var = self.bound_vars[bound_ty.var.as_usize()];
966 ty::BoundVariableKind::Ty(kind) => {
967 if kind != bound_ty.kind {
969 "Mismatched type kinds: {:?} doesn't var in list {:?}",
976 bug!("Mismatched bound variable kinds! Expected type, found {:?}", list_var)
984 t.super_visit_with(self)
987 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
989 ty::ReLateBound(index, br) if index == self.binder_index => {
990 if self.bound_vars.len() <= br.var.as_usize() {
991 bug!("Not enough bound vars: {:?} not found in {:?}", br, self.bound_vars);
993 let list_var = self.bound_vars[br.var.as_usize()];
995 ty::BoundVariableKind::Region(kind) => {
998 "Mismatched region kinds: {:?} doesn't match var ({:?}) in list ({:?})",
1006 "Mismatched bound variable kinds! Expected region, found {:?}",
1015 r.super_visit_with(self)
1019 ///////////////////////////////////////////////////////////////////////////
1022 // Shifts the De Bruijn indices on all escaping bound vars by a
1023 // fixed amount. Useful in substitution or when otherwise introducing
1024 // a binding level that is not intended to capture the existing bound
1025 // vars. See comment on `shift_vars_through_binders` method in
1026 // `subst.rs` for more details.
1028 struct Shifter<'tcx> {
1030 current_index: ty::DebruijnIndex,
1034 impl<'tcx> Shifter<'tcx> {
1035 pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
1036 Shifter { tcx, current_index: ty::INNERMOST, amount }
1040 impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> {
1041 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1045 fn fold_binder<T: TypeFoldable<'tcx>>(
1047 t: ty::Binder<'tcx, T>,
1048 ) -> ty::Binder<'tcx, T> {
1049 self.current_index.shift_in(1);
1050 let t = t.super_fold_with(self);
1051 self.current_index.shift_out(1);
1055 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1057 ty::ReLateBound(debruijn, br) => {
1058 if self.amount == 0 || debruijn < self.current_index {
1061 let debruijn = debruijn.shifted_in(self.amount);
1062 let shifted = ty::ReLateBound(debruijn, br);
1063 self.tcx.mk_region(shifted)
1070 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1072 ty::Bound(debruijn, bound_ty) => {
1073 if self.amount == 0 || debruijn < self.current_index {
1076 let debruijn = debruijn.shifted_in(self.amount);
1077 self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
1081 _ => ty.super_fold_with(self),
1085 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1086 if let ty::ConstKind::Bound(debruijn, bound_ct) = ct.val() {
1087 if self.amount == 0 || debruijn < self.current_index {
1090 let debruijn = debruijn.shifted_in(self.amount);
1091 self.tcx.mk_const(ty::ConstS {
1092 val: ty::ConstKind::Bound(debruijn, bound_ct),
1097 ct.super_fold_with(self)
1102 pub fn shift_region<'tcx>(
1104 region: ty::Region<'tcx>,
1106 ) -> ty::Region<'tcx> {
1108 ty::ReLateBound(debruijn, br) if amount > 0 => {
1109 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), br))
1115 pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T
1117 T: TypeFoldable<'tcx>,
1119 debug!("shift_vars(value={:?}, amount={})", value, amount);
1121 value.fold_with(&mut Shifter::new(tcx, amount))
1124 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1125 struct FoundEscapingVars;
1127 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
1128 /// bound region or a bound type.
1130 /// So, for example, consider a type like the following, which has two binders:
1132 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
1133 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1134 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
1136 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1137 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1138 /// fn type*, that type has an escaping region: `'a`.
1140 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
1141 /// we already use the term "free var". It refers to the regions or types that we use to represent
1142 /// bound regions or type params on a fn definition while we are type checking its body.
1144 /// To clarify, conceptually there is no particular difference between
1145 /// an "escaping" var and a "free" var. However, there is a big
1146 /// difference in practice. Basically, when "entering" a binding
1147 /// level, one is generally required to do some sort of processing to
1148 /// a bound var, such as replacing it with a fresh/placeholder
1149 /// var, or making an entry in the environment to represent the
1150 /// scope to which it is attached, etc. An escaping var represents
1151 /// a bound var for which this processing has not yet been done.
1152 struct HasEscapingVarsVisitor {
1153 /// Anything bound by `outer_index` or "above" is escaping.
1154 outer_index: ty::DebruijnIndex,
1157 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
1158 type BreakTy = FoundEscapingVars;
1160 fn visit_binder<T: TypeFoldable<'tcx>>(
1162 t: &Binder<'tcx, T>,
1163 ) -> ControlFlow<Self::BreakTy> {
1164 self.outer_index.shift_in(1);
1165 let result = t.super_visit_with(self);
1166 self.outer_index.shift_out(1);
1171 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1172 // If the outer-exclusive-binder is *strictly greater* than
1173 // `outer_index`, that means that `t` contains some content
1174 // bound at `outer_index` or above (because
1175 // `outer_exclusive_binder` is always 1 higher than the
1176 // content in `t`). Therefore, `t` has some escaping vars.
1177 if t.outer_exclusive_binder() > self.outer_index {
1178 ControlFlow::Break(FoundEscapingVars)
1180 ControlFlow::CONTINUE
1185 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1186 // If the region is bound by `outer_index` or anything outside
1187 // of outer index, then it escapes the binders we have
1189 if r.bound_at_or_above_binder(self.outer_index) {
1190 ControlFlow::Break(FoundEscapingVars)
1192 ControlFlow::CONTINUE
1196 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1197 // we don't have a `visit_infer_const` callback, so we have to
1198 // hook in here to catch this case (annoying...), but
1199 // otherwise we do want to remember to visit the rest of the
1200 // const, as it has types/regions embedded in a lot of other
1203 ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => {
1204 ControlFlow::Break(FoundEscapingVars)
1206 _ => ct.super_visit_with(self),
1211 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1212 if predicate.outer_exclusive_binder() > self.outer_index {
1213 ControlFlow::Break(FoundEscapingVars)
1215 ControlFlow::CONTINUE
1220 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
1223 // FIXME: Optimize for checking for infer flags
1224 struct HasTypeFlagsVisitor {
1225 flags: ty::TypeFlags,
1228 impl std::fmt::Debug for HasTypeFlagsVisitor {
1229 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1234 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
1235 type BreakTy = FoundFlags;
1238 #[instrument(level = "trace")]
1239 fn visit_ty(&mut self, t: Ty<'_>) -> ControlFlow<Self::BreakTy> {
1241 "HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}",
1246 if t.flags().intersects(self.flags) {
1247 ControlFlow::Break(FoundFlags)
1249 ControlFlow::CONTINUE
1254 #[instrument(skip(self), level = "trace")]
1255 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1256 let flags = r.type_flags();
1257 trace!(r.flags=?flags);
1258 if flags.intersects(self.flags) {
1259 ControlFlow::Break(FoundFlags)
1261 ControlFlow::CONTINUE
1266 #[instrument(level = "trace")]
1267 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1268 let flags = FlagComputation::for_const(c);
1269 trace!(r.flags=?flags);
1270 if flags.intersects(self.flags) {
1271 ControlFlow::Break(FoundFlags)
1273 ControlFlow::CONTINUE
1278 #[instrument(level = "trace")]
1279 fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow<Self::BreakTy> {
1280 let flags = FlagComputation::for_unevaluated_const(uv);
1281 trace!(r.flags=?flags);
1282 if flags.intersects(self.flags) {
1283 ControlFlow::Break(FoundFlags)
1285 ControlFlow::CONTINUE
1290 #[instrument(level = "trace")]
1291 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
1293 "HasTypeFlagsVisitor: predicate={:?} predicate.flags={:?} self.flags={:?}",
1298 if predicate.flags().intersects(self.flags) {
1299 ControlFlow::Break(FoundFlags)
1301 ControlFlow::CONTINUE
1306 /// Collects all the late-bound regions at the innermost binding level
1307 /// into a hash set.
1308 struct LateBoundRegionsCollector {
1309 current_index: ty::DebruijnIndex,
1310 regions: FxHashSet<ty::BoundRegionKind>,
1312 /// `true` if we only want regions that are known to be
1313 /// "constrained" when you equate this type with another type. In
1314 /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
1315 /// them constraints `'a == 'b`. But if you have `<&'a u32 as
1316 /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
1317 /// types may mean that `'a` and `'b` don't appear in the results,
1318 /// so they are not considered *constrained*.
1319 just_constrained: bool,
1322 impl LateBoundRegionsCollector {
1323 fn new(just_constrained: bool) -> Self {
1324 LateBoundRegionsCollector {
1325 current_index: ty::INNERMOST,
1326 regions: Default::default(),
1332 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
1333 fn visit_binder<T: TypeFoldable<'tcx>>(
1335 t: &Binder<'tcx, T>,
1336 ) -> ControlFlow<Self::BreakTy> {
1337 self.current_index.shift_in(1);
1338 let result = t.super_visit_with(self);
1339 self.current_index.shift_out(1);
1343 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1344 // if we are only looking for "constrained" region, we have to
1345 // ignore the inputs to a projection, as they may not appear
1346 // in the normalized form
1347 if self.just_constrained {
1348 if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
1349 return ControlFlow::CONTINUE;
1353 t.super_visit_with(self)
1356 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1357 // if we are only looking for "constrained" region, we have to
1358 // ignore the inputs of an unevaluated const, as they may not appear
1359 // in the normalized form
1360 if self.just_constrained {
1361 if let ty::ConstKind::Unevaluated(..) = c.val() {
1362 return ControlFlow::CONTINUE;
1366 c.super_visit_with(self)
1369 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1370 if let ty::ReLateBound(debruijn, br) = *r {
1371 if debruijn == self.current_index {
1372 self.regions.insert(br.kind);
1375 ControlFlow::CONTINUE