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