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