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, TypingModeEqWrapper,
21};
22use tracing::instrument;
23
24use crate::delegate::SolverDelegate;
25use crate::resolve::eager_resolve_vars;
26use crate::solve::{
27    CanonicalInput, CanonicalResponse, Certainty, ExternalConstraintsData, Goal,
28    NestedNormalizationGoals, QueryInput, Response, inspect,
29};
30
31pub mod canonicalizer;
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
49/// 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
59    D: SolverDelegate<Interner = I>,
60    I: Interner,
61{
62    let (orig_values, canonical) = Canonicalizer::canonicalize_input(
63        delegate,
64        QueryInput {
65            goal,
66            predefined_opaques_in_body: delegate.cx().mk_predefined_opaques_in_body(opaque_types),
67        },
68    );
69    let query_input = ty::CanonicalQueryInput {
70        canonical,
71        typing_mode: TypingModeEqWrapper(delegate.typing_mode()),
72    };
73    (orig_values, query_input)
74}
75
76pub(super) fn canonicalize_response<D, I, T>(
77    delegate: &D,
78    max_input_universe: ty::UniverseIndex,
79    value: T,
80) -> ty::Canonical<I, T>
81where
82    D: SolverDelegate<Interner = I>,
83    I: Interner,
84    T: TypeFoldable<I>,
85{
86    Canonicalizer::canonicalize_response(delegate, max_input_universe, value)
87}
88
89/// After calling a canonical query, we apply the constraints returned
90/// by the query using this function.
91///
92/// This happens in three steps:
93/// - we instantiate the bound variables of the query response
94/// - we unify the `var_values` of the response with the `original_values`
95/// - we apply the `external_constraints` returned by the query, returning
96///   the `normalization_nested_goals`
97pub(super) fn instantiate_and_apply_query_response<D, I>(
98    delegate: &D,
99    param_env: I::ParamEnv,
100    original_values: &[I::GenericArg],
101    response: CanonicalResponse<I>,
102    span: I::Span,
103) -> (NestedNormalizationGoals<I>, Certainty)
104where
105    D: SolverDelegate<Interner = I>,
106    I: Interner,
107{
108    let instantiation =
109        compute_query_response_instantiation_values(delegate, &original_values, &response, span);
110
111    let Response { var_values, external_constraints, certainty } =
112        delegate.instantiate_canonical(response, instantiation);
113
114    unify_query_var_values(delegate, param_env, &original_values, var_values, span);
115
116    let ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals } =
117        &*external_constraints;
118
119    register_region_constraints(delegate, region_constraints, span);
120    register_new_opaque_types(delegate, opaque_types, span);
121
122    (normalization_nested_goals.clone(), certainty)
123}
124
125/// This returns the canonical variable values to instantiate the bound variables of
126/// the canonical response. This depends on the `original_values` for the
127/// bound variables.
128fn compute_query_response_instantiation_values<D, I, T>(
129    delegate: &D,
130    original_values: &[I::GenericArg],
131    response: &Canonical<I, T>,
132    span: I::Span,
133) -> CanonicalVarValues<I>
134where
135    D: SolverDelegate<Interner = I>,
136    I: Interner,
137    T: ResponseT<I>,
138{
139    // FIXME: Longterm canonical queries should deal with all placeholders
140    // created inside of the query directly instead of returning them to the
141    // caller.
142    let prev_universe = delegate.universe();
143    let universes_created_in_query = response.max_universe.index();
144    for _ in 0..universes_created_in_query {
145        delegate.create_next_universe();
146    }
147
148    let var_values = response.value.var_values();
149    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());
150
151    // If the query did not make progress with constraining inference variables,
152    // we would normally create a new inference variables for bound existential variables
153    // only then unify this new inference variable with the inference variable from
154    // the input.
155    //
156    // We therefore instantiate the existential variable in the canonical response with the
157    // inference variable of the input right away, which is more performant.
158    let mut opt_values = IndexVec::from_elem_n(None, response.var_kinds.len());
159    for (original_value, result_value) in iter::zip(original_values, var_values.var_values.iter()) {
160        match result_value.kind() {
161            ty::GenericArgKind::Type(t) => {
162                // We disable the instantiation guess for inference variables
163                // and only use it for placeholders. We need to handle the
164                // `sub_root` of type inference variables which would make this
165                // more involved. They are also a lot rarer than region variables.
166                if let ty::Bound(index_kind, b) = t.kind()
167                    && !#[allow(non_exhaustive_omitted_patterns)] match response.var_kinds.get(b.var().as_usize()).unwrap()
    {
    CanonicalVarKind::Ty { .. } => true,
    _ => false,
}matches!(
168                        response.var_kinds.get(b.var().as_usize()).unwrap(),
169                        CanonicalVarKind::Ty { .. }
170                    )
171                {
172                    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));
173                    opt_values[b.var()] = Some(*original_value);
174                }
175            }
176            ty::GenericArgKind::Lifetime(r) => {
177                if let ty::ReBound(index_kind, br) = r.kind() {
178                    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));
179                    opt_values[br.var()] = Some(*original_value);
180                }
181            }
182            ty::GenericArgKind::Const(c) => {
183                if let ty::ConstKind::Bound(index_kind, bc) = c.kind() {
184                    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));
185                    opt_values[bc.var()] = Some(*original_value);
186                }
187            }
188        }
189    }
190    CanonicalVarValues::instantiate(delegate.cx(), response.var_kinds, |var_values, kind| {
191        if kind.universe() != ty::UniverseIndex::ROOT {
192            // A variable from inside a binder of the query. While ideally these shouldn't
193            // exist at all (see the FIXME at the start of this method), we have to deal with
194            // them for now.
195            delegate.instantiate_canonical_var(kind, span, &var_values, |idx| {
196                prev_universe + idx.index()
197            })
198        } else if kind.is_existential() {
199            // As an optimization we sometimes avoid creating a new inference variable here.
200            //
201            // All new inference variables we create start out in the current universe of the caller.
202            // This is conceptually wrong as these inference variables would be able to name
203            // more placeholders then they should be able to. However the inference variables have
204            // to "come from somewhere", so by equating them with the original values of the caller
205            // later on, we pull them down into their correct universe again.
206            if let Some(v) = opt_values[ty::BoundVar::from_usize(var_values.len())] {
207                v
208            } else {
209                delegate.instantiate_canonical_var(kind, span, &var_values, |_| prev_universe)
210            }
211        } else {
212            // For placeholders which were already part of the input, we simply map this
213            // universal bound variable back the placeholder of the input.
214            original_values[kind.expect_placeholder_index()]
215        }
216    })
217}
218
219/// Unify the `original_values` with the `var_values` returned by the canonical query..
220///
221/// This assumes that this unification will always succeed. This is the case when
222/// applying a query response right away. However, calling a canonical query, doing any
223/// other kind of trait solving, and only then instantiating the result of the query
224/// can cause the instantiation to fail. This is not supported and we ICE in this case.
225///
226/// We always structurally instantiate aliases. Relating aliases needs to be different
227/// depending on whether the alias is *rigid* or not. We're only really able to tell
228/// whether an alias is rigid by using the trait solver. When instantiating a response
229/// from the solver we assume that the solver correctly handled aliases and therefore
230/// always relate them structurally here.
231#[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(231u32),
                                    ::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))]
232fn unify_query_var_values<D, I>(
233    delegate: &D,
234    param_env: I::ParamEnv,
235    original_values: &[I::GenericArg],
236    var_values: CanonicalVarValues<I>,
237    span: I::Span,
238) where
239    D: SolverDelegate<Interner = I>,
240    I: Interner,
241{
242    assert_eq!(original_values.len(), var_values.len());
243
244    for (&orig, response) in iter::zip(original_values, var_values.var_values.iter()) {
245        let goals =
246            delegate.eq_structurally_relating_aliases(param_env, orig, response, span).unwrap();
247        assert!(goals.is_empty());
248    }
249}
250
251fn register_region_constraints<D, I>(
252    delegate: &D,
253    outlives: &[ty::OutlivesPredicate<I, I::GenericArg>],
254    span: I::Span,
255) where
256    D: SolverDelegate<Interner = I>,
257    I: Interner,
258{
259    for &ty::OutlivesPredicate(lhs, rhs) in outlives {
260        match lhs.kind() {
261            ty::GenericArgKind::Lifetime(lhs) => delegate.sub_regions(rhs, lhs, span),
262            ty::GenericArgKind::Type(lhs) => delegate.register_ty_outlives(lhs, rhs, span),
263            ty::GenericArgKind::Const(_) => {
    ::core::panicking::panic_fmt(format_args!("const outlives: {0:?}: {1:?}",
            lhs, rhs));
}panic!("const outlives: {lhs:?}: {rhs:?}"),
264        }
265    }
266}
267
268fn register_new_opaque_types<D, I>(
269    delegate: &D,
270    opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
271    span: I::Span,
272) where
273    D: SolverDelegate<Interner = I>,
274    I: Interner,
275{
276    for &(key, ty) in opaque_types {
277        let prev = delegate.register_hidden_type_in_storage(key, ty, span);
278        // We eagerly resolve inference variables when computing the query response.
279        // This can cause previously distinct opaque type keys to now be structurally equal.
280        //
281        // To handle this, we store any duplicate entries in a separate list to check them
282        // at the end of typeck/borrowck. We could alternatively eagerly equate the hidden
283        // types here. However, doing so is difficult as it may result in nested goals and
284        // any errors may make it harder to track the control flow for diagnostics.
285        if let Some(prev) = prev {
286            delegate.add_duplicate_opaque_type(key, prev, span);
287        }
288    }
289}
290
291/// Used by proof trees to be able to recompute intermediate actions while
292/// evaluating a goal. The `var_values` not only include the bound variables
293/// of the query input, but also contain all unconstrained inference vars
294/// created while evaluating this goal.
295pub fn make_canonical_state<D, I, T>(
296    delegate: &D,
297    var_values: &[I::GenericArg],
298    max_input_universe: ty::UniverseIndex,
299    data: T,
300) -> inspect::CanonicalState<I, T>
301where
302    D: SolverDelegate<Interner = I>,
303    I: Interner,
304    T: TypeFoldable<I>,
305{
306    let var_values = CanonicalVarValues { var_values: delegate.cx().mk_args(var_values) };
307    let state = inspect::State { var_values, data };
308    let state = eager_resolve_vars(delegate, state);
309    Canonicalizer::canonicalize_response(delegate, max_input_universe, state)
310}
311
312// FIXME: needs to be pub to be accessed by downstream
313// `rustc_trait_selection::solve::inspect::analyse`.
314pub fn instantiate_canonical_state<D, I, T>(
315    delegate: &D,
316    span: I::Span,
317    param_env: I::ParamEnv,
318    orig_values: &mut Vec<I::GenericArg>,
319    state: inspect::CanonicalState<I, T>,
320) -> T
321where
322    D: SolverDelegate<Interner = I>,
323    I: Interner,
324    T: TypeFoldable<I>,
325{
326    // In case any fresh inference variables have been created between `state`
327    // and the previous instantiation, extend `orig_values` for it.
328    orig_values.extend(
329        state.value.var_values.var_values.as_slice()[orig_values.len()..]
330            .iter()
331            .map(|&arg| delegate.fresh_var_for_kind_with_span(arg, span)),
332    );
333
334    let instantiation =
335        compute_query_response_instantiation_values(delegate, orig_values, &state, span);
336
337    let inspect::State { var_values, data } = delegate.instantiate_canonical(state, instantiation);
338
339    unify_query_var_values(delegate, param_env, orig_values, var_values, span);
340    data
341}
342
343pub fn response_no_constraints_raw<I: Interner>(
344    cx: I,
345    max_universe: ty::UniverseIndex,
346    var_kinds: I::CanonicalVarKinds,
347    certainty: Certainty,
348) -> CanonicalResponse<I> {
349    ty::Canonical {
350        max_universe,
351        var_kinds,
352        value: Response {
353            var_values: ty::CanonicalVarValues::make_identity(cx, var_kinds),
354            // FIXME: maybe we should store the "no response" version in cx, like
355            // we do for cx.types and stuff.
356            external_constraints: cx.mk_external_constraints(ExternalConstraintsData::default()),
357            certainty,
358        },
359    }
360}