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, TypingMode, TypingModeEqWrapper,
21};
22use tracing::instrument;
2324use crate::delegate::SolverDelegate;
25use crate::resolve::eager_resolve_vars;
26use crate::solve::{
27CanonicalInput, CanonicalResponse, Certainty, ExternalConstraintsData,
28ExternalRegionConstraints, Goal, NestedNormalizationGoals, QueryInput, Response,
29VisibleForLeakCheck, inspect,
30};
3132pub mod canonicalizer;
3334trait ResponseT<I: Interner> {
35fn var_values(&self) -> CanonicalVarValues<I>;
36}
3738impl<I: Interner> ResponseT<I> for Response<I> {
39fn var_values(&self) -> CanonicalVarValues<I> {
40self.var_values
41 }
42}
4344impl<I: Interner, T> ResponseT<I> for inspect::State<I, T> {
45fn var_values(&self) -> CanonicalVarValues<I> {
46self.var_values
47 }
48}
4950/// Canonicalizes the goal remembering the original values
51/// for each bound variable.
52///
53/// This expects `goal` and `opaque_types` to be eager resolved.
54pub(super) fn canonicalize_goal<D, I>(
55 delegate: &D,
56 goal: Goal<I, I::Predicate>,
57 opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
58 typing_mode: TypingMode<I>,
59) -> (Vec<I::GenericArg>, CanonicalInput<I, I::Predicate>)
60where
61D: SolverDelegate<Interner = I>,
62 I: Interner,
63{
64let (orig_values, canonical) = Canonicalizer::canonicalize_input(
65delegate,
66QueryInput {
67goal,
68 predefined_opaques_in_body: delegate.cx().mk_predefined_opaques_in_body(opaque_types),
69 },
70 );
7172let query_input =
73 ty::CanonicalQueryInput { canonical, typing_mode: TypingModeEqWrapper(typing_mode) };
74 (orig_values, query_input)
75}
7677pub(super) fn canonicalize_response<D, I, T>(
78 delegate: &D,
79 max_input_universe: ty::UniverseIndex,
80 value: T,
81) -> ty::Canonical<I, T>
82where
83D: SolverDelegate<Interner = I>,
84 I: Interner,
85 T: TypeFoldable<I>,
86{
87Canonicalizer::canonicalize_response(delegate, max_input_universe, value)
88}
8990/// After calling a canonical query, we apply the constraints returned
91/// by the query using this function.
92///
93/// This happens in three steps:
94/// - we instantiate the bound variables of the query response
95/// - we unify the `var_values` of the response with the `original_values`
96/// - we apply the `external_constraints` returned by the query, returning
97/// the `normalization_nested_goals`
98pub(super) fn instantiate_and_apply_query_response<D, I>(
99 delegate: &D,
100 param_env: I::ParamEnv,
101 original_values: &[I::GenericArg],
102 response: CanonicalResponse<I>,
103 span: I::Span,
104) -> (NestedNormalizationGoals<I>, Certainty)
105where
106D: SolverDelegate<Interner = I>,
107 I: Interner,
108{
109let instantiation =
110compute_query_response_instantiation_values(delegate, &original_values, &response, span);
111112let Response { var_values, external_constraints, certainty } =
113delegate.instantiate_canonical(response, instantiation);
114115unify_query_var_values(delegate, param_env, &original_values, var_values, span);
116117let ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals } =
118&*external_constraints;
119120match region_constraints {
121 ExternalRegionConstraints::Old(r) => register_region_constraints(
122delegate,
123r.iter().map(|(c, vis)| {
124// FIXME: We should revisit and consider removing this after *assumptions on
125 // binders* is available, like once we had done in the stabilization of
126 // `-Znext-solver=coherence`(#121848).
127 // We ignore constraints from the nested goals in leak check. This is to match with
128 // the old solver's behavior, which has separated evaluation and fulfillment, and
129 // the former doesn't consider outlives obligations from the later.
130(*c, vis.and(VisibleForLeakCheck::No))
131 }),
132span,
133 ),
134 ExternalRegionConstraints::NextGen(r) => {
135delegate.register_solver_region_constraint(r.clone())
136 }
137 };
138register_new_opaque_types(delegate, opaque_types, span);
139140 (normalization_nested_goals.clone(), certainty)
141}
142143/// This returns the canonical variable values to instantiate the bound variables of
144/// the canonical response. This depends on the `original_values` for the
145/// bound variables.
146fn compute_query_response_instantiation_values<D, I, T>(
147 delegate: &D,
148 original_values: &[I::GenericArg],
149 response: &Canonical<I, T>,
150 span: I::Span,
151) -> CanonicalVarValues<I>
152where
153D: SolverDelegate<Interner = I>,
154 I: Interner,
155 T: ResponseT<I>,
156{
157// FIXME: Longterm canonical queries should deal with all placeholders
158 // created inside of the query directly instead of returning them to the
159 // caller.
160let prev_universe = delegate.universe();
161let universes_created_in_query = response.max_universe.index();
162for _ in 0..universes_created_in_query {
163 delegate.create_next_universe();
164 }
165166let var_values = response.value.var_values();
167{
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);
}
}
}
};assert_eq!(original_values.len(), var_values.len());
168169// If the query did not make progress with constraining inference variables,
170 // we would normally create a new inference variables for bound existential variables
171 // only then unify this new inference variable with the inference variable from
172 // the input.
173 //
174 // We therefore instantiate the existential variable in the canonical response with the
175 // inference variable of the input right away, which is more performant.
176let mut opt_values = IndexVec::from_elem_n(None, response.var_kinds.len());
177for (original_value, result_value) in iter::zip(original_values, var_values.var_values.iter()) {
178match result_value.kind() {
179 ty::GenericArgKind::Type(t) => {
180// We disable the instantiation guess for inference variables
181 // and only use it for placeholders. We need to handle the
182 // `sub_root` of type inference variables which would make this
183 // more involved. They are also a lot rarer than region variables.
184if let ty::Bound(index_kind, b) = t.kind()
185 && !#[allow(non_exhaustive_omitted_patterns)] match response.var_kinds.get(b.var().as_usize()).unwrap()
{
CanonicalVarKind::Ty { .. } => true,
_ => false,
}matches!(
186 response.var_kinds.get(b.var().as_usize()).unwrap(),
187 CanonicalVarKind::Ty { .. }
188 )189 {
190if !#[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));
191 opt_values[b.var()] = Some(*original_value);
192 }
193 }
194 ty::GenericArgKind::Lifetime(r) => {
195if let ty::ReBound(index_kind, br) = r.kind() {
196if !#[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));
197 opt_values[br.var()] = Some(*original_value);
198 }
199 }
200 ty::GenericArgKind::Const(c) => {
201if let ty::ConstKind::Bound(index_kind, bc) = c.kind() {
202if !#[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));
203 opt_values[bc.var()] = Some(*original_value);
204 }
205 }
206 }
207 }
208CanonicalVarValues::instantiate(delegate.cx(), response.var_kinds, |var_values, kind| {
209if kind.universe() != ty::UniverseIndex::ROOT {
210// A variable from inside a binder of the query. While ideally these shouldn't
211 // exist at all (see the FIXME at the start of this method), we have to deal with
212 // them for now.
213delegate.instantiate_canonical_var(kind, span, &var_values, |idx| {
214prev_universe + idx.index()
215 })
216 } else if kind.is_existential() {
217// As an optimization we sometimes avoid creating a new inference variable here.
218 //
219 // All new inference variables we create start out in the current universe of the caller.
220 // This is conceptually wrong as these inference variables would be able to name
221 // more placeholders then they should be able to. However the inference variables have
222 // to "come from somewhere", so by equating them with the original values of the caller
223 // later on, we pull them down into their correct universe again.
224if let Some(v) = opt_values[ty::BoundVar::from_usize(var_values.len())] {
225v226 } else {
227delegate.instantiate_canonical_var(kind, span, &var_values, |_| prev_universe)
228 }
229 } else {
230// For placeholders which were already part of the input, we simply map this
231 // universal bound variable back the placeholder of the input.
232 //
233 // For `CanonicalVarKind::PlaceholderRegion`, this differs slightly: we
234 // canonicalize all free regions from the input into placeholders. This is
235 // unlike types or consts, where only input placeholders remain placeholders
236 // in the canonical form.
237 //
238 // We can still map these back to the original input regions, as we
239 // just instantiate the canonical variable with its corresponding
240 // `original_value`.
241 //
242 // For more information on why we canonicalize all input regions as
243 // placeholders, see the comment in `Canonicalizer::fold_region`.
244original_values[kind.expect_placeholder_index()]
245 }
246 })
247}
248249/// Unify the `original_values` with the `var_values` returned by the canonical query..
250///
251/// This assumes that this unification will always succeed. This is the case when
252/// applying a query response right away. However, calling a canonical query, doing any
253/// other kind of trait solving, and only then instantiating the result of the query
254/// can cause the instantiation to fail. This is not supported and we ICE in this case.
255///
256/// We always structurally instantiate aliases. Relating aliases needs to be different
257/// depending on whether the alias is *rigid* or not. We're only really able to tell
258/// whether an alias is rigid by using the trait solver. When instantiating a response
259/// from the solver we assume that the solver correctly handled aliases and therefore
260/// always relate them structurally here.
261#[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(261u32),
::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))]262fn unify_query_var_values<D, I>(
263 delegate: &D,
264 param_env: I::ParamEnv,
265 original_values: &[I::GenericArg],
266 var_values: CanonicalVarValues<I>,
267 span: I::Span,
268) where
269D: SolverDelegate<Interner = I>,
270 I: Interner,
271{
272assert_eq!(original_values.len(), var_values.len());
273274for (&orig, response) in iter::zip(original_values, var_values.var_values.iter()) {
275let goals =
276 delegate.eq_structurally_relating_aliases(param_env, orig, response, span).unwrap();
277assert!(goals.is_empty());
278 }
279}
280281fn register_region_constraints<D, I>(
282 delegate: &D,
283 constraints: impl IntoIterator<Item = (ty::RegionConstraint<I>, VisibleForLeakCheck)>,
284 span: I::Span,
285) where
286D: SolverDelegate<Interner = I>,
287 I: Interner,
288{
289for (constraint, vis) in constraints {
290match constraint {
291 ty::RegionConstraint::Outlives(ty::OutlivesPredicate(lhs, rhs)) => match lhs.kind() {
292 ty::GenericArgKind::Lifetime(lhs) => delegate.sub_regions(rhs, lhs, vis, span),
293 ty::GenericArgKind::Type(lhs) => delegate.register_ty_outlives(lhs, rhs, span),
294 ty::GenericArgKind::Const(_) => {
::core::panicking::panic_fmt(format_args!("const outlives: {0:?}: {1:?}",
lhs, rhs));
}panic!("const outlives: {lhs:?}: {rhs:?}"),
295 },
296 ty::RegionConstraint::Eq(ty::RegionEqPredicate(lhs, rhs)) => {
297 delegate.equate_regions(lhs, rhs, vis, span)
298 }
299 }
300 }
301}
302303fn register_new_opaque_types<D, I>(
304 delegate: &D,
305 opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
306 span: I::Span,
307) where
308D: SolverDelegate<Interner = I>,
309 I: Interner,
310{
311for &(key, ty) in opaque_types {
312let prev = delegate.register_hidden_type_in_storage(key, ty, span);
313// We eagerly resolve inference variables when computing the query response.
314 // This can cause previously distinct opaque type keys to now be structurally equal.
315 //
316 // To handle this, we store any duplicate entries in a separate list to check them
317 // at the end of typeck/borrowck. We could alternatively eagerly equate the hidden
318 // types here. However, doing so is difficult as it may result in nested goals and
319 // any errors may make it harder to track the control flow for diagnostics.
320if let Some(prev) = prev {
321 delegate.add_duplicate_opaque_type(key, prev, span);
322 }
323 }
324}
325326/// Used by proof trees to be able to recompute intermediate actions while
327/// evaluating a goal. The `var_values` not only include the bound variables
328/// of the query input, but also contain all unconstrained inference vars
329/// created while evaluating this goal.
330pub fn make_canonical_state<D, I, T>(
331 delegate: &D,
332 var_values: &[I::GenericArg],
333 max_input_universe: ty::UniverseIndex,
334 data: T,
335) -> inspect::CanonicalState<I, T>
336where
337D: SolverDelegate<Interner = I>,
338 I: Interner,
339 T: TypeFoldable<I>,
340{
341let var_values = CanonicalVarValues { var_values: delegate.cx().mk_args(var_values) };
342let state = inspect::State { var_values, data };
343let state = eager_resolve_vars(&**delegate, state);
344Canonicalizer::canonicalize_response(delegate, max_input_universe, state)
345}
346347// FIXME: needs to be pub to be accessed by downstream
348// `rustc_trait_selection::solve::inspect::analyse`.
349pub fn instantiate_canonical_state<D, I, T>(
350 delegate: &D,
351 span: I::Span,
352 param_env: I::ParamEnv,
353 orig_values: &mut Vec<I::GenericArg>,
354 state: inspect::CanonicalState<I, T>,
355) -> T
356where
357D: SolverDelegate<Interner = I>,
358 I: Interner,
359 T: TypeFoldable<I>,
360{
361// In case any fresh inference variables have been created between `state`
362 // and the previous instantiation, extend `orig_values` for it.
363orig_values.extend(
364state.value.var_values.var_values.as_slice()[orig_values.len()..]
365 .iter()
366 .map(|&arg| delegate.fresh_var_for_kind_with_span(arg, span)),
367 );
368369let instantiation =
370compute_query_response_instantiation_values(delegate, orig_values, &state, span);
371372let inspect::State { var_values, data } = delegate.instantiate_canonical(state, instantiation);
373374unify_query_var_values(delegate, param_env, orig_values, var_values, span);
375data376}
377378pub fn response_no_constraints_raw<I: Interner>(
379 cx: I,
380 max_universe: ty::UniverseIndex,
381 var_kinds: I::CanonicalVarKinds,
382 certainty: Certainty,
383) -> CanonicalResponse<I> {
384 ty::Canonical {
385max_universe,
386var_kinds,
387 value: Response {
388 var_values: ty::CanonicalVarValues::make_identity(cx, var_kinds),
389// FIXME: maybe we should store the "no response" version in cx, like
390 // we do for cx.types and stuff.
391external_constraints: cx.mk_external_constraints(ExternalConstraintsData::new(cx)),
392certainty,
393 },
394 }
395}