1//! Canonicalization is used to separate some goal from its context,
2//! throwing away unnecessary information in the process.
3//!
4//! This is necessary to cache goals containing inference variables
5//! and placeholders without restricting them to the current `InferCtxt`.
6//!
7//! Canonicalization is fairly involved, for more details see the relevant
8//! section of the [rustc-dev-guide][c].
9//!
10//! [c]: https://rustc-dev-guide.rust-lang.org/solve/canonicalization.html
1112use std::iter;
1314use canonicalizer::Canonicalizer;
15use rustc_index::IndexVec;
16use rustc_type_ir::inherent::*;
17use rustc_type_ir::relate::solver_relating::RelateExt;
18use rustc_type_ir::{
19selfas ty, Canonical, CanonicalVarKind, CanonicalVarValues, InferCtxtLike, Interner,
20TypeFoldable,
21};
22use tracing::instrument;
2324use crate::delegate::SolverDelegate;
25use crate::resolve::eager_resolve_vars;
26use crate::solve::{
27CanonicalInput, CanonicalResponse, Certainty, ExternalConstraintsData, Goal,
28NestedNormalizationGoals, QueryInput, Response, inspect,
29};
3031pub mod canonicalizer;
3233trait ResponseT<I: Interner> {
34fn var_values(&self) -> CanonicalVarValues<I>;
35}
3637impl<I: Interner> ResponseT<I> for Response<I> {
38fn var_values(&self) -> CanonicalVarValues<I> {
39self.var_values
40 }
41}
4243impl<I: Interner, T> ResponseT<I> for inspect::State<I, T> {
44fn var_values(&self) -> CanonicalVarValues<I> {
45self.var_values
46 }
47}
4849/// Canonicalizes the goal remembering the original values
50/// for each bound variable.
51///
52/// This expects `goal` and `opaque_types` to be eager resolved.
53pub(super) fn canonicalize_goal<D, I>(
54 delegate: &D,
55 goal: Goal<I, I::Predicate>,
56 opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
57) -> (Vec<I::GenericArg>, CanonicalInput<I, I::Predicate>)
58where
59D: SolverDelegate<Interner = I>,
60 I: Interner,
61{
62let (orig_values, canonical) = Canonicalizer::canonicalize_input(
63delegate,
64QueryInput {
65goal,
66 predefined_opaques_in_body: delegate.cx().mk_predefined_opaques_in_body(opaque_types),
67 },
68 );
69let query_input = ty::CanonicalQueryInput { canonical, typing_mode: delegate.typing_mode() };
70 (orig_values, query_input)
71}
7273pub(super) fn canonicalize_response<D, I, T>(
74 delegate: &D,
75 max_input_universe: ty::UniverseIndex,
76 value: T,
77) -> ty::Canonical<I, T>
78where
79D: SolverDelegate<Interner = I>,
80 I: Interner,
81 T: TypeFoldable<I>,
82{
83Canonicalizer::canonicalize_response(delegate, max_input_universe, value)
84}
8586/// After calling a canonical query, we apply the constraints returned
87/// by the query using this function.
88///
89/// This happens in three steps:
90/// - we instantiate the bound variables of the query response
91/// - we unify the `var_values` of the response with the `original_values`
92/// - we apply the `external_constraints` returned by the query, returning
93/// the `normalization_nested_goals`
94pub(super) fn instantiate_and_apply_query_response<D, I>(
95 delegate: &D,
96 param_env: I::ParamEnv,
97 original_values: &[I::GenericArg],
98 response: CanonicalResponse<I>,
99 span: I::Span,
100) -> (NestedNormalizationGoals<I>, Certainty)
101where
102D: SolverDelegate<Interner = I>,
103 I: Interner,
104{
105let instantiation =
106compute_query_response_instantiation_values(delegate, &original_values, &response, span);
107108let Response { var_values, external_constraints, certainty } =
109delegate.instantiate_canonical(response, instantiation);
110111unify_query_var_values(delegate, param_env, &original_values, var_values, span);
112113let ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals } =
114&*external_constraints;
115116register_region_constraints(delegate, region_constraints, span);
117register_new_opaque_types(delegate, opaque_types, span);
118119 (normalization_nested_goals.clone(), certainty)
120}
121122/// This returns the canonical variable values to instantiate the bound variables of
123/// the canonical response. This depends on the `original_values` for the
124/// bound variables.
125fn compute_query_response_instantiation_values<D, I, T>(
126 delegate: &D,
127 original_values: &[I::GenericArg],
128 response: &Canonical<I, T>,
129 span: I::Span,
130) -> CanonicalVarValues<I>
131where
132D: SolverDelegate<Interner = I>,
133 I: Interner,
134 T: ResponseT<I>,
135{
136// FIXME: Longterm canonical queries should deal with all placeholders
137 // created inside of the query directly instead of returning them to the
138 // caller.
139let prev_universe = delegate.universe();
140let universes_created_in_query = response.max_universe.index();
141for _ in 0..universes_created_in_query {
142 delegate.create_next_universe();
143 }
144145let var_values = response.value.var_values();
146match (&original_values.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);
}
}
};assert_eq!(original_values.len(), var_values.len());
147148// If the query did not make progress with constraining inference variables,
149 // we would normally create a new inference variables for bound existential variables
150 // only then unify this new inference variable with the inference variable from
151 // the input.
152 //
153 // We therefore instantiate the existential variable in the canonical response with the
154 // inference variable of the input right away, which is more performant.
155let mut opt_values = IndexVec::from_elem_n(None, response.var_kinds.len());
156for (original_value, result_value) in iter::zip(original_values, var_values.var_values.iter()) {
157match result_value.kind() {
158 ty::GenericArgKind::Type(t) => {
159// We disable the instantiation guess for inference variables
160 // and only use it for placeholders. We need to handle the
161 // `sub_root` of type inference variables which would make this
162 // more involved. They are also a lot rarer than region variables.
163if let ty::Bound(index_kind, b) = t.kind()
164 && !#[allow(non_exhaustive_omitted_patterns)] match response.var_kinds.get(b.var().as_usize()).unwrap()
{
CanonicalVarKind::Ty { .. } => true,
_ => false,
}matches!(
165 response.var_kinds.get(b.var().as_usize()).unwrap(),
166 CanonicalVarKind::Ty { .. }
167 )168 {
169if !#[allow(non_exhaustive_omitted_patterns)] match index_kind {
ty::BoundVarIndexKind::Canonical => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(index_kind, ty::BoundVarIndexKind::Canonical)")
};assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
170 opt_values[b.var()] = Some(*original_value);
171 }
172 }
173 ty::GenericArgKind::Lifetime(r) => {
174if let ty::ReBound(index_kind, br) = r.kind() {
175if !#[allow(non_exhaustive_omitted_patterns)] match index_kind {
ty::BoundVarIndexKind::Canonical => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(index_kind, ty::BoundVarIndexKind::Canonical)")
};assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
176 opt_values[br.var()] = Some(*original_value);
177 }
178 }
179 ty::GenericArgKind::Const(c) => {
180if let ty::ConstKind::Bound(index_kind, bc) = c.kind() {
181if !#[allow(non_exhaustive_omitted_patterns)] match index_kind {
ty::BoundVarIndexKind::Canonical => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(index_kind, ty::BoundVarIndexKind::Canonical)")
};assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
182 opt_values[bc.var()] = Some(*original_value);
183 }
184 }
185 }
186 }
187CanonicalVarValues::instantiate(delegate.cx(), response.var_kinds, |var_values, kind| {
188if kind.universe() != ty::UniverseIndex::ROOT {
189// A variable from inside a binder of the query. While ideally these shouldn't
190 // exist at all (see the FIXME at the start of this method), we have to deal with
191 // them for now.
192delegate.instantiate_canonical_var(kind, span, &var_values, |idx| {
193prev_universe + idx.index()
194 })
195 } else if kind.is_existential() {
196// As an optimization we sometimes avoid creating a new inference variable here.
197 //
198 // All new inference variables we create start out in the current universe of the caller.
199 // This is conceptually wrong as these inference variables would be able to name
200 // more placeholders then they should be able to. However the inference variables have
201 // to "come from somewhere", so by equating them with the original values of the caller
202 // later on, we pull them down into their correct universe again.
203if let Some(v) = opt_values[ty::BoundVar::from_usize(var_values.len())] {
204v205 } else {
206delegate.instantiate_canonical_var(kind, span, &var_values, |_| prev_universe)
207 }
208 } else {
209// For placeholders which were already part of the input, we simply map this
210 // universal bound variable back the placeholder of the input.
211original_values[kind.expect_placeholder_index()]
212 }
213 })
214}
215216/// Unify the `original_values` with the `var_values` returned by the canonical query..
217///
218/// This assumes that this unification will always succeed. This is the case when
219/// applying a query response right away. However, calling a canonical query, doing any
220/// other kind of trait solving, and only then instantiating the result of the query
221/// can cause the instantiation to fail. This is not supported and we ICE in this case.
222///
223/// We always structurally instantiate aliases. Relating aliases needs to be different
224/// depending on whether the alias is *rigid* or not. We're only really able to tell
225/// whether an alias is rigid by using the trait solver. When instantiating a response
226/// from the solver we assume that the solver correctly handled aliases and therefore
227/// always relate them structurally here.
228#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("unify_query_var_values",
"rustc_next_trait_solver::canonical",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/canonical/mod.rs"),
::tracing_core::__macro_support::Option::Some(228u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::canonical"),
::tracing_core::field::FieldSet::new(&["param_env",
"original_values", "var_values", "span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&original_values)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_values)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match (&original_values.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);
}
}
};
for (&orig, response) in
iter::zip(original_values, var_values.var_values.iter()) {
let goals =
delegate.eq_structurally_relating_aliases(param_env, orig,
response, span).unwrap();
if !goals.is_empty() {
::core::panicking::panic("assertion failed: goals.is_empty()")
};
}
}
}
}#[instrument(level = "trace", skip(delegate))]229fn unify_query_var_values<D, I>(
230 delegate: &D,
231 param_env: I::ParamEnv,
232 original_values: &[I::GenericArg],
233 var_values: CanonicalVarValues<I>,
234 span: I::Span,
235) where
236D: SolverDelegate<Interner = I>,
237 I: Interner,
238{
239assert_eq!(original_values.len(), var_values.len());
240241for (&orig, response) in iter::zip(original_values, var_values.var_values.iter()) {
242let goals =
243 delegate.eq_structurally_relating_aliases(param_env, orig, response, span).unwrap();
244assert!(goals.is_empty());
245 }
246}
247248fn register_region_constraints<D, I>(
249 delegate: &D,
250 outlives: &[ty::OutlivesPredicate<I, I::GenericArg>],
251 span: I::Span,
252) where
253D: SolverDelegate<Interner = I>,
254 I: Interner,
255{
256for &ty::OutlivesPredicate(lhs, rhs) in outlives {
257match lhs.kind() {
258 ty::GenericArgKind::Lifetime(lhs) => delegate.sub_regions(rhs, lhs, span),
259 ty::GenericArgKind::Type(lhs) => delegate.register_ty_outlives(lhs, rhs, span),
260 ty::GenericArgKind::Const(_) => {
::core::panicking::panic_fmt(format_args!("const outlives: {0:?}: {1:?}",
lhs, rhs));
}panic!("const outlives: {lhs:?}: {rhs:?}"),
261 }
262 }
263}
264265fn register_new_opaque_types<D, I>(
266 delegate: &D,
267 opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
268 span: I::Span,
269) where
270D: SolverDelegate<Interner = I>,
271 I: Interner,
272{
273for &(key, ty) in opaque_types {
274let prev = delegate.register_hidden_type_in_storage(key, ty, span);
275// We eagerly resolve inference variables when computing the query response.
276 // This can cause previously distinct opaque type keys to now be structurally equal.
277 //
278 // To handle this, we store any duplicate entries in a separate list to check them
279 // at the end of typeck/borrowck. We could alternatively eagerly equate the hidden
280 // types here. However, doing so is difficult as it may result in nested goals and
281 // any errors may make it harder to track the control flow for diagnostics.
282if let Some(prev) = prev {
283 delegate.add_duplicate_opaque_type(key, prev, span);
284 }
285 }
286}
287288/// Used by proof trees to be able to recompute intermediate actions while
289/// evaluating a goal. The `var_values` not only include the bound variables
290/// of the query input, but also contain all unconstrained inference vars
291/// created while evaluating this goal.
292pub fn make_canonical_state<D, I, T>(
293 delegate: &D,
294 var_values: &[I::GenericArg],
295 max_input_universe: ty::UniverseIndex,
296 data: T,
297) -> inspect::CanonicalState<I, T>
298where
299D: SolverDelegate<Interner = I>,
300 I: Interner,
301 T: TypeFoldable<I>,
302{
303let var_values = CanonicalVarValues { var_values: delegate.cx().mk_args(var_values) };
304let state = inspect::State { var_values, data };
305let state = eager_resolve_vars(delegate, state);
306Canonicalizer::canonicalize_response(delegate, max_input_universe, state)
307}
308309// FIXME: needs to be pub to be accessed by downstream
310// `rustc_trait_selection::solve::inspect::analyse`.
311pub fn instantiate_canonical_state<D, I, T>(
312 delegate: &D,
313 span: I::Span,
314 param_env: I::ParamEnv,
315 orig_values: &mut Vec<I::GenericArg>,
316 state: inspect::CanonicalState<I, T>,
317) -> T
318where
319D: SolverDelegate<Interner = I>,
320 I: Interner,
321 T: TypeFoldable<I>,
322{
323// In case any fresh inference variables have been created between `state`
324 // and the previous instantiation, extend `orig_values` for it.
325orig_values.extend(
326state.value.var_values.var_values.as_slice()[orig_values.len()..]
327 .iter()
328 .map(|&arg| delegate.fresh_var_for_kind_with_span(arg, span)),
329 );
330331let instantiation =
332compute_query_response_instantiation_values(delegate, orig_values, &state, span);
333334let inspect::State { var_values, data } = delegate.instantiate_canonical(state, instantiation);
335336unify_query_var_values(delegate, param_env, orig_values, var_values, span);
337data338}
339340pub fn response_no_constraints_raw<I: Interner>(
341 cx: I,
342 max_universe: ty::UniverseIndex,
343 var_kinds: I::CanonicalVarKinds,
344 certainty: Certainty,
345) -> CanonicalResponse<I> {
346 ty::Canonical {
347max_universe,
348var_kinds,
349 value: Response {
350 var_values: ty::CanonicalVarValues::make_identity(cx, var_kinds),
351// FIXME: maybe we should store the "no response" version in cx, like
352 // we do for cx.types and stuff.
353external_constraints: cx.mk_external_constraints(ExternalConstraintsData::default()),
354certainty,
355 },
356 }
357}