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