]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/fold.rs
Various minor/cosmetic improvements to code
[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_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
71         self.visit_with(&mut HasEscapingVarsVisitor { 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_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
77         self.has_vars_bound_at_or_above(binder.shifted_in(1))
78     }
79
80     fn has_escaping_bound_vars(&self) -> bool {
81         self.has_vars_bound_at_or_above(ty::INNERMOST)
82     }
83
84     fn has_type_flags(&self, flags: TypeFlags) -> bool {
85         self.visit_with(&mut HasTypeFlagsVisitor { 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_placeholders(&self) -> bool {
106         self.has_type_flags(TypeFlags::HAS_RE_PLACEHOLDER | TypeFlags::HAS_TY_PLACEHOLDER)
107     }
108     fn needs_subst(&self) -> bool {
109         self.has_type_flags(TypeFlags::NEEDS_SUBST)
110     }
111     fn has_re_placeholders(&self) -> bool {
112         self.has_type_flags(TypeFlags::HAS_RE_PLACEHOLDER)
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, G>
204     where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
205           G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
206 {
207     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
208     pub fldop: F,
209     pub reg_op: G,
210 }
211
212 impl<'a, 'gcx, 'tcx, F, G> TypeFolder<'gcx, 'tcx> for BottomUpFolder<'a, 'gcx, 'tcx, F, G>
213     where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
214           G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
215 {
216     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
217
218     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
219         let t1 = ty.super_fold_with(self);
220         (self.fldop)(t1)
221     }
222
223     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
224         let r = r.super_fold_with(self);
225         (self.reg_op)(r)
226     }
227 }
228
229 ///////////////////////////////////////////////////////////////////////////
230 // Region folder
231
232 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
233     /// Collects the free and escaping regions in `value` into `region_set`. Returns
234     /// whether any late-bound regions were skipped
235     pub fn collect_regions<T>(self,
236         value: &T,
237         region_set: &mut FxHashSet<ty::Region<'tcx>>)
238         -> bool
239         where T : TypeFoldable<'tcx>
240     {
241         let mut have_bound_regions = false;
242         self.fold_regions(value, &mut have_bound_regions, |r, d| {
243             region_set.insert(self.mk_region(r.shifted_out_to_binder(d)));
244             r
245         });
246         have_bound_regions
247     }
248
249     /// Folds the escaping and free regions in `value` using `f`, and
250     /// sets `skipped_regions` to true if any late-bound region was found
251     /// and skipped.
252     pub fn fold_regions<T>(
253         self,
254         value: &T,
255         skipped_regions: &mut bool,
256         mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
257     ) -> T
258     where
259         T : TypeFoldable<'tcx>,
260     {
261         value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
262     }
263
264     /// Invoke `callback` on every region appearing free in `value`.
265     pub fn for_each_free_region(
266         self,
267         value: &impl TypeFoldable<'tcx>,
268         mut callback: impl FnMut(ty::Region<'tcx>),
269     ) {
270         self.any_free_region_meets(value, |r| {
271             callback(r);
272             false
273         });
274     }
275
276     /// True if `callback` returns true for every region appearing free in `value`.
277     pub fn all_free_regions_meet(
278         self,
279         value: &impl TypeFoldable<'tcx>,
280         mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
281     ) -> bool {
282         !self.any_free_region_meets(value, |r| !callback(r))
283     }
284
285     /// True if `callback` returns true for some region appearing free in `value`.
286     pub fn any_free_region_meets(
287         self,
288         value: &impl TypeFoldable<'tcx>,
289         callback: impl FnMut(ty::Region<'tcx>) -> bool,
290     ) -> bool {
291         return value.visit_with(&mut RegionVisitor {
292             outer_index: ty::INNERMOST,
293             callback
294         });
295
296         struct RegionVisitor<F> {
297             /// The index of a binder *just outside* the things we have
298             /// traversed. If we encounter a bound region bound by this
299             /// binder or one outer to it, it appears free. Example:
300             ///
301             /// ```
302             ///    for<'a> fn(for<'b> fn(), T)
303             /// ^          ^          ^     ^
304             /// |          |          |     | here, would be shifted in 1
305             /// |          |          | here, would be shifted in 2
306             /// |          | here, would be INNERMOST shifted in by 1
307             /// | here, initially, binder would be INNERMOST
308             /// ```
309             ///
310             /// You see that, initially, *any* bound value is free,
311             /// because we've not traversed any binders. As we pass
312             /// through a binder, we shift the `outer_index` by 1 to
313             /// account for the new binder that encloses us.
314             outer_index: ty::DebruijnIndex,
315             callback: F,
316         }
317
318         impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
319             where F: FnMut(ty::Region<'tcx>) -> bool
320         {
321             fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
322                 self.outer_index.shift_in(1);
323                 let result = t.skip_binder().visit_with(self);
324                 self.outer_index.shift_out(1);
325                 result
326             }
327
328             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
329                 match *r {
330                     ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
331                         false // ignore bound regions, keep visiting
332                     }
333                     _ => (self.callback)(r),
334                 }
335             }
336
337             fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
338                 // We're only interested in types involving regions
339                 if ty.flags.intersects(TypeFlags::HAS_FREE_REGIONS) {
340                     ty.super_visit_with(self)
341                 } else {
342                     false // keep visiting
343                 }
344             }
345         }
346     }
347 }
348
349 /// Folds over the substructure of a type, visiting its component
350 /// types and all regions that occur *free* within it.
351 ///
352 /// That is, `Ty` can contain function or method types that bind
353 /// regions at the call site (`ReLateBound`), and occurrences of
354 /// regions (aka "lifetimes") that are bound within a type are not
355 /// visited by this folder; only regions that occur free will be
356 /// visited by `fld_r`.
357
358 pub struct RegionFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
359     tcx: TyCtxt<'a, 'gcx, 'tcx>,
360     skipped_regions: &'a mut bool,
361
362     /// Stores the index of a binder *just outside* the stuff we have
363     /// visited.  So this begins as INNERMOST; when we pass through a
364     /// binder, it is incremented (via `shift_in`).
365     current_index: ty::DebruijnIndex,
366
367     /// Callback invokes for each free region. The `DebruijnIndex`
368     /// points to the binder *just outside* the ones we have passed
369     /// through.
370     fold_region_fn: &'a mut (dyn FnMut(
371         ty::Region<'tcx>,
372         ty::DebruijnIndex,
373     ) -> ty::Region<'tcx> + 'a),
374 }
375
376 impl<'a, 'gcx, 'tcx> RegionFolder<'a, 'gcx, 'tcx> {
377     #[inline]
378     pub fn new(
379         tcx: TyCtxt<'a, 'gcx, 'tcx>,
380         skipped_regions: &'a mut bool,
381         fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
382     ) -> RegionFolder<'a, 'gcx, 'tcx> {
383         RegionFolder {
384             tcx,
385             skipped_regions,
386             current_index: ty::INNERMOST,
387             fold_region_fn,
388         }
389     }
390 }
391
392 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionFolder<'a, 'gcx, 'tcx> {
393     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
394
395     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
396         self.current_index.shift_in(1);
397         let t = t.super_fold_with(self);
398         self.current_index.shift_out(1);
399         t
400     }
401
402     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
403         match *r {
404             ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
405                 debug!("RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
406                        r, self.current_index);
407                 *self.skipped_regions = true;
408                 r
409             }
410             _ => {
411                 debug!("RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
412                        r, self.current_index);
413                 (self.fold_region_fn)(r, self.current_index)
414             }
415         }
416     }
417 }
418
419 ///////////////////////////////////////////////////////////////////////////
420 // Bound vars replacer
421
422 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
423 struct BoundVarReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
424     tcx: TyCtxt<'a, 'gcx, 'tcx>,
425
426     /// As with `RegionFolder`, represents the index of a binder *just outside*
427     /// the ones we have visited.
428     current_index: ty::DebruijnIndex,
429
430     fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
431     fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> ty::Ty<'tcx> + 'a),
432 }
433
434 impl<'a, 'gcx, 'tcx> BoundVarReplacer<'a, 'gcx, 'tcx> {
435     fn new<F, G>(
436         tcx: TyCtxt<'a, 'gcx, 'tcx>,
437         fld_r: &'a mut F,
438         fld_t: &'a mut G
439     ) -> Self
440         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
441               G: FnMut(ty::BoundTy) -> ty::Ty<'tcx>
442     {
443         BoundVarReplacer {
444             tcx,
445             current_index: ty::INNERMOST,
446             fld_r,
447             fld_t,
448         }
449     }
450 }
451
452 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for BoundVarReplacer<'a, 'gcx, 'tcx> {
453     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
454
455     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
456         self.current_index.shift_in(1);
457         let t = t.super_fold_with(self);
458         self.current_index.shift_out(1);
459         t
460     }
461
462     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
463         match t.sty {
464             ty::Bound(debruijn, bound_ty) => {
465                 if debruijn == self.current_index {
466                     let fld_t = &mut self.fld_t;
467                     let ty = fld_t(bound_ty);
468                     ty::fold::shift_vars(
469                         self.tcx,
470                         &ty,
471                         self.current_index.as_u32()
472                     )
473                 } else {
474                     t
475                 }
476             }
477             _ => {
478                 if !t.has_vars_bound_at_or_above(self.current_index) {
479                     // Nothing more to substitute.
480                     t
481                 } else {
482                     t.super_fold_with(self)
483                 }
484             }
485         }
486     }
487
488     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
489         match *r {
490             ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
491                 let fld_r = &mut self.fld_r;
492                 let region = fld_r(br);
493                 if let ty::ReLateBound(debruijn1, br) = *region {
494                     // If the callback returns a late-bound region,
495                     // that region should always use the INNERMOST
496                     // debruijn index. Then we adjust it to the
497                     // correct depth.
498                     assert_eq!(debruijn1, ty::INNERMOST);
499                     self.tcx.mk_region(ty::ReLateBound(debruijn, br))
500                 } else {
501                     region
502                 }
503             }
504             _ => r
505         }
506     }
507 }
508
509 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
510     /// Replace all regions bound by the given `Binder` with the
511     /// results returned by the closure; the closure is expected to
512     /// return a free region (relative to this binder), and hence the
513     /// binder is removed in the return type. The closure is invoked
514     /// once for each unique `BoundRegion`; multiple references to the
515     /// same `BoundRegion` will reuse the previous result.  A map is
516     /// returned at the end with each bound region and the free region
517     /// that replaced it.
518     ///
519     /// This method only replaces late bound regions and the result may still
520     /// contain escaping bound types.
521     pub fn replace_late_bound_regions<T, F>(
522         self,
523         value: &Binder<T>,
524         fld_r: F
525     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
526         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
527               T: TypeFoldable<'tcx>
528     {
529         // identity for bound types
530         let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
531         self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t)
532     }
533
534     /// Replace all escaping bound vars. The `fld_r` closure replaces escaping
535     /// bound regions while the `fld_t` closure replaces escaping bound types.
536     pub fn replace_escaping_bound_vars<T, F, G>(
537         self,
538         value: &T,
539         mut fld_r: F,
540         mut fld_t: G
541     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
542         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
543               G: FnMut(ty::BoundTy) -> ty::Ty<'tcx>,
544               T: TypeFoldable<'tcx>
545     {
546         let mut map = BTreeMap::new();
547
548         if !value.has_escaping_bound_vars() {
549             (value.clone(), map)
550         } else {
551             let mut real_fld_r = |br| {
552                 *map.entry(br).or_insert_with(|| fld_r(br))
553             };
554
555             let mut replacer = BoundVarReplacer::new(self, &mut real_fld_r, &mut fld_t);
556             let result = value.fold_with(&mut replacer);
557             (result, map)
558         }
559     }
560
561     /// Replace all types or regions bound by the given `Binder`. The `fld_r`
562     /// closure replaces bound regions while the `fld_t` closure replaces bound
563     /// types.
564     pub fn replace_bound_vars<T, F, G>(
565         self,
566         value: &Binder<T>,
567         fld_r: F,
568         fld_t: G
569     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
570         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
571               G: FnMut(ty::BoundTy) -> ty::Ty<'tcx>,
572               T: TypeFoldable<'tcx>
573     {
574         self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t)
575     }
576
577     /// Replace any late-bound regions bound in `value` with
578     /// free variants attached to `all_outlive_scope`.
579     pub fn liberate_late_bound_regions<T>(
580         &self,
581         all_outlive_scope: DefId,
582         value: &ty::Binder<T>
583     ) -> T
584     where T: TypeFoldable<'tcx> {
585         self.replace_late_bound_regions(value, |br| {
586             self.mk_region(ty::ReFree(ty::FreeRegion {
587                 scope: all_outlive_scope,
588                 bound_region: br
589             }))
590         }).0
591     }
592
593     /// Flattens multiple binding levels into one. So `for<'a> for<'b> Foo`
594     /// becomes `for<'a,'b> Foo`.
595     pub fn flatten_late_bound_regions<T>(self, bound2_value: &Binder<Binder<T>>)
596                                          -> Binder<T>
597         where T: TypeFoldable<'tcx>
598     {
599         let bound0_value = bound2_value.skip_binder().skip_binder();
600         let value = self.fold_regions(bound0_value, &mut false, |region, current_depth| {
601             match *region {
602                 ty::ReLateBound(debruijn, br) => {
603                     // We assume no regions bound *outside* of the
604                     // binders in `bound2_value` (nmatsakis added in
605                     // the course of this PR; seems like a reasonable
606                     // sanity check though).
607                     assert!(debruijn == current_depth);
608                     self.mk_region(ty::ReLateBound(current_depth, br))
609                 }
610                 _ => {
611                     region
612                 }
613             }
614         });
615         Binder::bind(value)
616     }
617
618     /// Returns a set of all late-bound regions that are constrained
619     /// by `value`, meaning that if we instantiate those LBR with
620     /// variables and equate `value` with something else, those
621     /// variables will also be equated.
622     pub fn collect_constrained_late_bound_regions<T>(&self, value: &Binder<T>)
623                                                      -> FxHashSet<ty::BoundRegion>
624         where T : TypeFoldable<'tcx>
625     {
626         self.collect_late_bound_regions(value, true)
627     }
628
629     /// Returns a set of all late-bound regions that appear in `value` anywhere.
630     pub fn collect_referenced_late_bound_regions<T>(&self, value: &Binder<T>)
631                                                     -> FxHashSet<ty::BoundRegion>
632         where T : TypeFoldable<'tcx>
633     {
634         self.collect_late_bound_regions(value, false)
635     }
636
637     fn collect_late_bound_regions<T>(&self, value: &Binder<T>, just_constraint: bool)
638                                      -> FxHashSet<ty::BoundRegion>
639         where T : TypeFoldable<'tcx>
640     {
641         let mut collector = LateBoundRegionsCollector::new(just_constraint);
642         let result = value.skip_binder().visit_with(&mut collector);
643         assert!(!result); // should never have stopped early
644         collector.regions
645     }
646
647     /// Replace any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
648     /// method lookup and a few other places where precise region relationships are not required.
649     pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
650         where T : TypeFoldable<'tcx>
651     {
652         self.replace_late_bound_regions(value, |_| self.types.re_erased).0
653     }
654
655     /// Rewrite any late-bound regions so that they are anonymous.  Region numbers are
656     /// assigned starting at 1 and increasing monotonically in the order traversed
657     /// by the fold operation.
658     ///
659     /// The chief purpose of this function is to canonicalize regions so that two
660     /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
661     /// structurally identical.  For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
662     /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
663     pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
664         where T : TypeFoldable<'tcx>,
665     {
666         let mut counter = 0;
667         Binder::bind(self.replace_late_bound_regions(sig, |_| {
668             counter += 1;
669             self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)))
670         }).0)
671     }
672 }
673
674 ///////////////////////////////////////////////////////////////////////////
675 // Shifter
676 //
677 // Shifts the De Bruijn indices on all escaping bound vars by a
678 // fixed amount. Useful in substitution or when otherwise introducing
679 // a binding level that is not intended to capture the existing bound
680 // vars. See comment on `shift_vars_through_binders` method in
681 // `subst.rs` for more details.
682
683 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
684 enum Direction {
685     In,
686     Out,
687 }
688
689 struct Shifter<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
690     tcx: TyCtxt<'a, 'gcx, 'tcx>,
691     current_index: ty::DebruijnIndex,
692     amount: u32,
693     direction: Direction,
694 }
695
696 impl Shifter<'a, 'gcx, 'tcx> {
697     pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, amount: u32, direction: Direction) -> Self {
698         Shifter {
699             tcx,
700             current_index: ty::INNERMOST,
701             amount,
702             direction,
703         }
704     }
705 }
706
707 impl TypeFolder<'gcx, 'tcx> for Shifter<'a, 'gcx, 'tcx> {
708     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
709
710     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
711         self.current_index.shift_in(1);
712         let t = t.super_fold_with(self);
713         self.current_index.shift_out(1);
714         t
715     }
716
717     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
718         match *r {
719             ty::ReLateBound(debruijn, br) => {
720                 if self.amount == 0 || debruijn < self.current_index {
721                     r
722                 } else {
723                     let debruijn = match self.direction {
724                         Direction::In => debruijn.shifted_in(self.amount),
725                         Direction::Out => {
726                             assert!(debruijn.as_u32() >= self.amount);
727                             debruijn.shifted_out(self.amount)
728                         }
729                     };
730                     let shifted = ty::ReLateBound(debruijn, br);
731                     self.tcx.mk_region(shifted)
732                 }
733             }
734             _ => r
735         }
736     }
737
738     fn fold_ty(&mut self, ty: ty::Ty<'tcx>) -> ty::Ty<'tcx> {
739         match ty.sty {
740             ty::Bound(debruijn, bound_ty) => {
741                 if self.amount == 0 || debruijn < self.current_index {
742                     ty
743                 } else {
744                     let debruijn = match self.direction {
745                         Direction::In => debruijn.shifted_in(self.amount),
746                         Direction::Out => {
747                             assert!(debruijn.as_u32() >= self.amount);
748                             debruijn.shifted_out(self.amount)
749                         }
750                     };
751                     self.tcx.mk_ty(
752                         ty::Bound(debruijn, bound_ty)
753                     )
754                 }
755             }
756
757             _ => ty.super_fold_with(self),
758         }
759     }
760 }
761
762 pub fn shift_region<'a, 'gcx, 'tcx>(
763     tcx: TyCtxt<'a, 'gcx, 'tcx>,
764     region: ty::Region<'tcx>,
765     amount: u32
766 ) -> ty::Region<'tcx> {
767     match region {
768         ty::ReLateBound(debruijn, br) if amount > 0 => {
769             tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
770         }
771         _ => {
772             region
773         }
774     }
775 }
776
777 pub fn shift_vars<'a, 'gcx, 'tcx, T>(
778     tcx: TyCtxt<'a, 'gcx, 'tcx>,
779     value: &T,
780     amount: u32
781 ) -> T where T: TypeFoldable<'tcx> {
782     debug!("shift_vars(value={:?}, amount={})",
783            value, amount);
784
785     value.fold_with(&mut Shifter::new(tcx, amount, Direction::In))
786 }
787
788 pub fn shift_out_vars<'a, 'gcx, 'tcx, T>(
789     tcx: TyCtxt<'a, 'gcx, 'tcx>,
790     value: &T,
791     amount: u32
792 ) -> T where T: TypeFoldable<'tcx> {
793     debug!("shift_out_vars(value={:?}, amount={})",
794            value, amount);
795
796     value.fold_with(&mut Shifter::new(tcx, amount, Direction::Out))
797 }
798
799 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
800 /// bound region or a bound type.
801 ///
802 /// So, for example, consider a type like the following, which has two binders:
803 ///
804 ///    for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
805 ///    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
806 ///                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~  inner scope
807 ///
808 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
809 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
810 /// fn type*, that type has an escaping region: `'a`.
811 ///
812 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
813 /// we already use the term "free var". It refers to the regions or types that we use to represent
814 /// bound regions or type params on a fn definition while we are type checking its body.
815 ///
816 /// To clarify, conceptually there is no particular difference between
817 /// an "escaping" var and a "free" var. However, there is a big
818 /// difference in practice. Basically, when "entering" a binding
819 /// level, one is generally required to do some sort of processing to
820 /// a bound var, such as replacing it with a fresh/placeholder
821 /// var, or making an entry in the environment to represent the
822 /// scope to which it is attached, etc. An escaping var represents
823 /// a bound var for which this processing has not yet been done.
824 struct HasEscapingVarsVisitor {
825     /// Anything bound by `outer_index` or "above" is escaping
826     outer_index: ty::DebruijnIndex,
827 }
828
829 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
830     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
831         self.outer_index.shift_in(1);
832         let result = t.super_visit_with(self);
833         self.outer_index.shift_out(1);
834         result
835     }
836
837     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
838         // If the outer-exclusive-binder is *strictly greater* than
839         // `outer_index`, that means that `t` contains some content
840         // bound at `outer_index` or above (because
841         // `outer_exclusive_binder` is always 1 higher than the
842         // content in `t`). Therefore, `t` has some escaping vars.
843         t.outer_exclusive_binder > self.outer_index
844     }
845
846     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
847         // If the region is bound by `outer_index` or anything outside
848         // of outer index, then it escapes the binders we have
849         // visited.
850         r.bound_at_or_above_binder(self.outer_index)
851     }
852 }
853
854 struct HasTypeFlagsVisitor {
855     flags: ty::TypeFlags,
856 }
857
858 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
859     fn visit_ty(&mut self, t: Ty<'_>) -> bool {
860         debug!("HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}", t, t.flags, self.flags);
861         t.flags.intersects(self.flags)
862     }
863
864     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
865         let flags = r.type_flags();
866         debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
867         flags.intersects(self.flags)
868     }
869
870     fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
871         if let ConstValue::Unevaluated(..) = c.val {
872             let projection_flags = TypeFlags::HAS_NORMALIZABLE_PROJECTION |
873                 TypeFlags::HAS_PROJECTION;
874             if projection_flags.intersects(self.flags) {
875                 return true;
876             }
877         }
878         c.super_visit_with(self)
879     }
880 }
881
882 /// Collects all the late-bound regions at the innermost binding level
883 /// into a hash set.
884 struct LateBoundRegionsCollector {
885     current_index: ty::DebruijnIndex,
886     regions: FxHashSet<ty::BoundRegion>,
887
888     /// If true, we only want regions that are known to be
889     /// "constrained" when you equate this type with another type. In
890     /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
891     /// them constraints `'a == 'b`.  But if you have `<&'a u32 as
892     /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
893     /// types may mean that `'a` and `'b` don't appear in the results,
894     /// so they are not considered *constrained*.
895     just_constrained: bool,
896 }
897
898 impl LateBoundRegionsCollector {
899     fn new(just_constrained: bool) -> Self {
900         LateBoundRegionsCollector {
901             current_index: ty::INNERMOST,
902             regions: Default::default(),
903             just_constrained,
904         }
905     }
906 }
907
908 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
909     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
910         self.current_index.shift_in(1);
911         let result = t.super_visit_with(self);
912         self.current_index.shift_out(1);
913         result
914     }
915
916     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
917         // if we are only looking for "constrained" region, we have to
918         // ignore the inputs to a projection, as they may not appear
919         // in the normalized form
920         if self.just_constrained {
921             match t.sty {
922                 ty::Projection(..) | ty::Opaque(..) => { return false; }
923                 _ => { }
924             }
925         }
926
927         t.super_visit_with(self)
928     }
929
930     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
931         if let ty::ReLateBound(debruijn, br) = *r {
932              if debruijn == self.current_index {
933                 self.regions.insert(br);
934             }
935         }
936         false
937     }
938 }