Skip to main content

rustc_next_trait_solver/canonical/
mod.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 canonicalizer::Canonicalizer;
15use rustc_index::IndexVec;
16use rustc_type_ir::inherent::*;
17use rustc_type_ir::relate::solver_relating::RelateExt;
18use rustc_type_ir::{
19    self as ty, Canonical, CanonicalVarKind, CanonicalVarValues, InferCtxtLike, Interner,
20    TypeFoldable, TypingMode, TypingModeEqWrapper,
21};
22use tracing::instrument;
23
24use crate::delegate::SolverDelegate;
25use crate::resolve::eager_resolve_vars;
26use crate::solve::{
27    CanonicalInput, CanonicalResponse, Certainty, ExternalConstraintsData,
28    ExternalRegionConstraints, Goal, NestedNormalizationGoals, QueryInput, Response,
29    VisibleForLeakCheck, inspect,
30};
31
32pub mod canonicalizer;
33
34trait ResponseT<I: Interner> {
35    fn var_values(&self) -> CanonicalVarValues<I>;
36}
37
38impl<I: Interner> ResponseT<I> for Response<I> {
39    fn var_values(&self) -> CanonicalVarValues<I> {
40        self.var_values
41    }
42}
43
44impl<I: Interner, T> ResponseT<I> for inspect::State<I, T> {
45    fn var_values(&self) -> CanonicalVarValues<I> {
46        self.var_values
47    }
48}
49
50/// 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
61    D: SolverDelegate<Interner = I>,
62    I: Interner,
63{
64    let (orig_values, canonical) = Canonicalizer::canonicalize_input(
65        delegate,
66        QueryInput {
67            goal,
68            predefined_opaques_in_body: delegate.cx().mk_predefined_opaques_in_body(opaque_types),
69        },
70    );
71
72    let query_input =
73        ty::CanonicalQueryInput { canonical, typing_mode: TypingModeEqWrapper(typing_mode) };
74    (orig_values, query_input)
75}
76
77pub(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
83    D: SolverDelegate<Interner = I>,
84    I: Interner,
85    T: TypeFoldable<I>,
86{
87    Canonicalizer::canonicalize_response(delegate, max_input_universe, value)
88}
89
90/// 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
106    D: SolverDelegate<Interner = I>,
107    I: Interner,
108{
109    let instantiation =
110        compute_query_response_instantiation_values(delegate, &original_values, &response, span);
111
112    let Response { var_values, external_constraints, certainty } =
113        delegate.instantiate_canonical(response, instantiation);
114
115    unify_query_var_values(delegate, param_env, &original_values, var_values, span);
116
117    let ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals } =
118        &*external_constraints;
119
120    match region_constraints {
121        ExternalRegionConstraints::Old(r) => register_region_constraints(
122            delegate,
123            r.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            }),
132            span,
133        ),
134        ExternalRegionConstraints::NextGen(r) => {
135            delegate.register_solver_region_constraint(r.clone())
136        }
137    };
138    register_new_opaque_types(delegate, opaque_types, span);
139
140    (normalization_nested_goals.clone(), certainty)
141}
142
143/// 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
153    D: 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.
160    let prev_universe = delegate.universe();
161    let universes_created_in_query = response.max_universe.index();
162    for _ in 0..universes_created_in_query {
163        delegate.create_next_universe();
164    }
165
166    let 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());
168
169    // 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.
176    let mut opt_values = IndexVec::from_elem_n(None, response.var_kinds.len());
177    for (original_value, result_value) in iter::zip(original_values, var_values.var_values.iter()) {
178        match 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.
184                if 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                {
190                    if !#[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) => {
195                if let ty::ReBound(index_kind, br) = r.kind() {
196                    if !#[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) => {
201                if let ty::ConstKind::Bound(index_kind, bc) = c.kind() {
202                    if !#[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    }
208    CanonicalVarValues::instantiate(delegate.cx(), response.var_kinds, |var_values, kind| {
209        if 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.
213            delegate.instantiate_canonical_var(kind, span, &var_values, |idx| {
214                prev_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.
224            if let Some(v) = opt_values[ty::BoundVar::from_usize(var_values.len())] {
225                v
226            } else {
227                delegate.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`.
244            original_values[kind.expect_placeholder_index()]
245        }
246    })
247}
248
249/// 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(&param_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
269    D: SolverDelegate<Interner = I>,
270    I: Interner,
271{
272    assert_eq!(original_values.len(), var_values.len());
273
274    for (&orig, response) in iter::zip(original_values, var_values.var_values.iter()) {
275        let goals =
276            delegate.eq_structurally_relating_aliases(param_env, orig, response, span).unwrap();
277        assert!(goals.is_empty());
278    }
279}
280
281fn register_region_constraints<D, I>(
282    delegate: &D,
283    constraints: impl IntoIterator<Item = (ty::RegionConstraint<I>, VisibleForLeakCheck)>,
284    span: I::Span,
285) where
286    D: SolverDelegate<Interner = I>,
287    I: Interner,
288{
289    for (constraint, vis) in constraints {
290        match 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}
302
303fn register_new_opaque_types<D, I>(
304    delegate: &D,
305    opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
306    span: I::Span,
307) where
308    D: SolverDelegate<Interner = I>,
309    I: Interner,
310{
311    for &(key, ty) in opaque_types {
312        let 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.
320        if let Some(prev) = prev {
321            delegate.add_duplicate_opaque_type(key, prev, span);
322        }
323    }
324}
325
326/// 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
337    D: SolverDelegate<Interner = I>,
338    I: Interner,
339    T: TypeFoldable<I>,
340{
341    let var_values = CanonicalVarValues { var_values: delegate.cx().mk_args(var_values) };
342    let state = inspect::State { var_values, data };
343    let state = eager_resolve_vars(&**delegate, state);
344    Canonicalizer::canonicalize_response(delegate, max_input_universe, state)
345}
346
347// 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
357    D: 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.
363    orig_values.extend(
364        state.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    );
368
369    let instantiation =
370        compute_query_response_instantiation_values(delegate, orig_values, &state, span);
371
372    let inspect::State { var_values, data } = delegate.instantiate_canonical(state, instantiation);
373
374    unify_query_var_values(delegate, param_env, orig_values, var_values, span);
375    data
376}
377
378pub 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 {
385        max_universe,
386        var_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.
391            external_constraints: cx.mk_external_constraints(ExternalConstraintsData::new(cx)),
392            certainty,
393        },
394    }
395}