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