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