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