]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/infer/canonical.rs
Rollup merge of #103929 - BlackHoleFox:apple-targets-cleanup, r=petrochenkov
[rust.git] / compiler / rustc_middle / src / infer / canonical.rs
1 //! **Canonicalization** is the key to constructing a query in the
2 //! middle of type inference. Ordinarily, it is not possible to store
3 //! types from type inference in query keys, because they contain
4 //! references to inference variables whose lifetimes are too short
5 //! and so forth. Canonicalizing a value T1 using `canonicalize_query`
6 //! produces two things:
7 //!
8 //! - a value T2 where each unbound inference variable has been
9 //!   replaced with a **canonical variable**;
10 //! - a map M (of type `CanonicalVarValues`) from those canonical
11 //!   variables back to the original.
12 //!
13 //! We can then do queries using T2. These will give back constraints
14 //! on the canonical variables which can be translated, using the map
15 //! M, into constraints in our source context. This process of
16 //! translating the results back is done by the
17 //! `instantiate_query_result` method.
18 //!
19 //! For a more detailed look at what is happening here, check
20 //! out the [chapter in the rustc dev guide][c].
21 //!
22 //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html
23
24 use crate::infer::MemberConstraint;
25 use crate::mir::ConstraintCategory;
26 use crate::ty::subst::GenericArg;
27 use crate::ty::{self, BoundVar, List, Region, Ty, TyCtxt};
28 use rustc_index::vec::IndexVec;
29 use rustc_macros::HashStable;
30 use smallvec::SmallVec;
31 use std::iter;
32 use std::ops::Index;
33
34 /// A "canonicalized" type `V` is one where all free inference
35 /// variables have been rewritten to "canonical vars". These are
36 /// numbered starting from 0 in order of first appearance.
37 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable)]
38 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
39 pub struct Canonical<'tcx, V> {
40     pub max_universe: ty::UniverseIndex,
41     pub variables: CanonicalVarInfos<'tcx>,
42     pub value: V,
43 }
44
45 pub type CanonicalVarInfos<'tcx> = &'tcx List<CanonicalVarInfo<'tcx>>;
46
47 impl<'tcx> ty::TypeFoldable<'tcx> for CanonicalVarInfos<'tcx> {
48     fn try_fold_with<F: ty::FallibleTypeFolder<'tcx>>(
49         self,
50         folder: &mut F,
51     ) -> Result<Self, F::Error> {
52         ty::util::fold_list(self, folder, |tcx, v| tcx.intern_canonical_var_infos(v))
53     }
54 }
55
56 /// A set of values corresponding to the canonical variables from some
57 /// `Canonical`. You can give these values to
58 /// `canonical_value.substitute` to substitute them into the canonical
59 /// value at the right places.
60 ///
61 /// When you canonicalize a value `V`, you get back one of these
62 /// vectors with the original values that were replaced by canonical
63 /// variables. You will need to supply it later to instantiate the
64 /// canonicalized query response.
65 #[derive(Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable)]
66 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
67 pub struct CanonicalVarValues<'tcx> {
68     pub var_values: IndexVec<BoundVar, GenericArg<'tcx>>,
69 }
70
71 /// When we canonicalize a value to form a query, we wind up replacing
72 /// various parts of it with canonical variables. This struct stores
73 /// those replaced bits to remember for when we process the query
74 /// result.
75 #[derive(Clone, Debug)]
76 pub struct OriginalQueryValues<'tcx> {
77     /// Map from the universes that appear in the query to the universes in the
78     /// caller context. For all queries except `evaluate_goal` (used by Chalk),
79     /// we only ever put ROOT values into the query, so this map is very
80     /// simple.
81     pub universe_map: SmallVec<[ty::UniverseIndex; 4]>,
82
83     /// This is equivalent to `CanonicalVarValues`, but using a
84     /// `SmallVec` yields a significant performance win.
85     pub var_values: SmallVec<[GenericArg<'tcx>; 8]>,
86 }
87
88 impl<'tcx> Default for OriginalQueryValues<'tcx> {
89     fn default() -> Self {
90         let mut universe_map = SmallVec::default();
91         universe_map.push(ty::UniverseIndex::ROOT);
92
93         Self { universe_map, var_values: SmallVec::default() }
94     }
95 }
96
97 /// Information about a canonical variable that is included with the
98 /// canonical value. This is sufficient information for code to create
99 /// a copy of the canonical value in some other inference context,
100 /// with fresh inference variables replacing the canonical values.
101 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable, HashStable)]
102 #[derive(TypeFoldable, TypeVisitable)]
103 pub struct CanonicalVarInfo<'tcx> {
104     pub kind: CanonicalVarKind<'tcx>,
105 }
106
107 impl<'tcx> CanonicalVarInfo<'tcx> {
108     pub fn universe(&self) -> ty::UniverseIndex {
109         self.kind.universe()
110     }
111
112     pub fn is_existential(&self) -> bool {
113         match self.kind {
114             CanonicalVarKind::Ty(_) => true,
115             CanonicalVarKind::PlaceholderTy(_) => false,
116             CanonicalVarKind::Region(_) => true,
117             CanonicalVarKind::PlaceholderRegion(..) => false,
118             CanonicalVarKind::Const(..) => true,
119             CanonicalVarKind::PlaceholderConst(_, _) => false,
120         }
121     }
122 }
123
124 /// Describes the "kind" of the canonical variable. This is a "kind"
125 /// in the type-theory sense of the term -- i.e., a "meta" type system
126 /// that analyzes type-like values.
127 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable, HashStable)]
128 #[derive(TypeFoldable, TypeVisitable)]
129 pub enum CanonicalVarKind<'tcx> {
130     /// Some kind of type inference variable.
131     Ty(CanonicalTyVarKind),
132
133     /// A "placeholder" that represents "any type".
134     PlaceholderTy(ty::PlaceholderType),
135
136     /// Region variable `'?R`.
137     Region(ty::UniverseIndex),
138
139     /// A "placeholder" that represents "any region". Created when you
140     /// are solving a goal like `for<'a> T: Foo<'a>` to represent the
141     /// bound region `'a`.
142     PlaceholderRegion(ty::PlaceholderRegion),
143
144     /// Some kind of const inference variable.
145     Const(ty::UniverseIndex, Ty<'tcx>),
146
147     /// A "placeholder" that represents "any const".
148     PlaceholderConst(ty::PlaceholderConst<'tcx>, Ty<'tcx>),
149 }
150
151 impl<'tcx> CanonicalVarKind<'tcx> {
152     pub fn universe(self) -> ty::UniverseIndex {
153         match self {
154             CanonicalVarKind::Ty(kind) => match kind {
155                 CanonicalTyVarKind::General(ui) => ui,
156                 CanonicalTyVarKind::Float | CanonicalTyVarKind::Int => ty::UniverseIndex::ROOT,
157             },
158
159             CanonicalVarKind::PlaceholderTy(placeholder) => placeholder.universe,
160             CanonicalVarKind::Region(ui) => ui,
161             CanonicalVarKind::PlaceholderRegion(placeholder) => placeholder.universe,
162             CanonicalVarKind::Const(ui, _) => ui,
163             CanonicalVarKind::PlaceholderConst(placeholder, _) => placeholder.universe,
164         }
165     }
166 }
167
168 /// Rust actually has more than one category of type variables;
169 /// notably, the type variables we create for literals (e.g., 22 or
170 /// 22.) can only be instantiated with integral/float types (e.g.,
171 /// usize or f32). In order to faithfully reproduce a type, we need to
172 /// know what set of types a given type variable can be unified with.
173 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable, HashStable)]
174 pub enum CanonicalTyVarKind {
175     /// General type variable `?T` that can be unified with arbitrary types.
176     General(ty::UniverseIndex),
177
178     /// Integral type variable `?I` (that can only be unified with integral types).
179     Int,
180
181     /// Floating-point type variable `?F` (that can only be unified with float types).
182     Float,
183 }
184
185 /// After we execute a query with a canonicalized key, we get back a
186 /// `Canonical<QueryResponse<..>>`. You can use
187 /// `instantiate_query_result` to access the data in this result.
188 #[derive(Clone, Debug, HashStable, TypeFoldable, TypeVisitable, Lift)]
189 pub struct QueryResponse<'tcx, R> {
190     pub var_values: CanonicalVarValues<'tcx>,
191     pub region_constraints: QueryRegionConstraints<'tcx>,
192     pub certainty: Certainty,
193     /// List of opaque types which we tried to compare to another type.
194     /// Inside the query we don't know yet whether the opaque type actually
195     /// should get its hidden type inferred. So we bubble the opaque type
196     /// and the type it was compared against upwards and let the query caller
197     /// handle it.
198     pub opaque_types: Vec<(Ty<'tcx>, Ty<'tcx>)>,
199     pub value: R,
200 }
201
202 #[derive(Clone, Debug, Default, HashStable, TypeFoldable, TypeVisitable, Lift)]
203 pub struct QueryRegionConstraints<'tcx> {
204     pub outlives: Vec<QueryOutlivesConstraint<'tcx>>,
205     pub member_constraints: Vec<MemberConstraint<'tcx>>,
206 }
207
208 impl QueryRegionConstraints<'_> {
209     /// Represents an empty (trivially true) set of region
210     /// constraints.
211     pub fn is_empty(&self) -> bool {
212         self.outlives.is_empty() && self.member_constraints.is_empty()
213     }
214 }
215
216 pub type Canonicalized<'tcx, V> = Canonical<'tcx, V>;
217
218 pub type CanonicalizedQueryResponse<'tcx, T> = &'tcx Canonical<'tcx, QueryResponse<'tcx, T>>;
219
220 /// Indicates whether or not we were able to prove the query to be
221 /// true.
222 #[derive(Copy, Clone, Debug, HashStable)]
223 pub enum Certainty {
224     /// The query is known to be true, presuming that you apply the
225     /// given `var_values` and the region-constraints are satisfied.
226     Proven,
227
228     /// The query is not known to be true, but also not known to be
229     /// false. The `var_values` represent *either* values that must
230     /// hold in order for the query to be true, or helpful tips that
231     /// *might* make it true. Currently rustc's trait solver cannot
232     /// distinguish the two (e.g., due to our preference for where
233     /// clauses over impls).
234     ///
235     /// After some unification and things have been done, it makes
236     /// sense to try and prove again -- of course, at that point, the
237     /// canonical form will be different, making this a distinct
238     /// query.
239     Ambiguous,
240 }
241
242 impl Certainty {
243     pub fn is_proven(&self) -> bool {
244         match self {
245             Certainty::Proven => true,
246             Certainty::Ambiguous => false,
247         }
248     }
249 }
250
251 impl<'tcx, R> QueryResponse<'tcx, R> {
252     pub fn is_proven(&self) -> bool {
253         self.certainty.is_proven()
254     }
255 }
256
257 impl<'tcx, R> Canonical<'tcx, QueryResponse<'tcx, R>> {
258     pub fn is_proven(&self) -> bool {
259         self.value.is_proven()
260     }
261
262     pub fn is_ambiguous(&self) -> bool {
263         !self.is_proven()
264     }
265 }
266
267 impl<'tcx, R> Canonical<'tcx, ty::ParamEnvAnd<'tcx, R>> {
268     #[inline]
269     pub fn without_const(mut self) -> Self {
270         self.value = self.value.without_const();
271         self
272     }
273 }
274
275 impl<'tcx, V> Canonical<'tcx, V> {
276     /// Allows you to map the `value` of a canonical while keeping the
277     /// same set of bound variables.
278     ///
279     /// **WARNING:** This function is very easy to mis-use, hence the
280     /// name!  In particular, the new value `W` must use all **the
281     /// same type/region variables** in **precisely the same order**
282     /// as the original! (The ordering is defined by the
283     /// `TypeFoldable` implementation of the type in question.)
284     ///
285     /// An example of a **correct** use of this:
286     ///
287     /// ```rust,ignore (not real code)
288     /// let a: Canonical<'_, T> = ...;
289     /// let b: Canonical<'_, (T,)> = a.unchecked_map(|v| (v, ));
290     /// ```
291     ///
292     /// An example of an **incorrect** use of this:
293     ///
294     /// ```rust,ignore (not real code)
295     /// let a: Canonical<'tcx, T> = ...;
296     /// let ty: Ty<'tcx> = ...;
297     /// let b: Canonical<'tcx, (T, Ty<'tcx>)> = a.unchecked_map(|v| (v, ty));
298     /// ```
299     pub fn unchecked_map<W>(self, map_op: impl FnOnce(V) -> W) -> Canonical<'tcx, W> {
300         let Canonical { max_universe, variables, value } = self;
301         Canonical { max_universe, variables, value: map_op(value) }
302     }
303 }
304
305 pub type QueryOutlivesConstraint<'tcx> = (
306     ty::Binder<'tcx, ty::OutlivesPredicate<GenericArg<'tcx>, Region<'tcx>>>,
307     ConstraintCategory<'tcx>,
308 );
309
310 TrivialTypeTraversalAndLiftImpls! {
311     for <'tcx> {
312         crate::infer::canonical::Certainty,
313         crate::infer::canonical::CanonicalTyVarKind,
314     }
315 }
316
317 impl<'tcx> CanonicalVarValues<'tcx> {
318     #[inline]
319     pub fn len(&self) -> usize {
320         self.var_values.len()
321     }
322
323     /// Makes an identity substitution from this one: each bound var
324     /// is matched to the same bound var, preserving the original kinds.
325     /// For example, if we have:
326     /// `self.var_values == [Type(u32), Lifetime('a), Type(u64)]`
327     /// we'll return a substitution `subst` with:
328     /// `subst.var_values == [Type(^0), Lifetime(^1), Type(^2)]`.
329     pub fn make_identity(&self, tcx: TyCtxt<'tcx>) -> Self {
330         use crate::ty::subst::GenericArgKind;
331
332         CanonicalVarValues {
333             var_values: iter::zip(&self.var_values, 0..)
334                 .map(|(kind, i)| match kind.unpack() {
335                     GenericArgKind::Type(..) => {
336                         tcx.mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_u32(i).into())).into()
337                     }
338                     GenericArgKind::Lifetime(..) => {
339                         let br = ty::BoundRegion {
340                             var: ty::BoundVar::from_u32(i),
341                             kind: ty::BrAnon(i, None),
342                         };
343                         tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into()
344                     }
345                     GenericArgKind::Const(ct) => tcx
346                         .mk_const(
347                             ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_u32(i)),
348                             ct.ty(),
349                         )
350                         .into(),
351                 })
352                 .collect(),
353         }
354     }
355 }
356
357 impl<'a, 'tcx> IntoIterator for &'a CanonicalVarValues<'tcx> {
358     type Item = GenericArg<'tcx>;
359     type IntoIter = ::std::iter::Cloned<::std::slice::Iter<'a, GenericArg<'tcx>>>;
360
361     fn into_iter(self) -> Self::IntoIter {
362         self.var_values.iter().cloned()
363     }
364 }
365
366 impl<'tcx> Index<BoundVar> for CanonicalVarValues<'tcx> {
367     type Output = GenericArg<'tcx>;
368
369     fn index(&self, value: BoundVar) -> &GenericArg<'tcx> {
370         &self.var_values[value]
371     }
372 }