1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Generalized type folding mechanism. The setup is a bit convoluted
12 //! but allows for convenient usage. Let T be an instance of some
13 //! "foldable type" (one which implements `TypeFoldable`) and F be an
14 //! instance of a "folder" (a type which implements `TypeFolder`). Then
15 //! the setup is intended to be:
17 //! T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
19 //! This way, when you define a new folder F, you can override
20 //! `fold_T()` to customize the behavior, and invoke `T.super_fold_with()`
21 //! to get the original behavior. Meanwhile, to actually fold
22 //! something, you can just write `T.fold_with(F)`, which is
23 //! convenient. (Note that `fold_with` will also transparently handle
24 //! things like a `Vec<T>` where T is foldable and so on.)
26 //! In this ideal setup, the only function that actually *does*
27 //! anything is `T.super_fold_with()`, which traverses the type `T`.
28 //! Moreover, `T.super_fold_with()` should only ever call `T.fold_with()`.
30 //! In some cases, we follow a degenerate pattern where we do not have
31 //! a `fold_T` method. Instead, `T.fold_with` traverses the structure directly.
32 //! This is suboptimal because the behavior cannot be overridden, but it's
33 //! much less work to implement. If you ever *do* need an override that
34 //! doesn't exist, it's not hard to convert the degenerate pattern into the
37 //! A `TypeFoldable` T can also be visited by a `TypeVisitor` V using similar setup:
38 //! T.visit_with(V) --calls--> V.visit_T(T) --calls--> T.super_visit_with(V).
39 //! These methods return true to indicate that the visitor has found what it is looking for
40 //! and does not need to visit anything else.
42 use ty::{self, Binder, Ty, TyCtxt, TypeFlags};
45 use util::nodemap::{FxHashMap, FxHashSet};
47 /// The TypeFoldable trait is implemented for every type that can be folded.
48 /// Basically, every type that has a corresponding method in TypeFolder.
49 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
50 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self;
51 fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
52 self.super_fold_with(folder)
55 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool;
56 fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
57 self.super_visit_with(visitor)
60 fn has_regions_escaping_depth(&self, depth: u32) -> bool {
61 self.visit_with(&mut HasEscapingRegionsVisitor { depth: depth })
63 fn has_escaping_regions(&self) -> bool {
64 self.has_regions_escaping_depth(0)
67 fn has_type_flags(&self, flags: TypeFlags) -> bool {
68 self.visit_with(&mut HasTypeFlagsVisitor { flags: flags })
70 fn has_projection_types(&self) -> bool {
71 self.has_type_flags(TypeFlags::HAS_PROJECTION)
73 fn references_error(&self) -> bool {
74 self.has_type_flags(TypeFlags::HAS_TY_ERR)
76 fn has_param_types(&self) -> bool {
77 self.has_type_flags(TypeFlags::HAS_PARAMS)
79 fn has_self_ty(&self) -> bool {
80 self.has_type_flags(TypeFlags::HAS_SELF)
82 fn has_infer_types(&self) -> bool {
83 self.has_type_flags(TypeFlags::HAS_TY_INFER)
85 fn needs_infer(&self) -> bool {
86 self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER)
88 fn needs_subst(&self) -> bool {
89 self.has_type_flags(TypeFlags::NEEDS_SUBST)
91 fn has_re_skol(&self) -> bool {
92 self.has_type_flags(TypeFlags::HAS_RE_SKOL)
94 fn has_closure_types(&self) -> bool {
95 self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
97 fn has_erasable_regions(&self) -> bool {
98 self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
99 TypeFlags::HAS_RE_INFER |
100 TypeFlags::HAS_FREE_REGIONS)
102 fn is_normalized_for_trans(&self) -> bool {
103 !self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
104 TypeFlags::HAS_RE_INFER |
105 TypeFlags::HAS_FREE_REGIONS |
106 TypeFlags::HAS_TY_INFER |
107 TypeFlags::HAS_PARAMS |
108 TypeFlags::HAS_NORMALIZABLE_PROJECTION |
109 TypeFlags::HAS_TY_ERR |
112 /// Indicates whether this value references only 'global'
113 /// types/lifetimes that are the same regardless of what fn we are
114 /// in. This is used for caching. Errs on the side of returning
116 fn is_global(&self) -> bool {
117 !self.has_type_flags(TypeFlags::HAS_LOCAL_NAMES)
121 /// The TypeFolder trait defines the actual *folding*. There is a
122 /// method defined for every foldable type. Each of these has a
123 /// default implementation that does an "identity" fold. Within each
124 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
126 pub trait TypeFolder<'gcx: 'tcx, 'tcx> : Sized {
127 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
129 fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
130 where T : TypeFoldable<'tcx>
132 t.super_fold_with(self)
135 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
136 t.super_fold_with(self)
139 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
140 r.super_fold_with(self)
144 pub trait TypeVisitor<'tcx> : Sized {
145 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
146 t.super_visit_with(self)
149 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
150 t.super_visit_with(self)
153 fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
154 trait_ref.super_visit_with(self)
157 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
158 r.super_visit_with(self)
162 ///////////////////////////////////////////////////////////////////////////
163 // Some sample folders
165 pub struct BottomUpFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a, F>
166 where F: FnMut(Ty<'tcx>) -> Ty<'tcx>
168 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
172 impl<'a, 'gcx, 'tcx, F> TypeFolder<'gcx, 'tcx> for BottomUpFolder<'a, 'gcx, 'tcx, F>
173 where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
175 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
177 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
178 let t1 = ty.super_fold_with(self);
183 ///////////////////////////////////////////////////////////////////////////
186 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
187 /// Collects the free and escaping regions in `value` into `region_set`. Returns
188 /// whether any late-bound regions were skipped
189 pub fn collect_regions<T>(self,
191 region_set: &mut FxHashSet<ty::Region<'tcx>>)
193 where T : TypeFoldable<'tcx>
195 let mut have_bound_regions = false;
196 self.fold_regions(value, &mut have_bound_regions, |r, d| {
197 region_set.insert(self.mk_region(r.from_depth(d)));
203 /// Folds the escaping and free regions in `value` using `f`, and
204 /// sets `skipped_regions` to true if any late-bound region was found
206 pub fn fold_regions<T,F>(self,
208 skipped_regions: &mut bool,
211 where F : FnMut(ty::Region<'tcx>, u32) -> ty::Region<'tcx>,
212 T : TypeFoldable<'tcx>,
214 value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
218 /// Folds over the substructure of a type, visiting its component
219 /// types and all regions that occur *free* within it.
221 /// That is, `Ty` can contain function or method types that bind
222 /// regions at the call site (`ReLateBound`), and occurrences of
223 /// regions (aka "lifetimes") that are bound within a type are not
224 /// visited by this folder; only regions that occur free will be
225 /// visited by `fld_r`.
227 pub struct RegionFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
228 tcx: TyCtxt<'a, 'gcx, 'tcx>,
229 skipped_regions: &'a mut bool,
231 fld_r: &'a mut (FnMut(ty::Region<'tcx>, u32) -> ty::Region<'tcx> + 'a),
234 impl<'a, 'gcx, 'tcx> RegionFolder<'a, 'gcx, 'tcx> {
235 pub fn new<F>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
236 skipped_regions: &'a mut bool,
237 fld_r: &'a mut F) -> RegionFolder<'a, 'gcx, 'tcx>
238 where F : FnMut(ty::Region<'tcx>, u32) -> ty::Region<'tcx>
242 skipped_regions: skipped_regions,
249 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionFolder<'a, 'gcx, 'tcx> {
250 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
252 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
253 self.current_depth += 1;
254 let t = t.super_fold_with(self);
255 self.current_depth -= 1;
259 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
261 ty::ReLateBound(debruijn, _) if debruijn.depth < self.current_depth => {
262 debug!("RegionFolder.fold_region({:?}) skipped bound region (current depth={})",
263 r, self.current_depth);
264 *self.skipped_regions = true;
268 debug!("RegionFolder.fold_region({:?}) folding free region (current_depth={})",
269 r, self.current_depth);
270 (self.fld_r)(r, self.current_depth)
276 ///////////////////////////////////////////////////////////////////////////
277 // Late-bound region replacer
279 // Replaces the escaping regions in a type.
281 struct RegionReplacer<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
282 tcx: TyCtxt<'a, 'gcx, 'tcx>,
284 fld_r: &'a mut (FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
285 map: FxHashMap<ty::BoundRegion, ty::Region<'tcx>>
288 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
289 pub fn replace_late_bound_regions<T,F>(self,
292 -> (T, FxHashMap<ty::BoundRegion, ty::Region<'tcx>>)
293 where F : FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
294 T : TypeFoldable<'tcx>,
296 let mut replacer = RegionReplacer::new(self, &mut f);
297 let result = value.skip_binder().fold_with(&mut replacer);
298 (result, replacer.map)
301 /// Flattens two binding levels into one. So `for<'a> for<'b> Foo`
302 /// becomes `for<'a,'b> Foo`.
303 pub fn flatten_late_bound_regions<T>(self, bound2_value: &Binder<Binder<T>>)
305 where T: TypeFoldable<'tcx>
307 let bound0_value = bound2_value.skip_binder().skip_binder();
308 let value = self.fold_regions(bound0_value, &mut false,
309 |region, current_depth| {
311 ty::ReLateBound(debruijn, br) if debruijn.depth >= current_depth => {
312 // should be true if no escaping regions from bound2_value
313 assert!(debruijn.depth - current_depth <= 1);
314 self.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(current_depth), br))
324 pub fn no_late_bound_regions<T>(self, value: &Binder<T>) -> Option<T>
325 where T : TypeFoldable<'tcx>
327 if value.0.has_escaping_regions() {
330 Some(value.0.clone())
334 /// Returns a set of all late-bound regions that are constrained
335 /// by `value`, meaning that if we instantiate those LBR with
336 /// variables and equate `value` with something else, those
337 /// variables will also be equated.
338 pub fn collect_constrained_late_bound_regions<T>(&self, value: &Binder<T>)
339 -> FxHashSet<ty::BoundRegion>
340 where T : TypeFoldable<'tcx>
342 self.collect_late_bound_regions(value, true)
345 /// Returns a set of all late-bound regions that appear in `value` anywhere.
346 pub fn collect_referenced_late_bound_regions<T>(&self, value: &Binder<T>)
347 -> FxHashSet<ty::BoundRegion>
348 where T : TypeFoldable<'tcx>
350 self.collect_late_bound_regions(value, false)
353 fn collect_late_bound_regions<T>(&self, value: &Binder<T>, just_constraint: bool)
354 -> FxHashSet<ty::BoundRegion>
355 where T : TypeFoldable<'tcx>
357 let mut collector = LateBoundRegionsCollector::new(just_constraint);
358 let result = value.skip_binder().visit_with(&mut collector);
359 assert!(!result); // should never have stopped early
363 /// Replace any late-bound regions bound in `value` with `'erased`. Useful in trans but also
364 /// method lookup and a few other places where precise region relationships are not required.
365 pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
366 where T : TypeFoldable<'tcx>
368 self.replace_late_bound_regions(value, |_| self.types.re_erased).0
371 /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
372 /// assigned starting at 1 and increasing monotonically in the order traversed
373 /// by the fold operation.
375 /// The chief purpose of this function is to canonicalize regions so that two
376 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
377 /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
378 /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
379 pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
380 where T : TypeFoldable<'tcx>,
383 Binder(self.replace_late_bound_regions(sig, |_| {
385 self.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), ty::BrAnon(counter)))
390 impl<'a, 'gcx, 'tcx> RegionReplacer<'a, 'gcx, 'tcx> {
391 fn new<F>(tcx: TyCtxt<'a, 'gcx, 'tcx>, fld_r: &'a mut F)
392 -> RegionReplacer<'a, 'gcx, 'tcx>
393 where F : FnMut(ty::BoundRegion) -> ty::Region<'tcx>
404 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
405 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
407 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
408 self.current_depth += 1;
409 let t = t.super_fold_with(self);
410 self.current_depth -= 1;
414 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
415 if !t.has_regions_escaping_depth(self.current_depth-1) {
419 t.super_fold_with(self)
422 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
424 ty::ReLateBound(debruijn, br) if debruijn.depth == self.current_depth => {
425 let fld_r = &mut self.fld_r;
426 let region = *self.map.entry(br).or_insert_with(|| fld_r(br));
427 if let ty::ReLateBound(debruijn1, br) = *region {
428 // If the callback returns a late-bound region,
429 // that region should always use depth 1. Then we
430 // adjust it to the correct depth.
431 assert_eq!(debruijn1.depth, 1);
432 self.tcx.mk_region(ty::ReLateBound(debruijn, br))
442 ///////////////////////////////////////////////////////////////////////////
445 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
446 /// Returns an equivalent value with all free regions removed (note
447 /// that late-bound regions remain, because they are important for
448 /// subtyping, but they are anonymized and normalized as well)..
449 pub fn erase_regions<T>(self, value: &T) -> T
450 where T : TypeFoldable<'tcx>
452 let value1 = value.fold_with(&mut RegionEraser(self));
453 debug!("erase_regions({:?}) = {:?}",
457 struct RegionEraser<'a, 'gcx: 'a+'tcx, 'tcx: 'a>(TyCtxt<'a, 'gcx, 'tcx>);
459 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionEraser<'a, 'gcx, 'tcx> {
460 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.0 }
462 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
463 if let Some(u) = self.tcx().normalized_cache.borrow().get(&ty).cloned() {
467 // FIXME(eddyb) should local contexts have a cache too?
468 if let Some(ty_lifted) = self.tcx().lift_to_global(&ty) {
469 let tcx = self.tcx().global_tcx();
470 let t_norm = ty_lifted.super_fold_with(&mut RegionEraser(tcx));
471 tcx.normalized_cache.borrow_mut().insert(ty_lifted, t_norm);
474 ty.super_fold_with(self)
478 fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
479 where T : TypeFoldable<'tcx>
481 let u = self.tcx().anonymize_late_bound_regions(t);
482 u.super_fold_with(self)
485 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
486 // because late-bound regions affect subtyping, we can't
487 // erase the bound/free distinction, but we can replace
488 // all free regions with 'erased.
490 // Note that we *CAN* replace early-bound regions -- the
491 // type system never "sees" those, they get substituted
492 // away. In trans, they will always be erased to 'erased
493 // whenever a substitution occurs.
495 ty::ReLateBound(..) => r,
496 _ => self.tcx().types.re_erased
503 ///////////////////////////////////////////////////////////////////////////
506 // Shifts the De Bruijn indices on all escaping bound regions by a
507 // fixed amount. Useful in substitution or when otherwise introducing
508 // a binding level that is not intended to capture the existing bound
509 // regions. See comment on `shift_regions_through_binders` method in
510 // `subst.rs` for more details.
512 pub fn shift_region(region: ty::RegionKind, amount: u32) -> ty::RegionKind {
514 ty::ReLateBound(debruijn, br) => {
515 ty::ReLateBound(debruijn.shifted(amount), br)
523 pub fn shift_region_ref<'a, 'gcx, 'tcx>(
524 tcx: TyCtxt<'a, 'gcx, 'tcx>,
525 region: ty::Region<'tcx>,
530 &ty::ReLateBound(debruijn, br) if amount > 0 => {
531 tcx.mk_region(ty::ReLateBound(debruijn.shifted(amount), br))
539 pub fn shift_regions<'a, 'gcx, 'tcx, T>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
542 where T: TypeFoldable<'tcx>
544 debug!("shift_regions(value={:?}, amount={})",
547 value.fold_with(&mut RegionFolder::new(tcx, &mut false, &mut |region, _current_depth| {
548 shift_region_ref(tcx, region, amount)
552 /// An "escaping region" is a bound region whose binder is not part of `t`.
554 /// So, for example, consider a type like the following, which has two binders:
556 /// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
557 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
558 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
560 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
561 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
562 /// fn type*, that type has an escaping region: `'a`.
564 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
565 /// we already use the term "free region". It refers to the regions that we use to represent bound
566 /// regions on a fn definition while we are typechecking its body.
568 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
569 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
570 /// binding level, one is generally required to do some sort of processing to a bound region, such
571 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
572 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
573 /// for which this processing has not yet been done.
574 struct HasEscapingRegionsVisitor {
578 impl<'tcx> TypeVisitor<'tcx> for HasEscapingRegionsVisitor {
579 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
581 let result = t.super_visit_with(self);
586 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
587 t.region_depth > self.depth
590 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
591 r.escapes_depth(self.depth)
595 struct HasTypeFlagsVisitor {
596 flags: ty::TypeFlags,
599 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
600 fn visit_ty(&mut self, t: Ty) -> bool {
601 debug!("HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}", t, t.flags, self.flags);
602 t.flags.intersects(self.flags)
605 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
606 let flags = r.type_flags();
607 debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
608 flags.intersects(self.flags)
612 /// Collects all the late-bound regions it finds into a hash set.
613 struct LateBoundRegionsCollector {
615 regions: FxHashSet<ty::BoundRegion>,
616 just_constrained: bool,
619 impl LateBoundRegionsCollector {
620 fn new(just_constrained: bool) -> Self {
621 LateBoundRegionsCollector {
623 regions: FxHashSet(),
624 just_constrained: just_constrained,
629 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
630 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
631 self.current_depth += 1;
632 let result = t.super_visit_with(self);
633 self.current_depth -= 1;
637 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
638 // if we are only looking for "constrained" region, we have to
639 // ignore the inputs to a projection, as they may not appear
640 // in the normalized form
641 if self.just_constrained {
643 ty::TyProjection(..) | ty::TyAnon(..) => { return false; }
648 t.super_visit_with(self)
651 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
653 ty::ReLateBound(debruijn, br) if debruijn.depth == self.current_depth => {
654 self.regions.insert(br);