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