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