]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/normalize_erasing_regions.rs
Rollup merge of #107519 - joboet:raw_os_error_ty, r=Amanieu
[rust.git] / compiler / rustc_middle / src / ty / normalize_erasing_regions.rs
1 //! Methods for normalizing when you don't care about regions (and
2 //! aren't doing type inference). If either of those things don't
3 //! apply to you, use `infcx.normalize(...)`.
4 //!
5 //! The methods in this file use a `TypeFolder` to recursively process
6 //! contents, invoking the underlying
7 //! `normalize_generic_arg_after_erasing_regions` query for each type
8 //! or constant found within. (This underlying query is what is cached.)
9
10 use crate::mir;
11 use crate::traits::query::NoSolution;
12 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder};
13 use crate::ty::{self, EarlyBinder, SubstsRef, Ty, TyCtxt};
14
15 #[derive(Debug, Copy, Clone, HashStable, TyEncodable, TyDecodable)]
16 pub enum NormalizationError<'tcx> {
17     Type(Ty<'tcx>),
18     Const(ty::Const<'tcx>),
19     ConstantKind(mir::ConstantKind<'tcx>),
20 }
21
22 impl<'tcx> NormalizationError<'tcx> {
23     pub fn get_type_for_failure(&self) -> String {
24         match self {
25             NormalizationError::Type(t) => format!("{}", t),
26             NormalizationError::Const(c) => format!("{}", c),
27             NormalizationError::ConstantKind(ck) => format!("{}", ck),
28         }
29     }
30 }
31
32 impl<'tcx> TyCtxt<'tcx> {
33     /// Erase the regions in `value` and then fully normalize all the
34     /// types found within. The result will also have regions erased.
35     ///
36     /// This should only be used outside of type inference. For example,
37     /// it assumes that normalization will succeed.
38     #[tracing::instrument(level = "debug", skip(self, param_env))]
39     pub fn normalize_erasing_regions<T>(self, param_env: ty::ParamEnv<'tcx>, value: T) -> T
40     where
41         T: TypeFoldable<'tcx>,
42     {
43         debug!(
44             "normalize_erasing_regions::<{}>(value={:?}, param_env={:?})",
45             std::any::type_name::<T>(),
46             value,
47             param_env,
48         );
49
50         // Erase first before we do the real query -- this keeps the
51         // cache from being too polluted.
52         let value = self.erase_regions(value);
53         debug!(?value);
54
55         if !value.has_projections() {
56             value
57         } else {
58             value.fold_with(&mut NormalizeAfterErasingRegionsFolder { tcx: self, param_env })
59         }
60     }
61
62     /// Tries to erase the regions in `value` and then fully normalize all the
63     /// types found within. The result will also have regions erased.
64     ///
65     /// Contrary to `normalize_erasing_regions` this function does not assume that normalization
66     /// succeeds.
67     pub fn try_normalize_erasing_regions<T>(
68         self,
69         param_env: ty::ParamEnv<'tcx>,
70         value: T,
71     ) -> Result<T, NormalizationError<'tcx>>
72     where
73         T: TypeFoldable<'tcx>,
74     {
75         debug!(
76             "try_normalize_erasing_regions::<{}>(value={:?}, param_env={:?})",
77             std::any::type_name::<T>(),
78             value,
79             param_env,
80         );
81
82         // Erase first before we do the real query -- this keeps the
83         // cache from being too polluted.
84         let value = self.erase_regions(value);
85         debug!(?value);
86
87         if !value.has_projections() {
88             Ok(value)
89         } else {
90             let mut folder = TryNormalizeAfterErasingRegionsFolder::new(self, param_env);
91             value.try_fold_with(&mut folder)
92         }
93     }
94
95     /// If you have a `Binder<'tcx, T>`, you can do this to strip out the
96     /// late-bound regions and then normalize the result, yielding up
97     /// a `T` (with regions erased). This is appropriate when the
98     /// binder is being instantiated at the call site.
99     ///
100     /// N.B., currently, higher-ranked type bounds inhibit
101     /// normalization. Therefore, each time we erase them in
102     /// codegen, we need to normalize the contents.
103     #[tracing::instrument(level = "debug", skip(self, param_env))]
104     pub fn normalize_erasing_late_bound_regions<T>(
105         self,
106         param_env: ty::ParamEnv<'tcx>,
107         value: ty::Binder<'tcx, T>,
108     ) -> T
109     where
110         T: TypeFoldable<'tcx>,
111     {
112         let value = self.erase_late_bound_regions(value);
113         self.normalize_erasing_regions(param_env, value)
114     }
115
116     /// If you have a `Binder<'tcx, T>`, you can do this to strip out the
117     /// late-bound regions and then normalize the result, yielding up
118     /// a `T` (with regions erased). This is appropriate when the
119     /// binder is being instantiated at the call site.
120     ///
121     /// N.B., currently, higher-ranked type bounds inhibit
122     /// normalization. Therefore, each time we erase them in
123     /// codegen, we need to normalize the contents.
124     pub fn try_normalize_erasing_late_bound_regions<T>(
125         self,
126         param_env: ty::ParamEnv<'tcx>,
127         value: ty::Binder<'tcx, T>,
128     ) -> Result<T, NormalizationError<'tcx>>
129     where
130         T: TypeFoldable<'tcx>,
131     {
132         let value = self.erase_late_bound_regions(value);
133         self.try_normalize_erasing_regions(param_env, value)
134     }
135
136     /// Monomorphizes a type from the AST by first applying the
137     /// in-scope substitutions and then normalizing any associated
138     /// types.
139     /// Panics if normalization fails. In case normalization might fail
140     /// use `try_subst_and_normalize_erasing_regions` instead.
141     pub fn subst_and_normalize_erasing_regions<T>(
142         self,
143         param_substs: SubstsRef<'tcx>,
144         param_env: ty::ParamEnv<'tcx>,
145         value: T,
146     ) -> T
147     where
148         T: TypeFoldable<'tcx>,
149     {
150         debug!(
151             "subst_and_normalize_erasing_regions(\
152              param_substs={:?}, \
153              value={:?}, \
154              param_env={:?})",
155             param_substs, value, param_env,
156         );
157         let substituted = EarlyBinder(value).subst(self, param_substs);
158         self.normalize_erasing_regions(param_env, substituted)
159     }
160
161     /// Monomorphizes a type from the AST by first applying the
162     /// in-scope substitutions and then trying to normalize any associated
163     /// types. Contrary to `subst_and_normalize_erasing_regions` this does
164     /// not assume that normalization succeeds.
165     pub fn try_subst_and_normalize_erasing_regions<T>(
166         self,
167         param_substs: SubstsRef<'tcx>,
168         param_env: ty::ParamEnv<'tcx>,
169         value: T,
170     ) -> Result<T, NormalizationError<'tcx>>
171     where
172         T: TypeFoldable<'tcx>,
173     {
174         debug!(
175             "subst_and_normalize_erasing_regions(\
176              param_substs={:?}, \
177              value={:?}, \
178              param_env={:?})",
179             param_substs, value, param_env,
180         );
181         let substituted = EarlyBinder(value).subst(self, param_substs);
182         self.try_normalize_erasing_regions(param_env, substituted)
183     }
184 }
185
186 struct NormalizeAfterErasingRegionsFolder<'tcx> {
187     tcx: TyCtxt<'tcx>,
188     param_env: ty::ParamEnv<'tcx>,
189 }
190
191 impl<'tcx> NormalizeAfterErasingRegionsFolder<'tcx> {
192     fn normalize_generic_arg_after_erasing_regions(
193         &self,
194         arg: ty::GenericArg<'tcx>,
195     ) -> ty::GenericArg<'tcx> {
196         let arg = self.param_env.and(arg);
197
198         self.tcx.try_normalize_generic_arg_after_erasing_regions(arg).unwrap_or_else(|_| bug!(
199                 "Failed to normalize {:?}, maybe try to call `try_normalize_erasing_regions` instead",
200                 arg.value
201             ))
202     }
203 }
204
205 impl<'tcx> TypeFolder<'tcx> for NormalizeAfterErasingRegionsFolder<'tcx> {
206     fn tcx(&self) -> TyCtxt<'tcx> {
207         self.tcx
208     }
209
210     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
211         self.normalize_generic_arg_after_erasing_regions(ty.into()).expect_ty()
212     }
213
214     fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
215         self.normalize_generic_arg_after_erasing_regions(c.into()).expect_const()
216     }
217 }
218
219 struct TryNormalizeAfterErasingRegionsFolder<'tcx> {
220     tcx: TyCtxt<'tcx>,
221     param_env: ty::ParamEnv<'tcx>,
222 }
223
224 impl<'tcx> TryNormalizeAfterErasingRegionsFolder<'tcx> {
225     fn new(tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
226         TryNormalizeAfterErasingRegionsFolder { tcx, param_env }
227     }
228
229     #[instrument(skip(self), level = "debug")]
230     fn try_normalize_generic_arg_after_erasing_regions(
231         &self,
232         arg: ty::GenericArg<'tcx>,
233     ) -> Result<ty::GenericArg<'tcx>, NoSolution> {
234         let arg = self.param_env.and(arg);
235         debug!(?arg);
236
237         self.tcx.try_normalize_generic_arg_after_erasing_regions(arg)
238     }
239 }
240
241 impl<'tcx> FallibleTypeFolder<'tcx> for TryNormalizeAfterErasingRegionsFolder<'tcx> {
242     type Error = NormalizationError<'tcx>;
243
244     fn tcx(&self) -> TyCtxt<'tcx> {
245         self.tcx
246     }
247
248     fn try_fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
249         match self.try_normalize_generic_arg_after_erasing_regions(ty.into()) {
250             Ok(t) => Ok(t.expect_ty()),
251             Err(_) => Err(NormalizationError::Type(ty)),
252         }
253     }
254
255     fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
256         match self.try_normalize_generic_arg_after_erasing_regions(c.into()) {
257             Ok(t) => Ok(t.expect_const()),
258             Err(_) => Err(NormalizationError::Const(c)),
259         }
260     }
261 }