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