]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/fold.rs
Add stubs for `fold_const`
[rust.git] / src / librustc / ty / fold.rs
1 //! Generalized type folding mechanism. The setup is a bit convoluted
2 //! but allows for convenient usage. Let T be an instance of some
3 //! "foldable type" (one which implements `TypeFoldable`) and F be an
4 //! instance of a "folder" (a type which implements `TypeFolder`). Then
5 //! the setup is intended to be:
6 //!
7 //!     T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
8 //!
9 //! This way, when you define a new folder F, you can override
10 //! `fold_T()` to customize the behavior, and invoke `T.super_fold_with()`
11 //! to get the original behavior. Meanwhile, to actually fold
12 //! something, you can just write `T.fold_with(F)`, which is
13 //! convenient. (Note that `fold_with` will also transparently handle
14 //! things like a `Vec<T>` where T is foldable and so on.)
15 //!
16 //! In this ideal setup, the only function that actually *does*
17 //! anything is `T.super_fold_with()`, which traverses the type `T`.
18 //! Moreover, `T.super_fold_with()` should only ever call `T.fold_with()`.
19 //!
20 //! In some cases, we follow a degenerate pattern where we do not have
21 //! a `fold_T` method. Instead, `T.fold_with` traverses the structure directly.
22 //! This is suboptimal because the behavior cannot be overridden, but it's
23 //! much less work to implement. If you ever *do* need an override that
24 //! doesn't exist, it's not hard to convert the degenerate pattern into the
25 //! proper thing.
26 //!
27 //! A `TypeFoldable` T can also be visited by a `TypeVisitor` V using similar setup:
28 //!
29 //!     T.visit_with(V) --calls--> V.visit_T(T) --calls--> T.super_visit_with(V).
30 //!
31 //! These methods return true to indicate that the visitor has found what it is
32 //! looking for, and does not need to visit anything else.
33
34 use crate::hir::def_id::DefId;
35 use crate::ty::{self, Binder, Ty, TyCtxt, TypeFlags, flags::FlagComputation};
36
37 use std::collections::BTreeMap;
38 use std::fmt;
39 use crate::util::nodemap::FxHashSet;
40
41 /// The TypeFoldable trait is implemented for every type that can be folded.
42 /// Basically, every type that has a corresponding method in TypeFolder.
43 ///
44 /// To implement this conveniently, use the
45 /// `BraceStructTypeFoldableImpl` etc macros found in `macros.rs`.
46 pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
47     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self;
48     fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
49         self.super_fold_with(folder)
50     }
51
52     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool;
53     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
54         self.super_visit_with(visitor)
55     }
56
57     /// Returns `true` if `self` has any late-bound regions that are either
58     /// bound by `binder` or bound by some binder outside of `binder`.
59     /// If `binder` is `ty::INNERMOST`, this indicates whether
60     /// there are any late-bound regions that appear free.
61     fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
62         self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder })
63     }
64
65     /// Returns `true` if this `self` has any regions that escape `binder` (and
66     /// hence are not bound by it).
67     fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
68         self.has_vars_bound_at_or_above(binder.shifted_in(1))
69     }
70
71     fn has_escaping_bound_vars(&self) -> bool {
72         self.has_vars_bound_at_or_above(ty::INNERMOST)
73     }
74
75     fn has_type_flags(&self, flags: TypeFlags) -> bool {
76         self.visit_with(&mut HasTypeFlagsVisitor { flags })
77     }
78     fn has_projections(&self) -> bool {
79         self.has_type_flags(TypeFlags::HAS_PROJECTION)
80     }
81     fn references_error(&self) -> bool {
82         self.has_type_flags(TypeFlags::HAS_TY_ERR)
83     }
84     fn has_param_types(&self) -> bool {
85         self.has_type_flags(TypeFlags::HAS_PARAMS)
86     }
87     fn has_self_ty(&self) -> bool {
88         self.has_type_flags(TypeFlags::HAS_SELF)
89     }
90     fn has_infer_types(&self) -> bool {
91         self.has_type_flags(TypeFlags::HAS_TY_INFER)
92     }
93     fn needs_infer(&self) -> bool {
94         self.has_type_flags(
95             TypeFlags::HAS_TY_INFER | TypeFlags::HAS_RE_INFER | TypeFlags::HAS_CT_INFER
96         )
97     }
98     fn has_placeholders(&self) -> bool {
99         self.has_type_flags(TypeFlags::HAS_RE_PLACEHOLDER | TypeFlags::HAS_TY_PLACEHOLDER)
100     }
101     fn needs_subst(&self) -> bool {
102         self.has_type_flags(TypeFlags::NEEDS_SUBST)
103     }
104     fn has_re_placeholders(&self) -> bool {
105         self.has_type_flags(TypeFlags::HAS_RE_PLACEHOLDER)
106     }
107     fn has_closure_types(&self) -> bool {
108         self.has_type_flags(TypeFlags::HAS_TY_CLOSURE)
109     }
110     /// "Free" regions in this context means that it has any region
111     /// that is not (a) erased or (b) late-bound.
112     fn has_free_regions(&self) -> bool {
113         self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
114     }
115
116     /// True if there are any un-erased free regions.
117     fn has_erasable_regions(&self) -> bool {
118         self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
119     }
120
121     /// Indicates whether this value references only 'global'
122     /// generic parameters that are the same regardless of what fn we are
123     /// in. This is used for caching.
124     fn is_global(&self) -> bool {
125         !self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
126     }
127
128     /// True if there are any late-bound regions
129     fn has_late_bound_regions(&self) -> bool {
130         self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
131     }
132
133     /// A visitor that does not recurse into types, works like `fn walk_shallow` in `Ty`.
134     fn visit_tys_shallow(&self, visit: impl FnMut(Ty<'tcx>) -> bool) -> bool {
135
136         pub struct Visitor<F>(F);
137
138         impl<'tcx, F: FnMut(Ty<'tcx>) -> bool> TypeVisitor<'tcx> for Visitor<F> {
139             fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
140                 self.0(ty)
141             }
142         }
143
144         self.visit_with(&mut Visitor(visit))
145     }
146 }
147
148 /// The `TypeFolder` trait defines the actual *folding*. There is a
149 /// method defined for every foldable type. Each of these has a
150 /// default implementation that does an "identity" fold. Within each
151 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
152 /// sub-item.
153 pub trait TypeFolder<'gcx: 'tcx, 'tcx> : Sized {
154     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
155
156     fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
157         where T : TypeFoldable<'tcx>
158     {
159         t.super_fold_with(self)
160     }
161
162     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
163         t.super_fold_with(self)
164     }
165
166     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
167         r.super_fold_with(self)
168     }
169
170     fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
171         c.super_fold_with(self)
172     }
173 }
174
175 pub trait TypeVisitor<'tcx> : Sized {
176     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
177         t.super_visit_with(self)
178     }
179
180     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
181         t.super_visit_with(self)
182     }
183
184     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
185         r.super_visit_with(self)
186     }
187
188     fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
189         c.super_visit_with(self)
190     }
191 }
192
193 ///////////////////////////////////////////////////////////////////////////
194 // Some sample folders
195
196 pub struct BottomUpFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a, F, G, H>
197     where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
198           G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
199           H: FnMut(&'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx>,
200 {
201     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
202     pub ty_op: F,
203     pub lt_op: G,
204     pub ct_op: H,
205 }
206
207 impl<'a, 'gcx, 'tcx, F, G, H> TypeFolder<'gcx, 'tcx> for BottomUpFolder<'a, 'gcx, 'tcx, F, G, H>
208     where F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
209           G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
210           H: FnMut(&'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx>,
211 {
212     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
213
214     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
215         let t = ty.super_fold_with(self);
216         (self.ty_op)(t)
217     }
218
219     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
220         let r = r.super_fold_with(self);
221         (self.lt_op)(r)
222     }
223
224     fn fold_const(&mut self, c: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx> {
225         let c = c.super_fold_with(self);
226         (self.ct_op)(c)
227     }
228 }
229
230 ///////////////////////////////////////////////////////////////////////////
231 // Region folder
232
233 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
234     /// Collects the free and escaping regions in `value` into `region_set`. Returns
235     /// whether any late-bound regions were skipped
236     pub fn collect_regions<T>(self,
237         value: &T,
238         region_set: &mut FxHashSet<ty::Region<'tcx>>)
239         -> bool
240         where T : TypeFoldable<'tcx>
241     {
242         let mut have_bound_regions = false;
243         self.fold_regions(value, &mut have_bound_regions, |r, d| {
244             region_set.insert(self.mk_region(r.shifted_out_to_binder(d)));
245             r
246         });
247         have_bound_regions
248     }
249
250     /// Folds the escaping and free regions in `value` using `f`, and
251     /// sets `skipped_regions` to true if any late-bound region was found
252     /// and skipped.
253     pub fn fold_regions<T>(
254         self,
255         value: &T,
256         skipped_regions: &mut bool,
257         mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
258     ) -> T
259     where
260         T : TypeFoldable<'tcx>,
261     {
262         value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
263     }
264
265     /// Invoke `callback` on every region appearing free in `value`.
266     pub fn for_each_free_region(
267         self,
268         value: &impl TypeFoldable<'tcx>,
269         mut callback: impl FnMut(ty::Region<'tcx>),
270     ) {
271         self.any_free_region_meets(value, |r| {
272             callback(r);
273             false
274         });
275     }
276
277     /// Returns `true` if `callback` returns true for every region appearing free in `value`.
278     pub fn all_free_regions_meet(
279         self,
280         value: &impl TypeFoldable<'tcx>,
281         mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
282     ) -> bool {
283         !self.any_free_region_meets(value, |r| !callback(r))
284     }
285
286     /// Returns `true` if `callback` returns true for some region appearing free in `value`.
287     pub fn any_free_region_meets(
288         self,
289         value: &impl TypeFoldable<'tcx>,
290         callback: impl FnMut(ty::Region<'tcx>) -> bool,
291     ) -> bool {
292         return value.visit_with(&mut RegionVisitor {
293             outer_index: ty::INNERMOST,
294             callback
295         });
296
297         struct RegionVisitor<F> {
298             /// The index of a binder *just outside* the things we have
299             /// traversed. If we encounter a bound region bound by this
300             /// binder or one outer to it, it appears free. Example:
301             ///
302             /// ```
303             ///    for<'a> fn(for<'b> fn(), T)
304             /// ^          ^          ^     ^
305             /// |          |          |     | here, would be shifted in 1
306             /// |          |          | here, would be shifted in 2
307             /// |          | here, would be `INNERMOST` shifted in by 1
308             /// | here, initially, binder would be `INNERMOST`
309             /// ```
310             ///
311             /// You see that, initially, *any* bound value is free,
312             /// because we've not traversed any binders. As we pass
313             /// through a binder, we shift the `outer_index` by 1 to
314             /// account for the new binder that encloses us.
315             outer_index: ty::DebruijnIndex,
316             callback: F,
317         }
318
319         impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
320             where F: FnMut(ty::Region<'tcx>) -> bool
321         {
322             fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
323                 self.outer_index.shift_in(1);
324                 let result = t.skip_binder().visit_with(self);
325                 self.outer_index.shift_out(1);
326                 result
327             }
328
329             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
330                 match *r {
331                     ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
332                         false // ignore bound regions, keep visiting
333                     }
334                     _ => (self.callback)(r),
335                 }
336             }
337
338             fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
339                 // We're only interested in types involving regions
340                 if ty.flags.intersects(TypeFlags::HAS_FREE_REGIONS) {
341                     ty.super_visit_with(self)
342                 } else {
343                     false // keep visiting
344                 }
345             }
346         }
347     }
348 }
349
350 /// Folds over the substructure of a type, visiting its component
351 /// types and all regions that occur *free* within it.
352 ///
353 /// That is, `Ty` can contain function or method types that bind
354 /// regions at the call site (`ReLateBound`), and occurrences of
355 /// regions (aka "lifetimes") that are bound within a type are not
356 /// visited by this folder; only regions that occur free will be
357 /// visited by `fld_r`.
358
359 pub struct RegionFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
360     tcx: TyCtxt<'a, 'gcx, 'tcx>,
361     skipped_regions: &'a mut bool,
362
363     /// Stores the index of a binder *just outside* the stuff we have
364     /// visited.  So this begins as INNERMOST; when we pass through a
365     /// binder, it is incremented (via `shift_in`).
366     current_index: ty::DebruijnIndex,
367
368     /// Callback invokes for each free region. The `DebruijnIndex`
369     /// points to the binder *just outside* the ones we have passed
370     /// through.
371     fold_region_fn: &'a mut (dyn FnMut(
372         ty::Region<'tcx>,
373         ty::DebruijnIndex,
374     ) -> ty::Region<'tcx> + 'a),
375 }
376
377 impl<'a, 'gcx, 'tcx> RegionFolder<'a, 'gcx, 'tcx> {
378     #[inline]
379     pub fn new(
380         tcx: TyCtxt<'a, 'gcx, 'tcx>,
381         skipped_regions: &'a mut bool,
382         fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
383     ) -> RegionFolder<'a, 'gcx, 'tcx> {
384         RegionFolder {
385             tcx,
386             skipped_regions,
387             current_index: ty::INNERMOST,
388             fold_region_fn,
389         }
390     }
391 }
392
393 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for RegionFolder<'a, 'gcx, 'tcx> {
394     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
395
396     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
397         self.current_index.shift_in(1);
398         let t = t.super_fold_with(self);
399         self.current_index.shift_out(1);
400         t
401     }
402
403     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
404         match *r {
405             ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
406                 debug!("RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
407                        r, self.current_index);
408                 *self.skipped_regions = true;
409                 r
410             }
411             _ => {
412                 debug!("RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
413                        r, self.current_index);
414                 (self.fold_region_fn)(r, self.current_index)
415             }
416         }
417     }
418 }
419
420 ///////////////////////////////////////////////////////////////////////////
421 // Bound vars replacer
422
423 /// Replaces the escaping bound vars (late bound regions or bound types) in a type.
424 struct BoundVarReplacer<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
425     tcx: TyCtxt<'a, 'gcx, 'tcx>,
426
427     /// As with `RegionFolder`, represents the index of a binder *just outside*
428     /// the ones we have visited.
429     current_index: ty::DebruijnIndex,
430
431     fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
432     fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
433 }
434
435 impl<'a, 'gcx, 'tcx> BoundVarReplacer<'a, 'gcx, 'tcx> {
436     fn new<F, G>(
437         tcx: TyCtxt<'a, 'gcx, 'tcx>,
438         fld_r: &'a mut F,
439         fld_t: &'a mut G
440     ) -> Self
441         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
442               G: FnMut(ty::BoundTy) -> Ty<'tcx>
443     {
444         BoundVarReplacer {
445             tcx,
446             current_index: ty::INNERMOST,
447             fld_r,
448             fld_t,
449         }
450     }
451 }
452
453 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for BoundVarReplacer<'a, 'gcx, 'tcx> {
454     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
455
456     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
457         self.current_index.shift_in(1);
458         let t = t.super_fold_with(self);
459         self.current_index.shift_out(1);
460         t
461     }
462
463     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
464         match t.sty {
465             ty::Bound(debruijn, bound_ty) => {
466                 if debruijn == self.current_index {
467                     let fld_t = &mut self.fld_t;
468                     let ty = fld_t(bound_ty);
469                     ty::fold::shift_vars(
470                         self.tcx,
471                         &ty,
472                         self.current_index.as_u32()
473                     )
474                 } else {
475                     t
476                 }
477             }
478             _ => {
479                 if !t.has_vars_bound_at_or_above(self.current_index) {
480                     // Nothing more to substitute.
481                     t
482                 } else {
483                     t.super_fold_with(self)
484                 }
485             }
486         }
487     }
488
489     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
490         match *r {
491             ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
492                 let fld_r = &mut self.fld_r;
493                 let region = fld_r(br);
494                 if let ty::ReLateBound(debruijn1, br) = *region {
495                     // If the callback returns a late-bound region,
496                     // that region should always use the INNERMOST
497                     // debruijn index. Then we adjust it to the
498                     // correct depth.
499                     assert_eq!(debruijn1, ty::INNERMOST);
500                     self.tcx.mk_region(ty::ReLateBound(debruijn, br))
501                 } else {
502                     region
503                 }
504             }
505             _ => r
506         }
507     }
508
509     fn fold_const(&mut self, ct: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx> {
510         ct // FIXME(const_generics)
511     }
512 }
513
514 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
515     /// Replaces all regions bound by the given `Binder` with the
516     /// results returned by the closure; the closure is expected to
517     /// return a free region (relative to this binder), and hence the
518     /// binder is removed in the return type. The closure is invoked
519     /// once for each unique `BoundRegion`; multiple references to the
520     /// same `BoundRegion` will reuse the previous result. A map is
521     /// returned at the end with each bound region and the free region
522     /// that replaced it.
523     ///
524     /// This method only replaces late bound regions and the result may still
525     /// contain escaping bound types.
526     pub fn replace_late_bound_regions<T, F>(
527         self,
528         value: &Binder<T>,
529         fld_r: F
530     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
531         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
532               T: TypeFoldable<'tcx>
533     {
534         // identity for bound types
535         let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
536         self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t)
537     }
538
539     /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
540     /// bound regions while the `fld_t` closure replaces escaping bound types.
541     pub fn replace_escaping_bound_vars<T, F, G>(
542         self,
543         value: &T,
544         mut fld_r: F,
545         mut fld_t: G
546     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
547         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
548               G: FnMut(ty::BoundTy) -> Ty<'tcx>,
549               T: TypeFoldable<'tcx>
550     {
551         use rustc_data_structures::fx::FxHashMap;
552
553         let mut region_map = BTreeMap::new();
554         let mut type_map = FxHashMap::default();
555
556         if !value.has_escaping_bound_vars() {
557             (value.clone(), region_map)
558         } else {
559             let mut real_fld_r = |br| {
560                 *region_map.entry(br).or_insert_with(|| fld_r(br))
561             };
562
563             let mut real_fld_t = |bound_ty| {
564                 *type_map.entry(bound_ty).or_insert_with(|| fld_t(bound_ty))
565             };
566
567             let mut replacer = BoundVarReplacer::new(self, &mut real_fld_r, &mut real_fld_t);
568             let result = value.fold_with(&mut replacer);
569             (result, region_map)
570         }
571     }
572
573     /// Replaces all types or regions bound by the given `Binder`. The `fld_r`
574     /// closure replaces bound regions while the `fld_t` closure replaces bound
575     /// types.
576     pub fn replace_bound_vars<T, F, G>(
577         self,
578         value: &Binder<T>,
579         fld_r: F,
580         fld_t: G
581     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
582         where F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
583               G: FnMut(ty::BoundTy) -> Ty<'tcx>,
584               T: TypeFoldable<'tcx>
585     {
586         self.replace_escaping_bound_vars(value.skip_binder(), fld_r, fld_t)
587     }
588
589     /// Replaces any late-bound regions bound in `value` with
590     /// free variants attached to `all_outlive_scope`.
591     pub fn liberate_late_bound_regions<T>(
592         &self,
593         all_outlive_scope: DefId,
594         value: &ty::Binder<T>
595     ) -> T
596     where T: TypeFoldable<'tcx> {
597         self.replace_late_bound_regions(value, |br| {
598             self.mk_region(ty::ReFree(ty::FreeRegion {
599                 scope: all_outlive_scope,
600                 bound_region: br
601             }))
602         }).0
603     }
604
605     /// Returns a set of all late-bound regions that are constrained
606     /// by `value`, meaning that if we instantiate those LBR with
607     /// variables and equate `value` with something else, those
608     /// variables will also be equated.
609     pub fn collect_constrained_late_bound_regions<T>(&self, value: &Binder<T>)
610                                                      -> FxHashSet<ty::BoundRegion>
611         where T : TypeFoldable<'tcx>
612     {
613         self.collect_late_bound_regions(value, true)
614     }
615
616     /// Returns a set of all late-bound regions that appear in `value` anywhere.
617     pub fn collect_referenced_late_bound_regions<T>(&self, value: &Binder<T>)
618                                                     -> FxHashSet<ty::BoundRegion>
619         where T : TypeFoldable<'tcx>
620     {
621         self.collect_late_bound_regions(value, false)
622     }
623
624     fn collect_late_bound_regions<T>(&self, value: &Binder<T>, just_constraint: bool)
625                                      -> FxHashSet<ty::BoundRegion>
626         where T : TypeFoldable<'tcx>
627     {
628         let mut collector = LateBoundRegionsCollector::new(just_constraint);
629         let result = value.skip_binder().visit_with(&mut collector);
630         assert!(!result); // should never have stopped early
631         collector.regions
632     }
633
634     /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
635     /// method lookup and a few other places where precise region relationships are not required.
636     pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
637         where T : TypeFoldable<'tcx>
638     {
639         self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
640     }
641
642     /// Rewrite any late-bound regions so that they are anonymous. Region numbers are
643     /// assigned starting at 1 and increasing monotonically in the order traversed
644     /// by the fold operation.
645     ///
646     /// The chief purpose of this function is to canonicalize regions so that two
647     /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
648     /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
649     /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
650     pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
651         where T : TypeFoldable<'tcx>,
652     {
653         let mut counter = 0;
654         Binder::bind(self.replace_late_bound_regions(sig, |_| {
655             counter += 1;
656             self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)))
657         }).0)
658     }
659 }
660
661 ///////////////////////////////////////////////////////////////////////////
662 // Shifter
663 //
664 // Shifts the De Bruijn indices on all escaping bound vars by a
665 // fixed amount. Useful in substitution or when otherwise introducing
666 // a binding level that is not intended to capture the existing bound
667 // vars. See comment on `shift_vars_through_binders` method in
668 // `subst.rs` for more details.
669
670 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
671 enum Direction {
672     In,
673     Out,
674 }
675
676 struct Shifter<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
677     tcx: TyCtxt<'a, 'gcx, 'tcx>,
678     current_index: ty::DebruijnIndex,
679     amount: u32,
680     direction: Direction,
681 }
682
683 impl Shifter<'a, 'gcx, 'tcx> {
684     pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, amount: u32, direction: Direction) -> Self {
685         Shifter {
686             tcx,
687             current_index: ty::INNERMOST,
688             amount,
689             direction,
690         }
691     }
692 }
693
694 impl TypeFolder<'gcx, 'tcx> for Shifter<'a, 'gcx, 'tcx> {
695     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
696
697     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
698         self.current_index.shift_in(1);
699         let t = t.super_fold_with(self);
700         self.current_index.shift_out(1);
701         t
702     }
703
704     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
705         match *r {
706             ty::ReLateBound(debruijn, br) => {
707                 if self.amount == 0 || debruijn < self.current_index {
708                     r
709                 } else {
710                     let debruijn = match self.direction {
711                         Direction::In => debruijn.shifted_in(self.amount),
712                         Direction::Out => {
713                             assert!(debruijn.as_u32() >= self.amount);
714                             debruijn.shifted_out(self.amount)
715                         }
716                     };
717                     let shifted = ty::ReLateBound(debruijn, br);
718                     self.tcx.mk_region(shifted)
719                 }
720             }
721             _ => r
722         }
723     }
724
725     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
726         match ty.sty {
727             ty::Bound(debruijn, bound_ty) => {
728                 if self.amount == 0 || debruijn < self.current_index {
729                     ty
730                 } else {
731                     let debruijn = match self.direction {
732                         Direction::In => debruijn.shifted_in(self.amount),
733                         Direction::Out => {
734                             assert!(debruijn.as_u32() >= self.amount);
735                             debruijn.shifted_out(self.amount)
736                         }
737                     };
738                     self.tcx.mk_ty(
739                         ty::Bound(debruijn, bound_ty)
740                     )
741                 }
742             }
743
744             _ => ty.super_fold_with(self),
745         }
746     }
747
748     fn fold_const(&mut self, ct: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx> {
749         ct // FIXME(const_generics)
750     }
751 }
752
753 pub fn shift_region<'a, 'gcx, 'tcx>(
754     tcx: TyCtxt<'a, 'gcx, 'tcx>,
755     region: ty::Region<'tcx>,
756     amount: u32
757 ) -> ty::Region<'tcx> {
758     match region {
759         ty::ReLateBound(debruijn, br) if amount > 0 => {
760             tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
761         }
762         _ => {
763             region
764         }
765     }
766 }
767
768 pub fn shift_vars<'a, 'gcx, 'tcx, T>(
769     tcx: TyCtxt<'a, 'gcx, 'tcx>,
770     value: &T,
771     amount: u32
772 ) -> T where T: TypeFoldable<'tcx> {
773     debug!("shift_vars(value={:?}, amount={})",
774            value, amount);
775
776     value.fold_with(&mut Shifter::new(tcx, amount, Direction::In))
777 }
778
779 pub fn shift_out_vars<'a, 'gcx, 'tcx, T>(
780     tcx: TyCtxt<'a, 'gcx, 'tcx>,
781     value: &T,
782     amount: u32
783 ) -> T where T: TypeFoldable<'tcx> {
784     debug!("shift_out_vars(value={:?}, amount={})",
785            value, amount);
786
787     value.fold_with(&mut Shifter::new(tcx, amount, Direction::Out))
788 }
789
790 /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
791 /// bound region or a bound type.
792 ///
793 /// So, for example, consider a type like the following, which has two binders:
794 ///
795 ///    for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
796 ///    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
797 ///                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~  inner scope
798 ///
799 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
800 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
801 /// fn type*, that type has an escaping region: `'a`.
802 ///
803 /// Note that what I'm calling an "escaping var" is often just called a "free var". However,
804 /// we already use the term "free var". It refers to the regions or types that we use to represent
805 /// bound regions or type params on a fn definition while we are type checking its body.
806 ///
807 /// To clarify, conceptually there is no particular difference between
808 /// an "escaping" var and a "free" var. However, there is a big
809 /// difference in practice. Basically, when "entering" a binding
810 /// level, one is generally required to do some sort of processing to
811 /// a bound var, such as replacing it with a fresh/placeholder
812 /// var, or making an entry in the environment to represent the
813 /// scope to which it is attached, etc. An escaping var represents
814 /// a bound var for which this processing has not yet been done.
815 struct HasEscapingVarsVisitor {
816     /// Anything bound by `outer_index` or "above" is escaping.
817     outer_index: ty::DebruijnIndex,
818 }
819
820 impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
821     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
822         self.outer_index.shift_in(1);
823         let result = t.super_visit_with(self);
824         self.outer_index.shift_out(1);
825         result
826     }
827
828     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
829         // If the outer-exclusive-binder is *strictly greater* than
830         // `outer_index`, that means that `t` contains some content
831         // bound at `outer_index` or above (because
832         // `outer_exclusive_binder` is always 1 higher than the
833         // content in `t`). Therefore, `t` has some escaping vars.
834         t.outer_exclusive_binder > self.outer_index
835     }
836
837     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
838         // If the region is bound by `outer_index` or anything outside
839         // of outer index, then it escapes the binders we have
840         // visited.
841         r.bound_at_or_above_binder(self.outer_index)
842     }
843 }
844
845 struct HasTypeFlagsVisitor {
846     flags: ty::TypeFlags,
847 }
848
849 impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
850     fn visit_ty(&mut self, t: Ty<'_>) -> bool {
851         debug!("HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}", t, t.flags, self.flags);
852         t.flags.intersects(self.flags)
853     }
854
855     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
856         let flags = r.type_flags();
857         debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
858         flags.intersects(self.flags)
859     }
860
861     fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
862         let flags = FlagComputation::for_const(c);
863         debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
864         flags.intersects(self.flags) || c.super_visit_with(self)
865     }
866 }
867
868 /// Collects all the late-bound regions at the innermost binding level
869 /// into a hash set.
870 struct LateBoundRegionsCollector {
871     current_index: ty::DebruijnIndex,
872     regions: FxHashSet<ty::BoundRegion>,
873
874     /// `true` if we only want regions that are known to be
875     /// "constrained" when you equate this type with another type. In
876     /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
877     /// them constraints `'a == 'b`. But if you have `<&'a u32 as
878     /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
879     /// types may mean that `'a` and `'b` don't appear in the results,
880     /// so they are not considered *constrained*.
881     just_constrained: bool,
882 }
883
884 impl LateBoundRegionsCollector {
885     fn new(just_constrained: bool) -> Self {
886         LateBoundRegionsCollector {
887             current_index: ty::INNERMOST,
888             regions: Default::default(),
889             just_constrained,
890         }
891     }
892 }
893
894 impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
895     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
896         self.current_index.shift_in(1);
897         let result = t.super_visit_with(self);
898         self.current_index.shift_out(1);
899         result
900     }
901
902     fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
903         // if we are only looking for "constrained" region, we have to
904         // ignore the inputs to a projection, as they may not appear
905         // in the normalized form
906         if self.just_constrained {
907             match t.sty {
908                 ty::Projection(..) | ty::Opaque(..) => { return false; }
909                 _ => { }
910             }
911         }
912
913         t.super_visit_with(self)
914     }
915
916     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
917         if let ty::ReLateBound(debruijn, br) = *r {
918              if debruijn == self.current_index {
919                 self.regions.insert(br);
920             }
921         }
922         false
923     }
924 }