]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/erase_regions.rs
Unify Opaque/Projection handling in region outlives code
[rust.git] / compiler / rustc_middle / src / ty / erase_regions.rs
1 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
2 use crate::ty::visit::TypeVisitable;
3 use crate::ty::{self, Ty, TyCtxt, TypeFlags};
4
5 pub(super) fn provide(providers: &mut ty::query::Providers) {
6     *providers = ty::query::Providers { erase_regions_ty, ..*providers };
7 }
8
9 fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
10     // N.B., use `super_fold_with` here. If we used `fold_with`, it
11     // could invoke the `erase_regions_ty` query recursively.
12     ty.super_fold_with(&mut RegionEraserVisitor { tcx })
13 }
14
15 impl<'tcx> TyCtxt<'tcx> {
16     /// Returns an equivalent value with all free regions removed (note
17     /// that late-bound regions remain, because they are important for
18     /// subtyping, but they are anonymized and normalized as well)..
19     pub fn erase_regions<T>(self, value: T) -> T
20     where
21         T: TypeFoldable<'tcx>,
22     {
23         // If there's nothing to erase avoid performing the query at all
24         if !value.has_type_flags(TypeFlags::HAS_LATE_BOUND | TypeFlags::HAS_FREE_REGIONS) {
25             return value;
26         }
27         debug!("erase_regions({:?})", value);
28         let value1 = value.fold_with(&mut RegionEraserVisitor { tcx: self });
29         debug!("erase_regions = {:?}", value1);
30         value1
31     }
32 }
33
34 struct RegionEraserVisitor<'tcx> {
35     tcx: TyCtxt<'tcx>,
36 }
37
38 impl<'tcx> TypeFolder<'tcx> for RegionEraserVisitor<'tcx> {
39     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
40         self.tcx
41     }
42
43     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
44         if ty.needs_infer() { ty.super_fold_with(self) } else { self.tcx.erase_regions_ty(ty) }
45     }
46
47     fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
48     where
49         T: TypeFoldable<'tcx>,
50     {
51         let u = self.tcx.anonymize_bound_vars(t);
52         u.super_fold_with(self)
53     }
54
55     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
56         // because late-bound regions affect subtyping, we can't
57         // erase the bound/free distinction, but we can replace
58         // all free regions with 'erased.
59         //
60         // Note that we *CAN* replace early-bound regions -- the
61         // type system never "sees" those, they get substituted
62         // away. In codegen, they will always be erased to 'erased
63         // whenever a substitution occurs.
64         match *r {
65             ty::ReLateBound(..) => r,
66             _ => self.tcx.lifetimes.re_erased,
67         }
68     }
69 }