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