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