1 //! Generalized type folding mechanism. The setup is a bit convoluted
2 //! but allows for convenient usage. Let T be an instance of some
3 //! "foldable type" (one which implements `TypeFoldable`) and F be an
4 //! instance of a "folder" (a type which implements `TypeFolder`). Then
5 //! the setup is intended to be:
7 //! T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
9 //! This way, when you define a new folder F, you can override
10 //! `fold_T()` to customize the behavior, and invoke `T.super_fold_with()`
11 //! to get the original behavior. Meanwhile, to actually fold
12 //! something, you can just write `T.fold_with(F)`, which is
13 //! convenient. (Note that `fold_with` will also transparently handle
14 //! things like a `Vec<T>` where T is foldable and so on.)
16 //! In this ideal setup, the only function that actually *does*
17 //! anything is `T.super_fold_with()`, which traverses the type `T`.
18 //! Moreover, `T.super_fold_with()` should only ever call `T.fold_with()`.
20 //! In some cases, we follow a degenerate pattern where we do not have
21 //! a `fold_T` method. Instead, `T.fold_with` traverses the structure directly.
22 //! This is suboptimal because the behavior cannot be overridden, but it's
23 //! much less work to implement. If you ever *do* need an override that
24 //! doesn't exist, it's not hard to convert the degenerate pattern into the
27 //! A `TypeFoldable` T can also be visited by a `TypeVisitor` V using similar setup:
29 //! T.visit_with(V) --calls--> V.visit_T(T) --calls--> T.super_visit_with(V).
31 //! These methods return true to indicate that the visitor has found what it is
32 //! looking for, and does not need to visit anything else.
34 use crate::hir::def_id::DefId;
35 use crate::ty::{self, Binder, Ty, TyCtxt, TypeFlags, flags::FlagComputation};
37 use std::collections::BTreeMap;
39 use crate::util::nodemap::FxHashSet;
41 /// The TypeFoldable trait is implemented for every type that can be folded.
42 /// Basically, every type that has a corresponding method in TypeFolder.
44 /// To implement this conveniently, use the
45 /// `BraceStructTypeFoldableImpl` etc macros found in `macros.rs`.
46 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
47 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self;
48 fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
49 self.super_fold_with(folder)
52 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool;
53 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
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 })
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 })
78 fn has_projections(&self) -> bool {
79 self.has_type_flags(TypeFlags::HAS_PROJECTION)
81 fn references_error(&self) -> bool {
82 self.has_type_flags(TypeFlags::HAS_TY_ERR)
84 fn has_param_types(&self) -> bool {
85 self.has_type_flags(TypeFlags::HAS_PARAMS)
87 fn has_self_ty(&self) -> bool {
88 self.has_type_flags(TypeFlags::HAS_SELF)
90 fn has_infer_types(&self) -> bool {
91 self.has_type_flags(TypeFlags::HAS_TY_INFER)
93 fn needs_infer(&self) -> bool {
95 TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER | TypeFlags::HAS_CT_INFER
98 fn has_placeholders(&self) -> bool {
99 self.has_type_flags(TypeFlags::HAS_RE_PLACEHOLDER | TypeFlags::HAS_TY_PLACEHOLDER)
101 fn needs_subst(&self) -> bool {
102 self.has_type_flags(TypeFlags::NEEDS_SUBST)
104 fn has_re_placeholders(&self) -> bool {
105 self.has_type_flags(TypeFlags::HAS_RE_PLACEHOLDER)
107 fn has_closure_types(&self) -> bool {
108 self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
110 /// "Free" regions in this context means that it has any region
111 /// that is not (a) erased or (b) late-bound.
112 fn has_free_regions(&self) -> bool {
113 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
116 /// True if there are any un-erased free regions.
117 fn has_erasable_regions(&self) -> bool {
118 self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
121 /// Indicates whether this value references only 'global'
122 /// generic parameters that are the same regardless of what fn we are
123 /// in. This is used for caching.
124 fn is_global(&self) -> bool {
125 !self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
128 /// True if there are any late-bound regions
129 fn has_late_bound_regions(&self) -> bool {
130 self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
133 /// A visitor that does not recurse into types, works like `fn walk_shallow` in `Ty`.
134 fn visit_tys_shallow(&self, visit: impl FnMut(Ty<'tcx>) -> bool) -> bool {
136 pub struct Visitor<F>(F);
138 impl<'tcx, F: FnMut(Ty<'tcx>) -> bool> TypeVisitor<'tcx> for Visitor<F> {
139 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
144 self.visit_with(&mut Visitor(visit))
148 /// The `TypeFolder` trait defines the actual *folding*. There is a
149 /// method defined for every foldable type. Each of these has a
150 /// default implementation that does an "identity" fold. Within each
151 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
153 pub trait TypeFolder<'gcx: 'tcx, 'tcx> : Sized {
154 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
156 fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
157 where T : TypeFoldable<'tcx>
159 t.super_fold_with(self)
162 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
163 t.super_fold_with(self)
166 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
167 r.super_fold_with(self)
170 fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
171 c.super_fold_with(self)
175 pub trait TypeVisitor<'tcx> : Sized {
176 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
177 t.super_visit_with(self)
180 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
181 t.super_visit_with(self)
184 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
185 r.super_visit_with(self)
188 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
189 c.super_visit_with(self)
193 ///////////////////////////////////////////////////////////////////////////
194 // Some sample folders
196 pub struct BottomUpFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a, F, G>
197 where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
198 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
200 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
205 impl<'a, 'gcx, 'tcx, F, G> TypeFolder<'gcx, 'tcx> for BottomUpFolder<'a, 'gcx, 'tcx, F, G>
206 where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
207 G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
209 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
211 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
212 let t1 = ty.super_fold_with(self);
216 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
217 let r = r.super_fold_with(self);
222 ///////////////////////////////////////////////////////////////////////////
225 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
226 /// Collects the free and escaping regions in `value` into `region_set`. Returns
227 /// whether any late-bound regions were skipped
228 pub fn collect_regions<T>(self,
230 region_set: &mut FxHashSet<ty::Region<'tcx>>)
232 where T : TypeFoldable<'tcx>
234 let mut have_bound_regions = false;
235 self.fold_regions(value, &mut have_bound_regions, |r, d| {
236 region_set.insert(self.mk_region(r.shifted_out_to_binder(d)));
242 /// Folds the escaping and free regions in `value` using `f`, and
243 /// sets `skipped_regions` to true if any late-bound region was found
245 pub fn fold_regions<T>(
248 skipped_regions: &mut bool,
249 mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
252 T : TypeFoldable<'tcx>,
254 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
257 /// Invoke `callback` on every region appearing free in `value`.
258 pub fn for_each_free_region(
260 value: &impl TypeFoldable<'tcx>,
261 mut callback: impl FnMut(ty::Region<'tcx>),
263 self.any_free_region_meets(value, |r| {
269 /// Returns `true` if `callback` returns true for every region appearing free in `value`.
270 pub fn all_free_regions_meet(
272 value: &impl TypeFoldable<'tcx>,
273 mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
275 !self.any_free_region_meets(value, |r| !callback(r))
278 /// Returns `true` if `callback` returns true for some region appearing free in `value`.
279 pub fn any_free_region_meets(
281 value: &impl TypeFoldable<'tcx>,
282 callback: impl FnMut(ty::Region<'tcx>) -> bool,
284 return value.visit_with(&mut RegionVisitor {
285 outer_index: ty::INNERMOST,
289 struct RegionVisitor<F> {
290 /// The index of a binder *just outside* the things we have
291 /// traversed. If we encounter a bound region bound by this
292 /// binder or one outer to it, it appears free. Example:
295 /// for<'a> fn(for<'b> fn(), T)
297 /// | | | | here, would be shifted in 1
298 /// | | | here, would be shifted in 2
299 /// | | here, would be `INNERMOST` shifted in by 1
300 /// | here, initially, binder would be `INNERMOST`
303 /// You see that, initially, *any* bound value is free,
304 /// because we've not traversed any binders. As we pass
305 /// through a binder, we shift the `outer_index` by 1 to
306 /// account for the new binder that encloses us.
307 outer_index: ty::DebruijnIndex,
311 impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
312 where F: FnMut(ty::Region<'tcx>) -> bool
314 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
315 self.outer_index.shift_in(1);
316 let result = t.skip_binder().visit_with(self);
317 self.outer_index.shift_out(1);
321 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
323 ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
324 false // ignore bound regions, keep visiting
326 _ => (self.callback)(r),
330 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
331 // We're only interested in types involving regions
332 if ty.flags.intersects(TypeFlags::HAS_FREE_REGIONS) {
333 ty.super_visit_with(self)
335 false // keep visiting
342 /// Folds over the substructure of a type, visiting its component
343 /// types and all regions that occur *free* within it.
345 /// That is, `Ty` can contain function or method types that bind
346 /// regions at the call site (`ReLateBound`), and occurrences of
347 /// regions (aka "lifetimes") that are bound within a type are not
348 /// visited by this folder; only regions that occur free will be
349 /// visited by `fld_r`.
351 pub struct RegionFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
352 tcx: TyCtxt<'a, 'gcx, 'tcx>,
353 skipped_regions: &'a mut bool,
355 /// Stores the index of a binder *just outside* the stuff we have
356 /// visited. So this begins as INNERMOST; when we pass through a
357 /// binder, it is incremented (via `shift_in`).
358 current_index: ty::DebruijnIndex,
360 /// Callback invokes for each free region. The `DebruijnIndex`
361 /// points to the binder *just outside* the ones we have passed
363 fold_region_fn: &'a mut (dyn FnMut(
366 ) -> ty::Region<'tcx> + 'a),
369 impl<'a, 'gcx, 'tcx> RegionFolder<'a, 'gcx, 'tcx> {
372 tcx: TyCtxt<'a, 'gcx, 'tcx>,
373 skipped_regions: &'a mut bool,
374 fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
375 ) -> RegionFolder<'a, 'gcx, 'tcx> {
379 current_index: ty::INNERMOST,
385 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionFolder<'a, 'gcx, 'tcx> {
386 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
388 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
389 self.current_index.shift_in(1);
390 let t = t.super_fold_with(self);
391 self.current_index.shift_out(1);
395 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
397 ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
398 debug!("RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
399 r, self.current_index);
400 *self.skipped_regions = true;
404 debug!("RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
405 r, self.current_index);
406 (self.fold_region_fn)(r, self.current_index)
412 ///////////////////////////////////////////////////////////////////////////
413 // Bound vars replacer
415 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
416 struct BoundVarReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
417 tcx: TyCtxt<'a, 'gcx, 'tcx>,
419 /// As with `RegionFolder`, represents the index of a binder *just outside*
420 /// the ones we have visited.
421 current_index: ty::DebruijnIndex,
423 fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
424 fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
427 impl<'a, 'gcx, 'tcx> BoundVarReplacer<'a, 'gcx, 'tcx> {
429 tcx: TyCtxt<'a, 'gcx, 'tcx>,
433 where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
434 G: FnMut(ty::BoundTy) -> Ty<'tcx>
438 current_index: ty::INNERMOST,
445 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for BoundVarReplacer<'a, 'gcx, 'tcx> {
446 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
448 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
449 self.current_index.shift_in(1);
450 let t = t.super_fold_with(self);
451 self.current_index.shift_out(1);
455 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
457 ty::Bound(debruijn, bound_ty) => {
458 if debruijn == self.current_index {
459 let fld_t = &mut self.fld_t;
460 let ty = fld_t(bound_ty);
461 ty::fold::shift_vars(
464 self.current_index.as_u32()
471 if !t.has_vars_bound_at_or_above(self.current_index) {
472 // Nothing more to substitute.
475 t.super_fold_with(self)
481 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
483 ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
484 let fld_r = &mut self.fld_r;
485 let region = fld_r(br);
486 if let ty::ReLateBound(debruijn1, br) = *region {
487 // If the callback returns a late-bound region,
488 // that region should always use the INNERMOST
489 // debruijn index. Then we adjust it to the
491 assert_eq!(debruijn1, ty::INNERMOST);
492 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
502 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
503 /// Replaces all regions bound by the given `Binder` with the
504 /// results returned by the closure; the closure is expected to
505 /// return a free region (relative to this binder), and hence the
506 /// binder is removed in the return type. The closure is invoked
507 /// once for each unique `BoundRegion`; multiple references to the
508 /// same `BoundRegion` will reuse the previous result. A map is
509 /// returned at the end with each bound region and the free region
510 /// that replaced it.
512 /// This method only replaces late bound regions and the result may still
513 /// contain escaping bound types.
514 pub fn replace_late_bound_regions<T, F>(
518 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
519 where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
520 T: TypeFoldable<'tcx>
522 // identity for bound types
523 let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
524 self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t)
527 /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
528 /// bound regions while the `fld_t` closure replaces escaping bound types.
529 pub fn replace_escaping_bound_vars<T, F, G>(
534 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
535 where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
536 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
537 T: TypeFoldable<'tcx>
539 use rustc_data_structures::fx::FxHashMap;
541 let mut region_map = BTreeMap::new();
542 let mut type_map = FxHashMap::default();
544 if !value.has_escaping_bound_vars() {
545 (value.clone(), region_map)
547 let mut real_fld_r = |br| {
548 *region_map.entry(br).or_insert_with(|| fld_r(br))
551 let mut real_fld_t = |bound_ty| {
552 *type_map.entry(bound_ty).or_insert_with(|| fld_t(bound_ty))
555 let mut replacer = BoundVarReplacer::new(self, &mut real_fld_r, &mut real_fld_t);
556 let result = value.fold_with(&mut replacer);
561 /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
562 /// closure replaces bound regions while the `fld_t` closure replaces bound
564 pub fn replace_bound_vars<T, F, G>(
569 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
570 where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
571 G: FnMut(ty::BoundTy) -> Ty<'tcx>,
572 T: TypeFoldable<'tcx>
574 self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t)
577 /// Replaces any late-bound regions bound in `value` with
578 /// free variants attached to `all_outlive_scope`.
579 pub fn liberate_late_bound_regions<T>(
581 all_outlive_scope: DefId,
582 value: &ty::Binder<T>
584 where T: TypeFoldable<'tcx> {
585 self.replace_late_bound_regions(value, |br| {
586 self.mk_region(ty::ReFree(ty::FreeRegion {
587 scope: all_outlive_scope,
593 /// Returns a set of all late-bound regions that are constrained
594 /// by `value`, meaning that if we instantiate those LBR with
595 /// variables and equate `value` with something else, those
596 /// variables will also be equated.
597 pub fn collect_constrained_late_bound_regions<T>(&self, value: &Binder<T>)
598 -> FxHashSet<ty::BoundRegion>
599 where T : TypeFoldable<'tcx>
601 self.collect_late_bound_regions(value, true)
604 /// Returns a set of all late-bound regions that appear in `value` anywhere.
605 pub fn collect_referenced_late_bound_regions<T>(&self, value: &Binder<T>)
606 -> FxHashSet<ty::BoundRegion>
607 where T : TypeFoldable<'tcx>
609 self.collect_late_bound_regions(value, false)
612 fn collect_late_bound_regions<T>(&self, value: &Binder<T>, just_constraint: bool)
613 -> FxHashSet<ty::BoundRegion>
614 where T : TypeFoldable<'tcx>
616 let mut collector = LateBoundRegionsCollector::new(just_constraint);
617 let result = value.skip_binder().visit_with(&mut collector);
618 assert!(!result); // should never have stopped early
622 /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
623 /// method lookup and a few other places where precise region relationships are not required.
624 pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
625 where T : TypeFoldable<'tcx>
627 self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
630 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
631 /// assigned starting at 1 and increasing monotonically in the order traversed
632 /// by the fold operation.
634 /// The chief purpose of this function is to canonicalize regions so that two
635 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
636 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
637 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
638 pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
639 where T : TypeFoldable<'tcx>,
642 Binder::bind(self.replace_late_bound_regions(sig, |_| {
644 self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)))
649 ///////////////////////////////////////////////////////////////////////////
652 // Shifts the De Bruijn indices on all escaping bound vars by a
653 // fixed amount. Useful in substitution or when otherwise introducing
654 // a binding level that is not intended to capture the existing bound
655 // vars. See comment on `shift_vars_through_binders` method in
656 // `subst.rs` for more details.
658 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
664 struct Shifter<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
665 tcx: TyCtxt<'a, 'gcx, 'tcx>,
666 current_index: ty::DebruijnIndex,
668 direction: Direction,
671 impl Shifter<'a, 'gcx, 'tcx> {
672 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, amount: u32, direction: Direction) -> Self {
675 current_index: ty::INNERMOST,
682 impl TypeFolder<'gcx, 'tcx> for Shifter<'a, 'gcx, 'tcx> {
683 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
685 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
686 self.current_index.shift_in(1);
687 let t = t.super_fold_with(self);
688 self.current_index.shift_out(1);
692 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
694 ty::ReLateBound(debruijn, br) => {
695 if self.amount == 0 || debruijn < self.current_index {
698 let debruijn = match self.direction {
699 Direction::In => debruijn.shifted_in(self.amount),
701 assert!(debruijn.as_u32() >= self.amount);
702 debruijn.shifted_out(self.amount)
705 let shifted = ty::ReLateBound(debruijn, br);
706 self.tcx.mk_region(shifted)
713 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
715 ty::Bound(debruijn, bound_ty) => {
716 if self.amount == 0 || debruijn < self.current_index {
719 let debruijn = match self.direction {
720 Direction::In => debruijn.shifted_in(self.amount),
722 assert!(debruijn.as_u32() >= self.amount);
723 debruijn.shifted_out(self.amount)
727 ty::Bound(debruijn, bound_ty)
732 _ => ty.super_fold_with(self),
737 pub fn shift_region<'a, 'gcx, 'tcx>(
738 tcx: TyCtxt<'a, 'gcx, 'tcx>,
739 region: ty::Region<'tcx>,
741 ) -> ty::Region<'tcx> {
743 ty::ReLateBound(debruijn, br) if amount > 0 => {
744 tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
752 pub fn shift_vars<'a, 'gcx, 'tcx, T>(
753 tcx: TyCtxt<'a, 'gcx, 'tcx>,
756 ) -> T where T: TypeFoldable<'tcx> {
757 debug!("shift_vars(value={:?}, amount={})",
760 value.fold_with(&mut Shifter::new(tcx, amount, Direction::In))
763 pub fn shift_out_vars<'a, 'gcx, 'tcx, T>(
764 tcx: TyCtxt<'a, 'gcx, 'tcx>,
767 ) -> T where T: TypeFoldable<'tcx> {
768 debug!("shift_out_vars(value={:?}, amount={})",
771 value.fold_with(&mut Shifter::new(tcx, amount, Direction::Out))
774 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
775 /// bound region or a bound type.
777 /// So, for example, consider a type like the following, which has two binders:
779 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
780 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
781 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
783 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
784 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
785 /// fn type*, that type has an escaping region: `'a`.
787 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
788 /// we already use the term "free var". It refers to the regions or types that we use to represent
789 /// bound regions or type params on a fn definition while we are type checking its body.
791 /// To clarify, conceptually there is no particular difference between
792 /// an "escaping" var and a "free" var. However, there is a big
793 /// difference in practice. Basically, when "entering" a binding
794 /// level, one is generally required to do some sort of processing to
795 /// a bound var, such as replacing it with a fresh/placeholder
796 /// var, or making an entry in the environment to represent the
797 /// scope to which it is attached, etc. An escaping var represents
798 /// a bound var for which this processing has not yet been done.
799 struct HasEscapingVarsVisitor {
800 /// Anything bound by `outer_index` or "above" is escaping.
801 outer_index: ty::DebruijnIndex,
804 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
805 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
806 self.outer_index.shift_in(1);
807 let result = t.super_visit_with(self);
808 self.outer_index.shift_out(1);
812 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
813 // If the outer-exclusive-binder is *strictly greater* than
814 // `outer_index`, that means that `t` contains some content
815 // bound at `outer_index` or above (because
816 // `outer_exclusive_binder` is always 1 higher than the
817 // content in `t`). Therefore, `t` has some escaping vars.
818 t.outer_exclusive_binder > self.outer_index
821 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
822 // If the region is bound by `outer_index` or anything outside
823 // of outer index, then it escapes the binders we have
825 r.bound_at_or_above_binder(self.outer_index)
829 struct HasTypeFlagsVisitor {
830 flags: ty::TypeFlags,
833 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
834 fn visit_ty(&mut self, t: Ty<'_>) -> bool {
835 debug!("HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}", t, t.flags, self.flags);
836 t.flags.intersects(self.flags)
839 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
840 let flags = r.type_flags();
841 debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
842 flags.intersects(self.flags)
845 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
846 let flags = FlagComputation::for_const(c);
847 debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
848 flags.intersects(self.flags) || c.super_visit_with(self)
852 /// Collects all the late-bound regions at the innermost binding level
854 struct LateBoundRegionsCollector {
855 current_index: ty::DebruijnIndex,
856 regions: FxHashSet<ty::BoundRegion>,
858 /// `true` if we only want regions that are known to be
859 /// "constrained" when you equate this type with another type. In
860 /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
861 /// them constraints `'a == 'b`. But if you have `<&'a u32 as
862 /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
863 /// types may mean that `'a` and `'b` don't appear in the results,
864 /// so they are not considered *constrained*.
865 just_constrained: bool,
868 impl LateBoundRegionsCollector {
869 fn new(just_constrained: bool) -> Self {
870 LateBoundRegionsCollector {
871 current_index: ty::INNERMOST,
872 regions: Default::default(),
878 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
879 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
880 self.current_index.shift_in(1);
881 let result = t.super_visit_with(self);
882 self.current_index.shift_out(1);
886 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
887 // if we are only looking for "constrained" region, we have to
888 // ignore the inputs to a projection, as they may not appear
889 // in the normalized form
890 if self.just_constrained {
892 ty::Projection(..) | ty::Opaque(..) => { return false; }
897 t.super_visit_with(self)
900 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
901 if let ty::ReLateBound(debruijn, br) = *r {
902 if debruijn == self.current_index {
903 self.regions.insert(br);