]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/fold.rs
remove ROOT_CODE_EXTENT and DUMMY_CODE_EXTENT
[rust.git] / src / librustc / ty / fold.rs
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.
4 //
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.
10
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:
16 //!
17 //!   T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
18 //!
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.)
25 //!
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()`.
29 //!
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
35 //! proper thing.
36 //!
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.
41
42 use middle::region;
43 use ty::subst::Substs;
44 use ty::adjustment;
45 use ty::{self, Binder, Ty, TyCtxt, TypeFlags};
46
47 use std::fmt;
48 use util::nodemap::{FxHashMap, FxHashSet};
49
50 /// The TypeFoldable trait is implemented for every type that can be folded.
51 /// Basically, every type that has a corresponding method in TypeFolder.
52 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
53     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self;
54     fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
55         self.super_fold_with(folder)
56     }
57
58     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool;
59     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
60         self.super_visit_with(visitor)
61     }
62
63     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
64         self.visit_with(&mut HasEscapingRegionsVisitor { depth: depth })
65     }
66     fn has_escaping_regions(&self) -> bool {
67         self.has_regions_escaping_depth(0)
68     }
69
70     fn has_type_flags(&self, flags: TypeFlags) -> bool {
71         self.visit_with(&mut HasTypeFlagsVisitor { flags: flags })
72     }
73     fn has_projection_types(&self) -> bool {
74         self.has_type_flags(TypeFlags::HAS_PROJECTION)
75     }
76     fn references_error(&self) -> bool {
77         self.has_type_flags(TypeFlags::HAS_TY_ERR)
78     }
79     fn has_param_types(&self) -> bool {
80         self.has_type_flags(TypeFlags::HAS_PARAMS)
81     }
82     fn has_self_ty(&self) -> bool {
83         self.has_type_flags(TypeFlags::HAS_SELF)
84     }
85     fn has_infer_types(&self) -> bool {
86         self.has_type_flags(TypeFlags::HAS_TY_INFER)
87     }
88     fn needs_infer(&self) -> bool {
89         self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER)
90     }
91     fn needs_subst(&self) -> bool {
92         self.has_type_flags(TypeFlags::NEEDS_SUBST)
93     }
94     fn has_re_skol(&self) -> bool {
95         self.has_type_flags(TypeFlags::HAS_RE_SKOL)
96     }
97     fn has_closure_types(&self) -> bool {
98         self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
99     }
100     fn has_erasable_regions(&self) -> bool {
101         self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
102                             TypeFlags::HAS_RE_INFER |
103                             TypeFlags::HAS_FREE_REGIONS)
104     }
105     fn is_normalized_for_trans(&self) -> bool {
106         !self.has_type_flags(TypeFlags::HAS_RE_EARLY_BOUND |
107                              TypeFlags::HAS_RE_INFER |
108                              TypeFlags::HAS_FREE_REGIONS |
109                              TypeFlags::HAS_TY_INFER |
110                              TypeFlags::HAS_PARAMS |
111                              TypeFlags::HAS_NORMALIZABLE_PROJECTION |
112                              TypeFlags::HAS_TY_ERR |
113                              TypeFlags::HAS_SELF)
114     }
115     /// Indicates whether this value references only 'global'
116     /// types/lifetimes that are the same regardless of what fn we are
117     /// in. This is used for caching. Errs on the side of returning
118     /// false.
119     fn is_global(&self) -> bool {
120         !self.has_type_flags(TypeFlags::HAS_LOCAL_NAMES)
121     }
122 }
123
124 /// The TypeFolder trait defines the actual *folding*. There is a
125 /// method defined for every foldable type. Each of these has a
126 /// default implementation that does an "identity" fold. Within each
127 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
128 /// sub-item.
129 pub trait TypeFolder<'gcx: 'tcx, 'tcx> : Sized {
130     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
131
132     fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
133         where T : TypeFoldable<'tcx>
134     {
135         t.super_fold_with(self)
136     }
137
138     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
139         t.super_fold_with(self)
140     }
141
142     fn fold_mt(&mut self, t: &ty::TypeAndMut<'tcx>) -> ty::TypeAndMut<'tcx> {
143         t.super_fold_with(self)
144     }
145
146     fn fold_impl_header(&mut self, imp: &ty::ImplHeader<'tcx>) -> ty::ImplHeader<'tcx> {
147         imp.super_fold_with(self)
148     }
149
150     fn fold_substs(&mut self,
151                    substs: &'tcx Substs<'tcx>)
152                    -> &'tcx Substs<'tcx> {
153         substs.super_fold_with(self)
154     }
155
156     fn fold_fn_sig(&mut self,
157                    sig: &ty::FnSig<'tcx>)
158                    -> ty::FnSig<'tcx> {
159         sig.super_fold_with(self)
160     }
161
162     fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
163         r.super_fold_with(self)
164     }
165
166     fn fold_autoref(&mut self, ar: &adjustment::AutoBorrow<'tcx>)
167                     -> adjustment::AutoBorrow<'tcx> {
168         ar.super_fold_with(self)
169     }
170 }
171
172 pub trait TypeVisitor<'tcx> : Sized {
173     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
174         t.super_visit_with(self)
175     }
176
177     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
178         t.super_visit_with(self)
179     }
180
181     fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
182         trait_ref.super_visit_with(self)
183     }
184
185     fn visit_region(&mut self, r: &'tcx ty::Region) -> bool {
186         r.super_visit_with(self)
187     }
188 }
189
190 ///////////////////////////////////////////////////////////////////////////
191 // Some sample folders
192
193 pub struct BottomUpFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a, F>
194     where F: FnMut(Ty<'tcx>) -> Ty<'tcx>
195 {
196     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
197     pub fldop: F,
198 }
199
200 impl<'a, 'gcx, 'tcx, F> TypeFolder<'gcx, 'tcx> for BottomUpFolder<'a, 'gcx, 'tcx, F>
201     where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
202 {
203     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
204
205     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
206         let t1 = ty.super_fold_with(self);
207         (self.fldop)(t1)
208     }
209 }
210
211 ///////////////////////////////////////////////////////////////////////////
212 // Region folder
213
214 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
215     /// Collects the free and escaping regions in `value` into `region_set`. Returns
216     /// whether any late-bound regions were skipped
217     pub fn collect_regions<T>(self,
218         value: &T,
219         region_set: &mut FxHashSet<&'tcx ty::Region>)
220         -> bool
221         where T : TypeFoldable<'tcx>
222     {
223         let mut have_bound_regions = false;
224         self.fold_regions(value, &mut have_bound_regions, |r, d| {
225             region_set.insert(self.mk_region(r.from_depth(d)));
226             r
227         });
228         have_bound_regions
229     }
230
231     /// Folds the escaping and free regions in `value` using `f`, and
232     /// sets `skipped_regions` to true if any late-bound region was found
233     /// and skipped.
234     pub fn fold_regions<T,F>(self,
235         value: &T,
236         skipped_regions: &mut bool,
237         mut f: F)
238         -> T
239         where F : FnMut(&'tcx ty::Region, u32) -> &'tcx ty::Region,
240               T : TypeFoldable<'tcx>,
241     {
242         value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
243     }
244 }
245
246 /// Folds over the substructure of a type, visiting its component
247 /// types and all regions that occur *free* within it.
248 ///
249 /// That is, `Ty` can contain function or method types that bind
250 /// regions at the call site (`ReLateBound`), and occurrences of
251 /// regions (aka "lifetimes") that are bound within a type are not
252 /// visited by this folder; only regions that occur free will be
253 /// visited by `fld_r`.
254
255 pub struct RegionFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
256     tcx: TyCtxt<'a, 'gcx, 'tcx>,
257     skipped_regions: &'a mut bool,
258     current_depth: u32,
259     fld_r: &'a mut (FnMut(&'tcx ty::Region, u32) -> &'tcx ty::Region + 'a),
260 }
261
262 impl<'a, 'gcx, 'tcx> RegionFolder<'a, 'gcx, 'tcx> {
263     pub fn new<F>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
264                   skipped_regions: &'a mut bool,
265                   fld_r: &'a mut F) -> RegionFolder<'a, 'gcx, 'tcx>
266         where F : FnMut(&'tcx ty::Region, u32) -> &'tcx ty::Region
267     {
268         RegionFolder {
269             tcx: tcx,
270             skipped_regions: skipped_regions,
271             current_depth: 1,
272             fld_r: fld_r,
273         }
274     }
275 }
276
277 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionFolder<'a, 'gcx, 'tcx> {
278     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
279
280     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
281         self.current_depth += 1;
282         let t = t.super_fold_with(self);
283         self.current_depth -= 1;
284         t
285     }
286
287     fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
288         match *r {
289             ty::ReLateBound(debruijn, _) if debruijn.depth < self.current_depth => {
290                 debug!("RegionFolder.fold_region({:?}) skipped bound region (current depth={})",
291                        r, self.current_depth);
292                 *self.skipped_regions = true;
293                 r
294             }
295             _ => {
296                 debug!("RegionFolder.fold_region({:?}) folding free region (current_depth={})",
297                        r, self.current_depth);
298                 (self.fld_r)(r, self.current_depth)
299             }
300         }
301     }
302 }
303
304 ///////////////////////////////////////////////////////////////////////////
305 // Late-bound region replacer
306
307 // Replaces the escaping regions in a type.
308
309 struct RegionReplacer<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
310     tcx: TyCtxt<'a, 'gcx, 'tcx>,
311     current_depth: u32,
312     fld_r: &'a mut (FnMut(ty::BoundRegion) -> &'tcx ty::Region + 'a),
313     map: FxHashMap<ty::BoundRegion, &'tcx ty::Region>
314 }
315
316 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
317     pub fn replace_late_bound_regions<T,F>(self,
318         value: &Binder<T>,
319         mut f: F)
320         -> (T, FxHashMap<ty::BoundRegion, &'tcx ty::Region>)
321         where F : FnMut(ty::BoundRegion) -> &'tcx ty::Region,
322               T : TypeFoldable<'tcx>,
323     {
324         let mut replacer = RegionReplacer::new(self, &mut f);
325         let result = value.skip_binder().fold_with(&mut replacer);
326         (result, replacer.map)
327     }
328
329
330     /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
331     /// `scope_id`.
332     pub fn liberate_late_bound_regions<T>(self,
333         all_outlive_scope: Option<region::CodeExtent>,
334         value: &Binder<T>)
335         -> T
336         where T : TypeFoldable<'tcx>
337     {
338         self.replace_late_bound_regions(value, |br| {
339             self.mk_region(ty::ReFree(ty::FreeRegion {
340                 scope: all_outlive_scope,
341                 bound_region: br
342             }))
343         }).0
344     }
345
346     /// Flattens two binding levels into one. So `for<'a> for<'b> Foo`
347     /// becomes `for<'a,'b> Foo`.
348     pub fn flatten_late_bound_regions<T>(self, bound2_value: &Binder<Binder<T>>)
349                                          -> Binder<T>
350         where T: TypeFoldable<'tcx>
351     {
352         let bound0_value = bound2_value.skip_binder().skip_binder();
353         let value = self.fold_regions(bound0_value, &mut false,
354                                       |region, current_depth| {
355             match *region {
356                 ty::ReLateBound(debruijn, br) if debruijn.depth >= current_depth => {
357                     // should be true if no escaping regions from bound2_value
358                     assert!(debruijn.depth - current_depth <= 1);
359                     self.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(current_depth), br))
360                 }
361                 _ => {
362                     region
363                 }
364             }
365         });
366         Binder(value)
367     }
368
369     pub fn no_late_bound_regions<T>(self, value: &Binder<T>) -> Option<T>
370         where T : TypeFoldable<'tcx>
371     {
372         if value.0.has_escaping_regions() {
373             None
374         } else {
375             Some(value.0.clone())
376         }
377     }
378
379     /// Returns a set of all late-bound regions that are constrained
380     /// by `value`, meaning that if we instantiate those LBR with
381     /// variables and equate `value` with something else, those
382     /// variables will also be equated.
383     pub fn collect_constrained_late_bound_regions<T>(&self, value: &Binder<T>)
384                                                      -> FxHashSet<ty::BoundRegion>
385         where T : TypeFoldable<'tcx>
386     {
387         self.collect_late_bound_regions(value, true)
388     }
389
390     /// Returns a set of all late-bound regions that appear in `value` anywhere.
391     pub fn collect_referenced_late_bound_regions<T>(&self, value: &Binder<T>)
392                                                     -> FxHashSet<ty::BoundRegion>
393         where T : TypeFoldable<'tcx>
394     {
395         self.collect_late_bound_regions(value, false)
396     }
397
398     fn collect_late_bound_regions<T>(&self, value: &Binder<T>, just_constraint: bool)
399                                      -> FxHashSet<ty::BoundRegion>
400         where T : TypeFoldable<'tcx>
401     {
402         let mut collector = LateBoundRegionsCollector::new(just_constraint);
403         let result = value.skip_binder().visit_with(&mut collector);
404         assert!(!result); // should never have stopped early
405         collector.regions
406     }
407
408     /// Replace any late-bound regions bound in `value` with `'erased`. Useful in trans but also
409     /// method lookup and a few other places where precise region relationships are not required.
410     pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
411         where T : TypeFoldable<'tcx>
412     {
413         self.replace_late_bound_regions(value, |_| self.types.re_erased).0
414     }
415
416     /// Rewrite any late-bound regions so that they are anonymous.  Region numbers are
417     /// assigned starting at 1 and increasing monotonically in the order traversed
418     /// by the fold operation.
419     ///
420     /// The chief purpose of this function is to canonicalize regions so that two
421     /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
422     /// structurally identical.  For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
423     /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
424     pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
425         where T : TypeFoldable<'tcx>,
426     {
427         let mut counter = 0;
428         Binder(self.replace_late_bound_regions(sig, |_| {
429             counter += 1;
430             self.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), ty::BrAnon(counter)))
431         }).0)
432     }
433 }
434
435 impl<'a, 'gcx, 'tcx> RegionReplacer<'a, 'gcx, 'tcx> {
436     fn new<F>(tcx: TyCtxt<'a, 'gcx, 'tcx>, fld_r: &'a mut F)
437               -> RegionReplacer<'a, 'gcx, 'tcx>
438         where F : FnMut(ty::BoundRegion) -> &'tcx ty::Region
439     {
440         RegionReplacer {
441             tcx: tcx,
442             current_depth: 1,
443             fld_r: fld_r,
444             map: FxHashMap()
445         }
446     }
447 }
448
449 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionReplacer<'a, 'gcx, 'tcx> {
450     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
451
452     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
453         self.current_depth += 1;
454         let t = t.super_fold_with(self);
455         self.current_depth -= 1;
456         t
457     }
458
459     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
460         if !t.has_regions_escaping_depth(self.current_depth-1) {
461             return t;
462         }
463
464         t.super_fold_with(self)
465     }
466
467     fn fold_region(&mut self, r:&'tcx  ty::Region) -> &'tcx ty::Region {
468         match *r {
469             ty::ReLateBound(debruijn, br) if debruijn.depth == self.current_depth => {
470                 let fld_r = &mut self.fld_r;
471                 let region = *self.map.entry(br).or_insert_with(|| fld_r(br));
472                 if let ty::ReLateBound(debruijn1, br) = *region {
473                     // If the callback returns a late-bound region,
474                     // that region should always use depth 1. Then we
475                     // adjust it to the correct depth.
476                     assert_eq!(debruijn1.depth, 1);
477                     self.tcx.mk_region(ty::ReLateBound(debruijn, br))
478                 } else {
479                     region
480                 }
481             }
482             _ => r
483         }
484     }
485 }
486
487 ///////////////////////////////////////////////////////////////////////////
488 // Region eraser
489
490 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
491     /// Returns an equivalent value with all free regions removed (note
492     /// that late-bound regions remain, because they are important for
493     /// subtyping, but they are anonymized and normalized as well)..
494     pub fn erase_regions<T>(self, value: &T) -> T
495         where T : TypeFoldable<'tcx>
496     {
497         let value1 = value.fold_with(&mut RegionEraser(self));
498         debug!("erase_regions({:?}) = {:?}",
499                value, value1);
500         return value1;
501
502         struct RegionEraser<'a, 'gcx: 'a+'tcx, 'tcx: 'a>(TyCtxt<'a, 'gcx, 'tcx>);
503
504         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionEraser<'a, 'gcx, 'tcx> {
505             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.0 }
506
507             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
508                 if let Some(u) = self.tcx().normalized_cache.borrow().get(&ty).cloned() {
509                     return u;
510                 }
511
512                 // FIXME(eddyb) should local contexts have a cache too?
513                 if let Some(ty_lifted) = self.tcx().lift_to_global(&ty) {
514                     let tcx = self.tcx().global_tcx();
515                     let t_norm = ty_lifted.super_fold_with(&mut RegionEraser(tcx));
516                     tcx.normalized_cache.borrow_mut().insert(ty_lifted, t_norm);
517                     t_norm
518                 } else {
519                     ty.super_fold_with(self)
520                 }
521             }
522
523             fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
524                 where T : TypeFoldable<'tcx>
525             {
526                 let u = self.tcx().anonymize_late_bound_regions(t);
527                 u.super_fold_with(self)
528             }
529
530             fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
531                 // because late-bound regions affect subtyping, we can't
532                 // erase the bound/free distinction, but we can replace
533                 // all free regions with 'erased.
534                 //
535                 // Note that we *CAN* replace early-bound regions -- the
536                 // type system never "sees" those, they get substituted
537                 // away. In trans, they will always be erased to 'erased
538                 // whenever a substitution occurs.
539                 match *r {
540                     ty::ReLateBound(..) => r,
541                     _ => self.tcx().types.re_erased
542                 }
543             }
544         }
545     }
546 }
547
548 ///////////////////////////////////////////////////////////////////////////
549 // Region shifter
550 //
551 // Shifts the De Bruijn indices on all escaping bound regions by a
552 // fixed amount. Useful in substitution or when otherwise introducing
553 // a binding level that is not intended to capture the existing bound
554 // regions. See comment on `shift_regions_through_binders` method in
555 // `subst.rs` for more details.
556
557 pub fn shift_region(region: ty::Region, amount: u32) -> ty::Region {
558     match region {
559         ty::ReLateBound(debruijn, br) => {
560             ty::ReLateBound(debruijn.shifted(amount), br)
561         }
562         _ => {
563             region
564         }
565     }
566 }
567
568 pub fn shift_region_ref<'a, 'gcx, 'tcx>(
569     tcx: TyCtxt<'a, 'gcx, 'tcx>,
570     region: &'tcx ty::Region,
571     amount: u32)
572     -> &'tcx ty::Region
573 {
574     match region {
575         &ty::ReLateBound(debruijn, br) if amount > 0 => {
576             tcx.mk_region(ty::ReLateBound(debruijn.shifted(amount), br))
577         }
578         _ => {
579             region
580         }
581     }
582 }
583
584 pub fn shift_regions<'a, 'gcx, 'tcx, T>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
585                                         amount: u32, value: &T) -> T
586     where T: TypeFoldable<'tcx>
587 {
588     debug!("shift_regions(value={:?}, amount={})",
589            value, amount);
590
591     value.fold_with(&mut RegionFolder::new(tcx, &mut false, &mut |region, _current_depth| {
592         shift_region_ref(tcx, region, amount)
593     }))
594 }
595
596 /// An "escaping region" is a bound region whose binder is not part of `t`.
597 ///
598 /// So, for example, consider a type like the following, which has two binders:
599 ///
600 ///    for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
601 ///    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
602 ///                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~  inner scope
603 ///
604 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
605 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
606 /// fn type*, that type has an escaping region: `'a`.
607 ///
608 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
609 /// we already use the term "free region". It refers to the regions that we use to represent bound
610 /// regions on a fn definition while we are typechecking its body.
611 ///
612 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
613 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
614 /// binding level, one is generally required to do some sort of processing to a bound region, such
615 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
616 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
617 /// for which this processing has not yet been done.
618 struct HasEscapingRegionsVisitor {
619     depth: u32,
620 }
621
622 impl<'tcx> TypeVisitor<'tcx> for HasEscapingRegionsVisitor {
623     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
624         self.depth += 1;
625         let result = t.super_visit_with(self);
626         self.depth -= 1;
627         result
628     }
629
630     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
631         t.region_depth > self.depth
632     }
633
634     fn visit_region(&mut self, r: &'tcx ty::Region) -> bool {
635         r.escapes_depth(self.depth)
636     }
637 }
638
639 struct HasTypeFlagsVisitor {
640     flags: ty::TypeFlags,
641 }
642
643 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
644     fn visit_ty(&mut self, t: Ty) -> bool {
645         let flags = t.flags.get();
646         debug!("HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}", t, flags, self.flags);
647         flags.intersects(self.flags)
648     }
649
650     fn visit_region(&mut self, r: &'tcx ty::Region) -> bool {
651         let flags = r.type_flags();
652         debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
653         flags.intersects(self.flags)
654     }
655 }
656
657 /// Collects all the late-bound regions it finds into a hash set.
658 struct LateBoundRegionsCollector {
659     current_depth: u32,
660     regions: FxHashSet<ty::BoundRegion>,
661     just_constrained: bool,
662 }
663
664 impl LateBoundRegionsCollector {
665     fn new(just_constrained: bool) -> Self {
666         LateBoundRegionsCollector {
667             current_depth: 1,
668             regions: FxHashSet(),
669             just_constrained: just_constrained,
670         }
671     }
672 }
673
674 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
675     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
676         self.current_depth += 1;
677         let result = t.super_visit_with(self);
678         self.current_depth -= 1;
679         result
680     }
681
682     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
683         // if we are only looking for "constrained" region, we have to
684         // ignore the inputs to a projection, as they may not appear
685         // in the normalized form
686         if self.just_constrained {
687             match t.sty {
688                 ty::TyProjection(..) | ty::TyAnon(..) => { return false; }
689                 _ => { }
690             }
691         }
692
693         t.super_visit_with(self)
694     }
695
696     fn visit_region(&mut self, r: &'tcx ty::Region) -> bool {
697         match *r {
698             ty::ReLateBound(debruijn, br) if debruijn.depth == self.current_depth => {
699                 self.regions.insert(br);
700             }
701             _ => { }
702         }
703         false
704     }
705 }