rustc_next_trait_solver/solve/eval_ctxt/canonical.rs
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
11
12use std::iter;
13
14use rustc_index::IndexVec;
15use rustc_type_ir::inherent::*;
16use rustc_type_ir::relate::solver_relating::RelateExt;
17use rustc_type_ir::{
18 self as ty, Canonical, CanonicalVarValues, InferCtxtLike, Interner, TypeFoldable,
19};
20use tracing::{debug, instrument, trace};
21
22use crate::canonicalizer::Canonicalizer;
23use crate::delegate::SolverDelegate;
24use crate::resolve::EagerResolver;
25use crate::solve::eval_ctxt::CurrentGoalKind;
26use crate::solve::{
27 CanonicalInput, CanonicalResponse, Certainty, EvalCtxt, ExternalConstraintsData, Goal,
28 MaybeCause, NestedNormalizationGoals, NoSolution, PredefinedOpaquesData, QueryInput,
29 QueryResult, Response, inspect, response_no_constraints_raw,
30};
31
32trait ResponseT<I: Interner> {
33 fn var_values(&self) -> CanonicalVarValues<I>;
34}
35
36impl<I: Interner> ResponseT<I> for Response<I> {
37 fn var_values(&self) -> CanonicalVarValues<I> {
38 self.var_values
39 }
40}
41
42impl<I: Interner, T> ResponseT<I> for inspect::State<I, T> {
43 fn var_values(&self) -> CanonicalVarValues<I> {
44 self.var_values
45 }
46}
47
48impl<D, I> EvalCtxt<'_, D>
49where
50 D: SolverDelegate<Interner = I>,
51 I: Interner,
52{
53 /// Canonicalizes the goal remembering the original values
54 /// for each bound variable.
55 pub(super) fn canonicalize_goal<T: TypeFoldable<I>>(
56 &self,
57 goal: Goal<I, T>,
58 ) -> (Vec<I::GenericArg>, CanonicalInput<I, T>) {
59 // We only care about one entry per `OpaqueTypeKey` here,
60 // so we only canonicalize the lookup table and ignore
61 // duplicate entries.
62 let opaque_types = self.delegate.clone_opaque_types_lookup_table();
63 let (goal, opaque_types) =
64 (goal, opaque_types).fold_with(&mut EagerResolver::new(self.delegate));
65
66 let mut orig_values = Default::default();
67 let canonical = Canonicalizer::canonicalize_input(
68 self.delegate,
69 &mut orig_values,
70 QueryInput {
71 goal,
72 predefined_opaques_in_body: self
73 .cx()
74 .mk_predefined_opaques_in_body(PredefinedOpaquesData { opaque_types }),
75 },
76 );
77 let query_input = ty::CanonicalQueryInput { canonical, typing_mode: self.typing_mode() };
78 (orig_values, query_input)
79 }
80
81 /// To return the constraints of a canonical query to the caller, we canonicalize:
82 ///
83 /// - `var_values`: a map from bound variables in the canonical goal to
84 /// the values inferred while solving the instantiated goal.
85 /// - `external_constraints`: additional constraints which aren't expressible
86 /// using simple unification of inference variables.
87 ///
88 /// This takes the `shallow_certainty` which represents whether we're confident
89 /// that the final result of the current goal only depends on the nested goals.
90 ///
91 /// In case this is `Certainy::Maybe`, there may still be additional nested goals
92 /// or inference constraints required for this candidate to be hold. The candidate
93 /// always requires all already added constraints and nested goals.
94 #[instrument(level = "trace", skip(self), ret)]
95 pub(in crate::solve) fn evaluate_added_goals_and_make_canonical_response(
96 &mut self,
97 shallow_certainty: Certainty,
98 ) -> QueryResult<I> {
99 self.inspect.make_canonical_response(shallow_certainty);
100
101 let goals_certainty = self.try_evaluate_added_goals()?;
102 assert_eq!(
103 self.tainted,
104 Ok(()),
105 "EvalCtxt is tainted -- nested goals may have been dropped in a \
106 previous call to `try_evaluate_added_goals!`"
107 );
108
109 // We only check for leaks from universes which were entered inside
110 // of the query.
111 self.delegate.leak_check(self.max_input_universe).map_err(|NoSolution| {
112 trace!("failed the leak check");
113 NoSolution
114 })?;
115
116 let (certainty, normalization_nested_goals) =
117 match (self.current_goal_kind, shallow_certainty) {
118 // When normalizing, we've replaced the expected term with an unconstrained
119 // inference variable. This means that we dropped information which could
120 // have been important. We handle this by instead returning the nested goals
121 // to the caller, where they are then handled. We only do so if we do not
122 // need to recompute the `NormalizesTo` goal afterwards to avoid repeatedly
123 // uplifting its nested goals. This is the case if the `shallow_certainty` is
124 // `Certainty::Yes`.
125 (CurrentGoalKind::NormalizesTo, Certainty::Yes) => {
126 let goals = std::mem::take(&mut self.nested_goals);
127 // As we return all ambiguous nested goals, we can ignore the certainty
128 // returned by `self.try_evaluate_added_goals()`.
129 if goals.is_empty() {
130 assert!(matches!(goals_certainty, Certainty::Yes));
131 }
132 (Certainty::Yes, NestedNormalizationGoals(goals))
133 }
134 _ => {
135 let certainty = shallow_certainty.and(goals_certainty);
136 (certainty, NestedNormalizationGoals::empty())
137 }
138 };
139
140 if let Certainty::Maybe(cause @ MaybeCause::Overflow { keep_constraints: false, .. }) =
141 certainty
142 {
143 // If we have overflow, it's probable that we're substituting a type
144 // into itself infinitely and any partial substitutions in the query
145 // response are probably not useful anyways, so just return an empty
146 // query response.
147 //
148 // This may prevent us from potentially useful inference, e.g.
149 // 2 candidates, one ambiguous and one overflow, which both
150 // have the same inference constraints.
151 //
152 // Changing this to retain some constraints in the future
153 // won't be a breaking change, so this is good enough for now.
154 return Ok(self.make_ambiguous_response_no_constraints(cause));
155 }
156
157 let external_constraints =
158 self.compute_external_query_constraints(certainty, normalization_nested_goals);
159 let (var_values, mut external_constraints) = (self.var_values, external_constraints)
160 .fold_with(&mut EagerResolver::new(self.delegate));
161 // Remove any trivial region constraints once we've resolved regions
162 external_constraints
163 .region_constraints
164 .retain(|outlives| outlives.0.as_region().is_none_or(|re| re != outlives.1));
165
166 let canonical = Canonicalizer::canonicalize_response(
167 self.delegate,
168 self.max_input_universe,
169 &mut Default::default(),
170 Response {
171 var_values,
172 certainty,
173 external_constraints: self.cx().mk_external_constraints(external_constraints),
174 },
175 );
176
177 // HACK: We bail with overflow if the response would have too many non-region
178 // inference variables. This tends to only happen if we encounter a lot of
179 // ambiguous alias types which get replaced with fresh inference variables
180 // during generalization. This prevents hangs caused by an exponential blowup,
181 // see tests/ui/traits/next-solver/coherence-alias-hang.rs.
182 match self.current_goal_kind {
183 // We don't do so for `NormalizesTo` goals as we erased the expected term and
184 // bailing with overflow here would prevent us from detecting a type-mismatch,
185 // causing a coherence error in diesel, see #131969. We still bail with overflow
186 // when later returning from the parent AliasRelate goal.
187 CurrentGoalKind::NormalizesTo => {}
188 CurrentGoalKind::Misc | CurrentGoalKind::CoinductiveTrait => {
189 let num_non_region_vars = canonical
190 .variables
191 .iter()
192 .filter(|c| !c.is_region() && c.is_existential())
193 .count();
194 if num_non_region_vars > self.cx().recursion_limit() {
195 debug!(?num_non_region_vars, "too many inference variables -> overflow");
196 return Ok(self.make_ambiguous_response_no_constraints(MaybeCause::Overflow {
197 suggest_increasing_limit: true,
198 keep_constraints: false,
199 }));
200 }
201 }
202 }
203
204 Ok(canonical)
205 }
206
207 /// Constructs a totally unconstrained, ambiguous response to a goal.
208 ///
209 /// Take care when using this, since often it's useful to respond with
210 /// ambiguity but return constrained variables to guide inference.
211 pub(in crate::solve) fn make_ambiguous_response_no_constraints(
212 &self,
213 maybe_cause: MaybeCause,
214 ) -> CanonicalResponse<I> {
215 response_no_constraints_raw(
216 self.cx(),
217 self.max_input_universe,
218 self.variables,
219 Certainty::Maybe(maybe_cause),
220 )
221 }
222
223 /// Computes the region constraints and *new* opaque types registered when
224 /// proving a goal.
225 ///
226 /// If an opaque was already constrained before proving this goal, then the
227 /// external constraints do not need to record that opaque, since if it is
228 /// further constrained by inference, that will be passed back in the var
229 /// values.
230 #[instrument(level = "trace", skip(self), ret)]
231 fn compute_external_query_constraints(
232 &self,
233 certainty: Certainty,
234 normalization_nested_goals: NestedNormalizationGoals<I>,
235 ) -> ExternalConstraintsData<I> {
236 // We only return region constraints once the certainty is `Yes`. This
237 // is necessary as we may drop nested goals on ambiguity, which may result
238 // in unconstrained inference variables in the region constraints. It also
239 // prevents us from emitting duplicate region constraints, avoiding some
240 // unnecessary work. This slightly weakens the leak check in case it uses
241 // region constraints from an ambiguous nested goal. This is tested in both
242 // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-5-ambig.rs` and
243 // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-6-ambig-unify.rs`.
244 let region_constraints = if certainty == Certainty::Yes {
245 self.delegate.make_deduplicated_outlives_constraints()
246 } else {
247 Default::default()
248 };
249
250 // We only return *newly defined* opaque types from canonical queries.
251 //
252 // Constraints for any existing opaque types are already tracked by changes
253 // to the `var_values`.
254 let opaque_types = self
255 .delegate
256 .clone_opaque_types_added_since(self.initial_opaque_types_storage_num_entries);
257
258 ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals }
259 }
260
261 /// After calling a canonical query, we apply the constraints returned
262 /// by the query using this function.
263 ///
264 /// This happens in three steps:
265 /// - we instantiate the bound variables of the query response
266 /// - we unify the `var_values` of the response with the `original_values`
267 /// - we apply the `external_constraints` returned by the query, returning
268 /// the `normalization_nested_goals`
269 pub(super) fn instantiate_and_apply_query_response(
270 &mut self,
271 param_env: I::ParamEnv,
272 original_values: Vec<I::GenericArg>,
273 response: CanonicalResponse<I>,
274 ) -> (NestedNormalizationGoals<I>, Certainty) {
275 let instantiation = Self::compute_query_response_instantiation_values(
276 self.delegate,
277 &original_values,
278 &response,
279 self.origin_span,
280 );
281
282 let Response { var_values, external_constraints, certainty } =
283 self.delegate.instantiate_canonical(response, instantiation);
284
285 Self::unify_query_var_values(
286 self.delegate,
287 param_env,
288 &original_values,
289 var_values,
290 self.origin_span,
291 );
292
293 let ExternalConstraintsData {
294 region_constraints,
295 opaque_types,
296 normalization_nested_goals,
297 } = &*external_constraints;
298
299 self.register_region_constraints(region_constraints);
300 self.register_new_opaque_types(opaque_types);
301
302 (normalization_nested_goals.clone(), certainty)
303 }
304
305 /// This returns the canonical variable values to instantiate the bound variables of
306 /// the canonical response. This depends on the `original_values` for the
307 /// bound variables.
308 fn compute_query_response_instantiation_values<T: ResponseT<I>>(
309 delegate: &D,
310 original_values: &[I::GenericArg],
311 response: &Canonical<I, T>,
312 span: I::Span,
313 ) -> CanonicalVarValues<I> {
314 // FIXME: Longterm canonical queries should deal with all placeholders
315 // created inside of the query directly instead of returning them to the
316 // caller.
317 let prev_universe = delegate.universe();
318 let universes_created_in_query = response.max_universe.index();
319 for _ in 0..universes_created_in_query {
320 delegate.create_next_universe();
321 }
322
323 let var_values = response.value.var_values();
324 assert_eq!(original_values.len(), var_values.len());
325
326 // If the query did not make progress with constraining inference variables,
327 // we would normally create a new inference variables for bound existential variables
328 // only then unify this new inference variable with the inference variable from
329 // the input.
330 //
331 // We therefore instantiate the existential variable in the canonical response with the
332 // inference variable of the input right away, which is more performant.
333 let mut opt_values = IndexVec::from_elem_n(None, response.variables.len());
334 for (original_value, result_value) in
335 iter::zip(original_values, var_values.var_values.iter())
336 {
337 match result_value.kind() {
338 ty::GenericArgKind::Type(t) => {
339 if let ty::Bound(debruijn, b) = t.kind() {
340 assert_eq!(debruijn, ty::INNERMOST);
341 opt_values[b.var()] = Some(*original_value);
342 }
343 }
344 ty::GenericArgKind::Lifetime(r) => {
345 if let ty::ReBound(debruijn, br) = r.kind() {
346 assert_eq!(debruijn, ty::INNERMOST);
347 opt_values[br.var()] = Some(*original_value);
348 }
349 }
350 ty::GenericArgKind::Const(c) => {
351 if let ty::ConstKind::Bound(debruijn, bv) = c.kind() {
352 assert_eq!(debruijn, ty::INNERMOST);
353 opt_values[bv.var()] = Some(*original_value);
354 }
355 }
356 }
357 }
358
359 let var_values = delegate.cx().mk_args_from_iter(
360 response.variables.iter().enumerate().map(|(index, info)| {
361 if info.universe() != ty::UniverseIndex::ROOT {
362 // A variable from inside a binder of the query. While ideally these shouldn't
363 // exist at all (see the FIXME at the start of this method), we have to deal with
364 // them for now.
365 delegate.instantiate_canonical_var_with_infer(info, span, |idx| {
366 prev_universe + idx.index()
367 })
368 } else if info.is_existential() {
369 // As an optimization we sometimes avoid creating a new inference variable here.
370 //
371 // All new inference variables we create start out in the current universe of the caller.
372 // This is conceptually wrong as these inference variables would be able to name
373 // more placeholders then they should be able to. However the inference variables have
374 // to "come from somewhere", so by equating them with the original values of the caller
375 // later on, we pull them down into their correct universe again.
376 if let Some(v) = opt_values[ty::BoundVar::from_usize(index)] {
377 v
378 } else {
379 delegate.instantiate_canonical_var_with_infer(info, span, |_| prev_universe)
380 }
381 } else {
382 // For placeholders which were already part of the input, we simply map this
383 // universal bound variable back the placeholder of the input.
384 original_values[info.expect_placeholder_index()]
385 }
386 }),
387 );
388
389 CanonicalVarValues { var_values }
390 }
391
392 /// Unify the `original_values` with the `var_values` returned by the canonical query..
393 ///
394 /// This assumes that this unification will always succeed. This is the case when
395 /// applying a query response right away. However, calling a canonical query, doing any
396 /// other kind of trait solving, and only then instantiating the result of the query
397 /// can cause the instantiation to fail. This is not supported and we ICE in this case.
398 ///
399 /// We always structurally instantiate aliases. Relating aliases needs to be different
400 /// depending on whether the alias is *rigid* or not. We're only really able to tell
401 /// whether an alias is rigid by using the trait solver. When instantiating a response
402 /// from the solver we assume that the solver correctly handled aliases and therefore
403 /// always relate them structurally here.
404 #[instrument(level = "trace", skip(delegate))]
405 fn unify_query_var_values(
406 delegate: &D,
407 param_env: I::ParamEnv,
408 original_values: &[I::GenericArg],
409 var_values: CanonicalVarValues<I>,
410 span: I::Span,
411 ) {
412 assert_eq!(original_values.len(), var_values.len());
413
414 for (&orig, response) in iter::zip(original_values, var_values.var_values.iter()) {
415 let goals =
416 delegate.eq_structurally_relating_aliases(param_env, orig, response, span).unwrap();
417 assert!(goals.is_empty());
418 }
419 }
420
421 fn register_region_constraints(
422 &mut self,
423 outlives: &[ty::OutlivesPredicate<I, I::GenericArg>],
424 ) {
425 for &ty::OutlivesPredicate(lhs, rhs) in outlives {
426 match lhs.kind() {
427 ty::GenericArgKind::Lifetime(lhs) => self.register_region_outlives(lhs, rhs),
428 ty::GenericArgKind::Type(lhs) => self.register_ty_outlives(lhs, rhs),
429 ty::GenericArgKind::Const(_) => panic!("const outlives: {lhs:?}: {rhs:?}"),
430 }
431 }
432 }
433
434 fn register_new_opaque_types(&mut self, opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)]) {
435 for &(key, ty) in opaque_types {
436 let prev = self.delegate.register_hidden_type_in_storage(key, ty, self.origin_span);
437 // We eagerly resolve inference variables when computing the query response.
438 // This can cause previously distinct opaque type keys to now be structurally equal.
439 //
440 // To handle this, we store any duplicate entries in a separate list to check them
441 // at the end of typeck/borrowck. We could alternatively eagerly equate the hidden
442 // types here. However, doing so is difficult as it may result in nested goals and
443 // any errors may make it harder to track the control flow for diagnostics.
444 if let Some(prev) = prev {
445 self.delegate.add_duplicate_opaque_type(key, prev, self.origin_span);
446 }
447 }
448 }
449}
450
451/// Used by proof trees to be able to recompute intermediate actions while
452/// evaluating a goal. The `var_values` not only include the bound variables
453/// of the query input, but also contain all unconstrained inference vars
454/// created while evaluating this goal.
455pub(in crate::solve) fn make_canonical_state<D, T, I>(
456 delegate: &D,
457 var_values: &[I::GenericArg],
458 max_input_universe: ty::UniverseIndex,
459 data: T,
460) -> inspect::CanonicalState<I, T>
461where
462 D: SolverDelegate<Interner = I>,
463 I: Interner,
464 T: TypeFoldable<I>,
465{
466 let var_values = CanonicalVarValues { var_values: delegate.cx().mk_args(var_values) };
467 let state = inspect::State { var_values, data };
468 let state = state.fold_with(&mut EagerResolver::new(delegate));
469 Canonicalizer::canonicalize_response(delegate, max_input_universe, &mut vec![], state)
470}
471
472// FIXME: needs to be pub to be accessed by downstream
473// `rustc_trait_selection::solve::inspect::analyse`.
474pub fn instantiate_canonical_state<D, I, T: TypeFoldable<I>>(
475 delegate: &D,
476 span: I::Span,
477 param_env: I::ParamEnv,
478 orig_values: &mut Vec<I::GenericArg>,
479 state: inspect::CanonicalState<I, T>,
480) -> T
481where
482 D: SolverDelegate<Interner = I>,
483 I: Interner,
484{
485 // In case any fresh inference variables have been created between `state`
486 // and the previous instantiation, extend `orig_values` for it.
487 orig_values.extend(
488 state.value.var_values.var_values.as_slice()[orig_values.len()..]
489 .iter()
490 .map(|&arg| delegate.fresh_var_for_kind_with_span(arg, span)),
491 );
492
493 let instantiation =
494 EvalCtxt::compute_query_response_instantiation_values(delegate, orig_values, &state, span);
495
496 let inspect::State { var_values, data } = delegate.instantiate_canonical(state, instantiation);
497
498 EvalCtxt::unify_query_var_values(delegate, param_env, orig_values, var_values, span);
499 data
500}