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