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:
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.
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.
19 //! For a more detailed look at what is happening here, check
20 //! out the [chapter in the rustc dev guide][c].
22 //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html
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;
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>,
45 pub type CanonicalVarInfos<'tcx> = &'tcx List<CanonicalVarInfo<'tcx>>;
47 impl<'tcx> ty::TypeFoldable<'tcx> for CanonicalVarInfos<'tcx> {
48 fn try_fold_with<F: ty::FallibleTypeFolder<'tcx>>(
51 ) -> Result<Self, F::Error> {
52 ty::util::fold_list(self, folder, |tcx, v| tcx.intern_canonical_var_infos(v))
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.
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>>,
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
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
81 pub universe_map: SmallVec<[ty::UniverseIndex; 4]>,
83 /// This is equivalent to `CanonicalVarValues`, but using a
84 /// `SmallVec` yields a significant performance win.
85 pub var_values: SmallVec<[GenericArg<'tcx>; 8]>,
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);
93 Self { universe_map, var_values: SmallVec::default() }
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>,
107 impl<'tcx> CanonicalVarInfo<'tcx> {
108 pub fn universe(&self) -> ty::UniverseIndex {
112 pub fn is_existential(&self) -> bool {
114 CanonicalVarKind::Ty(_) => true,
115 CanonicalVarKind::PlaceholderTy(_) => false,
116 CanonicalVarKind::Region(_) => true,
117 CanonicalVarKind::PlaceholderRegion(..) => false,
118 CanonicalVarKind::Const(..) => true,
119 CanonicalVarKind::PlaceholderConst(_, _) => false,
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),
133 /// A "placeholder" that represents "any type".
134 PlaceholderTy(ty::PlaceholderType),
136 /// Region variable `'?R`.
137 Region(ty::UniverseIndex),
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),
144 /// Some kind of const inference variable.
145 Const(ty::UniverseIndex, Ty<'tcx>),
147 /// A "placeholder" that represents "any const".
148 PlaceholderConst(ty::PlaceholderConst<'tcx>, Ty<'tcx>),
151 impl<'tcx> CanonicalVarKind<'tcx> {
152 pub fn universe(self) -> ty::UniverseIndex {
154 CanonicalVarKind::Ty(kind) => match kind {
155 CanonicalTyVarKind::General(ui) => ui,
156 CanonicalTyVarKind::Float | CanonicalTyVarKind::Int => ty::UniverseIndex::ROOT,
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,
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),
178 /// Integral type variable `?I` (that can only be unified with integral types).
181 /// Floating-point type variable `?F` (that can only be unified with float types).
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
198 pub opaque_types: Vec<(Ty<'tcx>, Ty<'tcx>)>,
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>>,
208 impl QueryRegionConstraints<'_> {
209 /// Represents an empty (trivially true) set of region
211 pub fn is_empty(&self) -> bool {
212 self.outlives.is_empty() && self.member_constraints.is_empty()
216 pub type CanonicalQueryResponse<'tcx, T> = &'tcx Canonical<'tcx, QueryResponse<'tcx, T>>;
218 /// Indicates whether or not we were able to prove the query to be
220 #[derive(Copy, Clone, Debug, HashStable)]
222 /// The query is known to be true, presuming that you apply the
223 /// given `var_values` and the region-constraints are satisfied.
226 /// The query is not known to be true, but also not known to be
227 /// false. The `var_values` represent *either* values that must
228 /// hold in order for the query to be true, or helpful tips that
229 /// *might* make it true. Currently rustc's trait solver cannot
230 /// distinguish the two (e.g., due to our preference for where
231 /// clauses over impls).
233 /// After some unification and things have been done, it makes
234 /// sense to try and prove again -- of course, at that point, the
235 /// canonical form will be different, making this a distinct
241 pub fn is_proven(&self) -> bool {
243 Certainty::Proven => true,
244 Certainty::Ambiguous => false,
249 impl<'tcx, R> QueryResponse<'tcx, R> {
250 pub fn is_proven(&self) -> bool {
251 self.certainty.is_proven()
255 impl<'tcx, R> Canonical<'tcx, QueryResponse<'tcx, R>> {
256 pub fn is_proven(&self) -> bool {
257 self.value.is_proven()
260 pub fn is_ambiguous(&self) -> bool {
265 impl<'tcx, R> Canonical<'tcx, ty::ParamEnvAnd<'tcx, R>> {
267 pub fn without_const(mut self) -> Self {
268 self.value = self.value.without_const();
273 impl<'tcx, V> Canonical<'tcx, V> {
274 /// Allows you to map the `value` of a canonical while keeping the
275 /// same set of bound variables.
277 /// **WARNING:** This function is very easy to mis-use, hence the
278 /// name! In particular, the new value `W` must use all **the
279 /// same type/region variables** in **precisely the same order**
280 /// as the original! (The ordering is defined by the
281 /// `TypeFoldable` implementation of the type in question.)
283 /// An example of a **correct** use of this:
285 /// ```rust,ignore (not real code)
286 /// let a: Canonical<'_, T> = ...;
287 /// let b: Canonical<'_, (T,)> = a.unchecked_map(|v| (v, ));
290 /// An example of an **incorrect** use of this:
292 /// ```rust,ignore (not real code)
293 /// let a: Canonical<'tcx, T> = ...;
294 /// let ty: Ty<'tcx> = ...;
295 /// let b: Canonical<'tcx, (T, Ty<'tcx>)> = a.unchecked_map(|v| (v, ty));
297 pub fn unchecked_map<W>(self, map_op: impl FnOnce(V) -> W) -> Canonical<'tcx, W> {
298 let Canonical { max_universe, variables, value } = self;
299 Canonical { max_universe, variables, value: map_op(value) }
302 /// Allows you to map the `value` of a canonical while keeping the same set of
305 /// **WARNING:** This function is very easy to mis-use, hence the name! See
306 /// the comment of [Canonical::unchecked_map] for more details.
307 pub fn unchecked_rebind<W>(self, value: W) -> Canonical<'tcx, W> {
308 let Canonical { max_universe, variables, value: _ } = self;
309 Canonical { max_universe, variables, value }
313 pub type QueryOutlivesConstraint<'tcx> = (
314 ty::Binder<'tcx, ty::OutlivesPredicate<GenericArg<'tcx>, Region<'tcx>>>,
315 ConstraintCategory<'tcx>,
318 TrivialTypeTraversalAndLiftImpls! {
320 crate::infer::canonical::Certainty,
321 crate::infer::canonical::CanonicalTyVarKind,
325 impl<'tcx> CanonicalVarValues<'tcx> {
327 pub fn len(&self) -> usize {
328 self.var_values.len()
331 /// Makes an identity substitution from this one: each bound var
332 /// is matched to the same bound var, preserving the original kinds.
333 /// For example, if we have:
334 /// `self.var_values == [Type(u32), Lifetime('a), Type(u64)]`
335 /// we'll return a substitution `subst` with:
336 /// `subst.var_values == [Type(^0), Lifetime(^1), Type(^2)]`.
337 pub fn make_identity(&self, tcx: TyCtxt<'tcx>) -> Self {
338 use crate::ty::subst::GenericArgKind;
341 var_values: iter::zip(&self.var_values, 0..)
342 .map(|(kind, i)| match kind.unpack() {
343 GenericArgKind::Type(..) => {
344 tcx.mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_u32(i).into())).into()
346 GenericArgKind::Lifetime(..) => {
347 let br = ty::BoundRegion {
348 var: ty::BoundVar::from_u32(i),
349 kind: ty::BrAnon(i, None),
351 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into()
353 GenericArgKind::Const(ct) => tcx
355 ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_u32(i)),
365 impl<'a, 'tcx> IntoIterator for &'a CanonicalVarValues<'tcx> {
366 type Item = GenericArg<'tcx>;
367 type IntoIter = ::std::iter::Cloned<::std::slice::Iter<'a, GenericArg<'tcx>>>;
369 fn into_iter(self) -> Self::IntoIter {
370 self.var_values.iter().cloned()
374 impl<'tcx> Index<BoundVar> for CanonicalVarValues<'tcx> {
375 type Output = GenericArg<'tcx>;
377 fn index(&self, value: BoundVar) -> &GenericArg<'tcx> {
378 &self.var_values[value]