1//! This module contains code to instantiate new values into a
2//! `Canonical<'tcx, T>`.
3//!
4//! For an overview of what canonicalization is and how it fits into
5//! rustc, check out the [chapter in the rustc dev guide][c].
6//!
7//! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html
89use rustc_macros::extension;
10use rustc_middle::ty::{
11self, DelayedMap, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeFolder, TypeSuperFoldable,
12TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
13};
1415use crate::infer::canonical::{Canonical, CanonicalVarValues};
1617/// FIXME(-Znext-solver): This or public because it is shared with the
18/// new trait solver implementation. We should deduplicate canonicalization.
19impl<'tcx, V> CanonicalExt<'tcx, V> for Canonical<'tcx, V> {
#[doc = " Instantiate the wrapped value, replacing each canonical value"]
#[doc = " with the value given in `var_values`."]
fn instantiate(&self, tcx: TyCtxt<'tcx>,
var_values: &CanonicalVarValues<'tcx>) -> V where
V: TypeFoldable<TyCtxt<'tcx>> {
self.instantiate_projected(tcx, var_values, |value| value.clone())
}
#[doc = " Allows one to apply a instantiation to some subset of"]
#[doc = " `self.value`. Invoke `projection_fn` with `self.value` to get"]
#[doc = " a value V that is expressed in terms of the same canonical"]
#[doc = " variables bound in `self` (usually this extracts from subset"]
#[doc = " of `self`). Apply the instantiation `var_values` to this value"]
#[doc = " V, replacing each of the canonical variables."]
fn instantiate_projected<T>(&self, tcx: TyCtxt<'tcx>,
var_values: &CanonicalVarValues<'tcx>,
projection_fn: impl FnOnce(&V) -> T) -> T where
T: TypeFoldable<TyCtxt<'tcx>> {
{
match (&self.var_kinds.len(), &var_values.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
let value = projection_fn(&self.value);
instantiate_value(tcx, var_values, value)
}
}#[extension(pub trait CanonicalExt<'tcx, V>)]20impl<'tcx, V> Canonical<'tcx, V> {
21/// Instantiate the wrapped value, replacing each canonical value
22 /// with the value given in `var_values`.
23fn instantiate(&self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>) -> V
24where
25V: TypeFoldable<TyCtxt<'tcx>>,
26 {
27self.instantiate_projected(tcx, var_values, |value| value.clone())
28 }
2930/// Allows one to apply a instantiation to some subset of
31 /// `self.value`. Invoke `projection_fn` with `self.value` to get
32 /// a value V that is expressed in terms of the same canonical
33 /// variables bound in `self` (usually this extracts from subset
34 /// of `self`). Apply the instantiation `var_values` to this value
35 /// V, replacing each of the canonical variables.
36fn instantiate_projected<T>(
37&self,
38 tcx: TyCtxt<'tcx>,
39 var_values: &CanonicalVarValues<'tcx>,
40 projection_fn: impl FnOnce(&V) -> T,
41 ) -> T
42where
43T: TypeFoldable<TyCtxt<'tcx>>,
44 {
45assert_eq!(self.var_kinds.len(), var_values.len());
46let value = projection_fn(&self.value);
47instantiate_value(tcx, var_values, value)
48 }
49}
5051/// Instantiate the values from `var_values` into `value`. `var_values`
52/// must be values for the set of canonical variables that appear in
53/// `value`.
54pub(super) fn instantiate_value<'tcx, T>(
55 tcx: TyCtxt<'tcx>,
56 var_values: &CanonicalVarValues<'tcx>,
57 value: T,
58) -> T
59where
60T: TypeFoldable<TyCtxt<'tcx>>,
61{
62if var_values.var_values.is_empty() {
63return value;
64 }
6566value.fold_with(&mut CanonicalInstantiator {
67tcx,
68 var_values: var_values.var_values,
69 cache: Default::default(),
70 })
71}
7273/// Replaces the bound vars in a canonical binder with var values.
74struct CanonicalInstantiator<'tcx> {
75 tcx: TyCtxt<'tcx>,
7677// The values that the bound vars are are being instantiated with.
78var_values: ty::GenericArgsRef<'tcx>,
7980// Because we use `ty::BoundVarIndexKind::Canonical`, we can cache
81 // based only on the entire ty, not worrying about a `DebruijnIndex`
82cache: DelayedMap<Ty<'tcx>, Ty<'tcx>>,
83}
8485impl<'tcx> TypeFolder<TyCtxt<'tcx>> for CanonicalInstantiator<'tcx> {
86fn cx(&self) -> TyCtxt<'tcx> {
87self.tcx
88 }
8990fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
91match *t.kind() {
92 ty::Bound(ty::BoundVarIndexKind::Canonical, bound_ty) => {
93self.var_values[bound_ty.var.as_usize()].expect_ty()
94 }
95_ => {
96if !t.has_type_flags(TypeFlags::HAS_CANONICAL_BOUND) {
97t98 } else if let Some(&t) = self.cache.get(&t) {
99t100 } else {
101let res = t.super_fold_with(self);
102if !self.cache.insert(t, res) {
::core::panicking::panic("assertion failed: self.cache.insert(t, res)")
};assert!(self.cache.insert(t, res));
103res104 }
105 }
106 }
107 }
108109fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
110match r.kind() {
111 ty::ReBound(ty::BoundVarIndexKind::Canonical, br) => {
112self.var_values[br.var.as_usize()].expect_region()
113 }
114_ => r,
115 }
116 }
117118fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
119match ct.kind() {
120 ty::ConstKind::Bound(ty::BoundVarIndexKind::Canonical, bound_const) => {
121self.var_values[bound_const.var.as_usize()].expect_const()
122 }
123_ => ct.super_fold_with(self),
124 }
125 }
126127fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
128if p.has_type_flags(TypeFlags::HAS_CANONICAL_BOUND) { p.super_fold_with(self) } else { p }
129 }
130131fn fold_clauses(&mut self, c: ty::Clauses<'tcx>) -> ty::Clauses<'tcx> {
132if !c.has_type_flags(TypeFlags::HAS_CANONICAL_BOUND) {
133return c;
134 }
135136// Our cache key is `(clauses, var_values)`, but we also don't care about
137 // var values that aren't named in the clauses, since they can change without
138 // affecting the output. Since `ParamEnv`s are cached first, we compute the
139 // last var value that is mentioned in the clauses, and cut off the list so
140 // that we have more hits in the cache.
141142 // We also cache the computation of "highest var named by clauses" since that
143 // is both expensive (depending on the size of the clauses) and a pure function.
144let index = *self145 .tcx
146 .highest_var_in_clauses_cache
147 .lock()
148 .entry(c)
149 .or_insert_with(|| highest_var_in_clauses(c));
150let c_args = &self.var_values[..=index];
151152if let Some(c) = self.tcx.clauses_cache.lock().get(&(c, c_args)) {
153c154 } else {
155let folded = c.super_fold_with(self);
156self.tcx.clauses_cache.lock().insert((c, c_args), folded);
157folded158 }
159 }
160}
161162fn highest_var_in_clauses<'tcx>(c: ty::Clauses<'tcx>) -> usize {
163struct HighestVarInClauses {
164 max_var: usize,
165 }
166impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HighestVarInClauses {
167fn visit_ty(&mut self, t: Ty<'tcx>) {
168if let ty::Bound(ty::BoundVarIndexKind::Canonical, bound_ty) = *t.kind() {
169self.max_var = self.max_var.max(bound_ty.var.as_usize());
170 } else if t.has_type_flags(TypeFlags::HAS_CANONICAL_BOUND) {
171t.super_visit_with(self);
172 }
173 }
174fn visit_region(&mut self, r: ty::Region<'tcx>) {
175if let ty::ReBound(ty::BoundVarIndexKind::Canonical, bound_region) = r.kind() {
176self.max_var = self.max_var.max(bound_region.var.as_usize());
177 }
178 }
179fn visit_const(&mut self, ct: ty::Const<'tcx>) {
180if let ty::ConstKind::Bound(ty::BoundVarIndexKind::Canonical, bound_const) = ct.kind() {
181self.max_var = self.max_var.max(bound_const.var.as_usize());
182 } else if ct.has_type_flags(TypeFlags::HAS_CANONICAL_BOUND) {
183ct.super_visit_with(self);
184 }
185 }
186 }
187let mut visitor = HighestVarInClauses { max_var: 0 };
188c.visit_with(&mut visitor);
189visitor.max_var
190}