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::{
18    self, Relate, RelateResult, TypeRelation, VarianceDiagInfo, relate_args_invariantly,
19};
20use rustc_type_ir::{
21    self as ty, Canonical, CanonicalVarKind, CanonicalVarValues, InferCtxtLike, Interner, Region,
22    TypeFoldable, TypingMode, TypingModeEqWrapper,
23};
24use thin_vec::ThinVec;
25use tracing::instrument;
26
27use crate::delegate::SolverDelegate;
28use crate::solve::{
29    CanonicalResponse, Certainty, ExternalConstraintsData, ExternalRegionConstraints, Goal,
30    NestedNormalizationGoals, QueryInput, Response, VisibleForLeakCheck, inspect,
31};
32
33pub mod canonicalizer;
34
35trait ResponseT<I: Interner> {
36    fn var_values(&self) -> CanonicalVarValues<I>;
37}
38
39impl<I: Interner> ResponseT<I> for Response<I> {
40    fn var_values(&self) -> CanonicalVarValues<I> {
41        self.var_values
42    }
43}
44
45impl<I: Interner, T> ResponseT<I> for inspect::State<I, T> {
46    fn var_values(&self) -> CanonicalVarValues<I> {
47        self.var_values
48    }
49}
50
51/// Canonicalizes the goal remembering the original values
52/// for each bound variable.
53///
54/// This expects `goal` and `opaque_types` to be eager resolved.
55pub(super) fn canonicalize_goal<D, I>(
56    delegate: &D,
57    goal: Goal<I, I::Predicate>,
58    opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
59    typing_mode: TypingMode<I>,
60) -> (ThinVec<I::GenericArg>, I::CanonicalInput)
61where
62    D: SolverDelegate<Interner = I>,
63    I: Interner,
64{
65    let (orig_values, canonical) = Canonicalizer::canonicalize_input(
66        delegate,
67        QueryInput {
68            goal,
69            predefined_opaques_in_body: delegate.cx().mk_predefined_opaques_in_body(opaque_types),
70        },
71    );
72
73    let query_input = delegate.cx().mk_canonical_input(ty::CanonicalQueryInput {
74        canonical,
75        typing_mode: TypingModeEqWrapper(typing_mode),
76    });
77    (orig_values, query_input)
78}
79
80pub(super) fn canonicalize_response<D, I, T>(
81    delegate: &D,
82    max_input_universe: ty::UniverseIndex,
83    value: T,
84) -> ty::Canonical<I, T>
85where
86    D: SolverDelegate<Interner = I>,
87    I: Interner,
88    T: TypeFoldable<I>,
89{
90    Canonicalizer::canonicalize_response(delegate, max_input_universe, value)
91}
92
93/// After calling a canonical query, we apply the constraints returned
94/// by the query using this function.
95///
96/// This happens in three steps:
97/// - we instantiate the bound variables of the query response
98/// - we unify the `var_values` of the response with the `original_values`
99/// - we apply the `external_constraints` returned by the query, returning
100///   the `normalization_nested_goals`
101pub(super) fn instantiate_and_apply_query_response<D, I>(
102    delegate: &D,
103    param_env: I::ParamEnv,
104    original_values: &[I::GenericArg],
105    response: CanonicalResponse<I>,
106    span: I::Span,
107) -> (NestedNormalizationGoals<I>, Certainty)
108where
109    D: SolverDelegate<Interner = I>,
110    I: Interner,
111{
112    let instantiation =
113        compute_query_response_instantiation_values(delegate, &original_values, &response, span);
114
115    let Response { var_values, external_constraints, certainty } =
116        delegate.instantiate_canonical(response, instantiation);
117
118    unify_query_var_values(delegate, param_env, &original_values, var_values, span);
119
120    let ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals } =
121        &*external_constraints;
122
123    match region_constraints {
124        ExternalRegionConstraints::Old(r) => register_region_constraints(
125            delegate,
126            r.iter().map(|(c, vis)| {
127                // FIXME: We should revisit and consider removing this after *assumptions on
128                // binders* is available, like once we had done in the stabilization of
129                // `-Znext-solver=coherence`(#121848).
130                // We ignore constraints from the nested goals in leak check. This is to match with
131                // the old solver's behavior, which has separated evaluation and fulfillment, and
132                // the former doesn't consider outlives obligations from the later.
133                (*c, vis.and(VisibleForLeakCheck::No))
134            }),
135            span,
136        ),
137        ExternalRegionConstraints::NextGen(r) => {
138            delegate.register_solver_region_constraint(r.clone(), span)
139        }
140    };
141    register_new_opaque_types(delegate, opaque_types, span);
142
143    (normalization_nested_goals.clone(), certainty)
144}
145
146/// This returns the canonical variable values to instantiate the bound variables of
147/// the canonical response. This depends on the `original_values` for the
148/// bound variables.
149fn compute_query_response_instantiation_values<D, I, T>(
150    delegate: &D,
151    original_values: &[I::GenericArg],
152    response: &Canonical<I, T>,
153    span: I::Span,
154) -> CanonicalVarValues<I>
155where
156    D: SolverDelegate<Interner = I>,
157    I: Interner,
158    T: ResponseT<I>,
159{
160    // FIXME: Longterm canonical queries should deal with all placeholders
161    // created inside of the query directly instead of returning them to the
162    // caller.
163    let prev_universe = delegate.universe();
164    let universes_created_in_query = response.max_universe.index();
165    for _ in 0..universes_created_in_query {
166        let new_universe = delegate.create_next_universe();
167        if delegate.cx().assumptions_on_binders() {
168            // FIXME(-Zassumptions-on-binders): Remove this temporary workaround once
169            // opaque types no longer escape query responses with query-created placeholders.
170            // Region constraints involving query-created placeholders were handled inside
171            // the query. However, the placeholders can still escape in other response
172            // fields, such as opaque type constraints. To avoid triggering
173            // assertions, we explicitly insert empty assumptions for the
174            // recreated universes here.
175            delegate.insert_placeholder_assumptions(
176                new_universe,
177                Some(rustc_type_ir::region_constraint::Assumptions::empty()),
178            );
179        }
180    }
181
182    compute_query_response_instantiation_values_in_universe(
183        delegate,
184        original_values,
185        response,
186        span,
187        prev_universe,
188    )
189}
190
191fn compute_query_response_instantiation_values_in_universe<D, I, T>(
192    delegate: &D,
193    original_values: &[I::GenericArg],
194    response: &Canonical<I, T>,
195    span: I::Span,
196    prev_universe: ty::UniverseIndex,
197) -> CanonicalVarValues<I>
198where
199    D: SolverDelegate<Interner = I>,
200    I: Interner,
201    T: ResponseT<I>,
202{
203    let var_values = response.value.var_values();
204    {
    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());
205
206    // If the query did not make progress with constraining inference variables,
207    // we would normally create a new inference variables for bound existential variables
208    // only then unify this new inference variable with the inference variable from
209    // the input.
210    //
211    // We therefore instantiate the existential variable in the canonical response with the
212    // inference variable of the input right away, which is more performant.
213    let mut opt_values = IndexVec::from_elem_n(None, response.var_kinds.len());
214    for (original_value, result_value) in iter::zip(original_values, var_values.var_values.iter()) {
215        match result_value.kind() {
216            ty::GenericArgKind::Type(t) => {
217                // We disable the instantiation guess for inference variables
218                // and only use it for placeholders. We need to handle the
219                // `sub_root` of type inference variables which would make this
220                // more involved. They are also a lot rarer than region variables.
221                if let ty::Bound(index_kind, b) = t.kind()
222                    && !#[allow(non_exhaustive_omitted_patterns)] match response.var_kinds.get(b.var().as_usize()).unwrap()
    {
    CanonicalVarKind::Ty { .. } => true,
    _ => false,
}matches!(
223                        response.var_kinds.get(b.var().as_usize()).unwrap(),
224                        CanonicalVarKind::Ty { .. }
225                    )
226                {
227                    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));
228                    opt_values[b.var()] = Some(*original_value);
229                }
230            }
231            ty::GenericArgKind::Lifetime(r) => {
232                if let ty::ReBound(index_kind, br) = r.kind() {
233                    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));
234                    opt_values[br.var()] = Some(*original_value);
235                }
236            }
237            ty::GenericArgKind::Const(c) => {
238                if let ty::ConstKind::Bound(index_kind, bc) = c.kind() {
239                    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));
240                    opt_values[bc.var()] = Some(*original_value);
241                }
242            }
243        }
244    }
245    CanonicalVarValues::instantiate(delegate.cx(), response.var_kinds, |var_values, kind| {
246        if kind.universe() != ty::UniverseIndex::ROOT {
247            // A variable from inside a binder of the query. While ideally these shouldn't
248            // exist at all (see the FIXME at the start of this method), we have to deal with
249            // them for now.
250            delegate.instantiate_canonical_var(kind, span, &var_values, |idx| {
251                prev_universe + idx.index()
252            })
253        } else if kind.is_existential() {
254            // As an optimization we sometimes avoid creating a new inference variable here.
255            //
256            // All new inference variables we create start out in the current universe of the caller.
257            // This is conceptually wrong as these inference variables would be able to name
258            // more placeholders then they should be able to. However the inference variables have
259            // to "come from somewhere", so by equating them with the original values of the caller
260            // later on, we pull them down into their correct universe again.
261            if let Some(v) = opt_values[ty::BoundVar::from_usize(var_values.len())] {
262                v
263            } else {
264                delegate.instantiate_canonical_var(kind, span, &var_values, |_| prev_universe)
265            }
266        } else {
267            // For placeholders which were already part of the input, we simply map this
268            // universal bound variable back the placeholder of the input.
269            //
270            // For `CanonicalVarKind::PlaceholderRegion`, this differs slightly: we
271            // canonicalize all free regions from the input into placeholders. This is
272            // unlike types or consts, where only input placeholders remain placeholders
273            // in the canonical form.
274            //
275            // We can still map these back to the original input regions, as we
276            // just instantiate the canonical variable with its corresponding
277            // `original_value`.
278            //
279            // For more information on why we canonicalize all input regions as
280            // placeholders, see the comment in `Canonicalizer::fold_region`.
281            original_values[kind.expect_placeholder_index()]
282        }
283    })
284}
285
286/// Enforce that `a` is equal to `b`.
287///
288/// In normal type relating, we don't structurally relate non-rigid aliases
289/// as they can be normalized to any type. So we emit projection obligations to
290/// defer the checks. E.g. in `infcx.eq` or `infcx.relate`.
291/// But when unifying query response with original vars, we want to directly
292/// set the original vars to values in response.
293///
294/// Therefore this type relation is created to **always** structurally relate
295/// aliases, or more specifically, structurally eq everything.
296struct ResponseRelating<'infcx, Infcx, I: Interner> {
297    infcx: &'infcx Infcx,
298    span: I::Span,
299}
300
301impl<'infcx, Infcx, I> ResponseRelating<'infcx, Infcx, I>
302where
303    Infcx: InferCtxtLike<Interner = I>,
304    I: Interner,
305{
306    fn new(infcx: &'infcx Infcx, span: I::Span) -> Self {
307        ResponseRelating { infcx, span }
308    }
309}
310
311impl<Infcx, I> TypeRelation<I> for ResponseRelating<'_, Infcx, I>
312where
313    Infcx: InferCtxtLike<Interner = I>,
314    I: Interner,
315{
316    fn cx(&self) -> I {
317        self.infcx.cx()
318    }
319
320    fn relate_ty_args(
321        &mut self,
322        a_ty: I::Ty,
323        _b_ty: I::Ty,
324        _def_id: I::DefId,
325        a_args: I::GenericArgs,
326        b_args: I::GenericArgs,
327        _: impl FnOnce(I::GenericArgs) -> I::Ty,
328    ) -> RelateResult<I, I::Ty> {
329        relate_args_invariantly(self, a_args, b_args)?;
330        Ok(a_ty)
331    }
332
333    fn relate_with_variance<T: Relate<I>>(
334        &mut self,
335        _variance: ty::Variance,
336        _info: VarianceDiagInfo<I>,
337        a: T,
338        b: T,
339    ) -> RelateResult<I, T> {
340        self.relate(a, b)
341    }
342
343    {}
#[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("tys",
                                    "rustc_next_trait_solver::canonical",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_next_trait_solver/src/canonical/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(343u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::canonical"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::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: RelateResult<I, I::Ty> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if a == b { return Ok(a); }
            let infcx = self.infcx;
            let a = infcx.shallow_resolve(a);
            let b = infcx.shallow_resolve(b);
            match (a.kind(), b.kind()) {
                (ty::Infer(ty::TyVar(a_id)), ty::Infer(ty::TyVar(b_id))) => {
                    infcx.equate_ty_vids_raw(a_id, b_id);
                }
                (ty::Infer(ty::TyVar(a_vid)), _) => {
                    infcx.instantiate_ty_var_raw(a_vid, b);
                }
                (_, ty::Infer(ty::TyVar(b_vid))) => {
                    infcx.instantiate_ty_var_raw(b_vid, a);
                }
                (ty::Error(e), _) | (_, ty::Error(e)) => {
                    infcx.set_tainted_by_errors(e);
                    return Ok(Ty::new_error(infcx.cx(), e));
                }
                (ty::Infer(ty::IntVar(a_id)), ty::Infer(ty::IntVar(b_id))) =>
                    {
                    infcx.equate_int_vids_raw(a_id, b_id);
                }
                (ty::Infer(ty::IntVar(v_id)), ty::Int(v)) => {
                    infcx.instantiate_int_var_raw(v_id,
                        ty::IntVarValue::IntType(v));
                }
                (ty::Int(v), ty::Infer(ty::IntVar(v_id))) => {
                    infcx.instantiate_int_var_raw(v_id,
                        ty::IntVarValue::IntType(v));
                }
                (ty::Infer(ty::IntVar(v_id)), ty::Uint(v)) => {
                    infcx.instantiate_int_var_raw(v_id,
                        ty::IntVarValue::UintType(v));
                }
                (ty::Uint(v), ty::Infer(ty::IntVar(v_id))) => {
                    infcx.instantiate_int_var_raw(v_id,
                        ty::IntVarValue::UintType(v));
                }
                (ty::Infer(ty::FloatVar(a_id)), ty::Infer(ty::FloatVar(b_id)))
                    => {
                    infcx.equate_float_vids_raw(a_id, b_id);
                }
                (ty::Infer(ty::FloatVar(v_id)), ty::Float(v)) => {
                    infcx.instantiate_float_var_raw(v_id,
                        ty::FloatVarValue::Known(v));
                }
                (ty::Float(v), ty::Infer(ty::FloatVar(v_id))) => {
                    infcx.instantiate_float_var_raw(v_id,
                        ty::FloatVarValue::Known(v));
                }
                (_,
                    ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) |
                    ty::FreshFloatTy(_))) |
                    (ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) |
                    ty::FreshFloatTy(_)), _) => {
                    {
                        ::core::panicking::panic_fmt(format_args!("We do not expect to encounter `Fresh` variables in the new solver"));
                    }
                }
                _ => { relate::structurally_relate_tys(self, a, b)?; }
            }
            Ok(a)
        }
    }
}#[instrument(skip(self), level = "trace")]
344    fn tys(&mut self, a: I::Ty, b: I::Ty) -> RelateResult<I, I::Ty> {
345        if a == b {
346            return Ok(a);
347        }
348
349        let infcx = self.infcx;
350        let a = infcx.shallow_resolve(a);
351        let b = infcx.shallow_resolve(b);
352
353        match (a.kind(), b.kind()) {
354            (ty::Infer(ty::TyVar(a_id)), ty::Infer(ty::TyVar(b_id))) => {
355                infcx.equate_ty_vids_raw(a_id, b_id);
356            }
357
358            (ty::Infer(ty::TyVar(a_vid)), _) => {
359                infcx.instantiate_ty_var_raw(a_vid, b);
360            }
361
362            (_, ty::Infer(ty::TyVar(b_vid))) => {
363                infcx.instantiate_ty_var_raw(b_vid, a);
364            }
365
366            (ty::Error(e), _) | (_, ty::Error(e)) => {
367                infcx.set_tainted_by_errors(e);
368                return Ok(Ty::new_error(infcx.cx(), e));
369            }
370
371            // FIXME: Share the arms below with `super_combine_tys`.
372            // We can't use `super_combine_tys` here because we want to support
373            // values with escaping bound vars so that we can avoid
374            // instantiating binders when relating them.
375            //
376            // Relate integral variables to other types
377            (ty::Infer(ty::IntVar(a_id)), ty::Infer(ty::IntVar(b_id))) => {
378                infcx.equate_int_vids_raw(a_id, b_id);
379            }
380            (ty::Infer(ty::IntVar(v_id)), ty::Int(v)) => {
381                infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::IntType(v));
382            }
383            (ty::Int(v), ty::Infer(ty::IntVar(v_id))) => {
384                infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::IntType(v));
385            }
386            (ty::Infer(ty::IntVar(v_id)), ty::Uint(v)) => {
387                infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::UintType(v));
388            }
389            (ty::Uint(v), ty::Infer(ty::IntVar(v_id))) => {
390                infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::UintType(v));
391            }
392
393            // Relate floating-point variables to other types
394            (ty::Infer(ty::FloatVar(a_id)), ty::Infer(ty::FloatVar(b_id))) => {
395                infcx.equate_float_vids_raw(a_id, b_id);
396            }
397            (ty::Infer(ty::FloatVar(v_id)), ty::Float(v)) => {
398                infcx.instantiate_float_var_raw(v_id, ty::FloatVarValue::Known(v));
399            }
400            (ty::Float(v), ty::Infer(ty::FloatVar(v_id))) => {
401                infcx.instantiate_float_var_raw(v_id, ty::FloatVarValue::Known(v));
402            }
403
404            (_, ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)))
405            | (ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)), _) => {
406                panic!("We do not expect to encounter `Fresh` variables in the new solver")
407            }
408
409            _ => {
410                relate::structurally_relate_tys(self, a, b)?;
411            }
412        }
413
414        Ok(a)
415    }
416
417    {}
#[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("regions",
                                    "rustc_next_trait_solver::canonical",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_next_trait_solver/src/canonical/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(417u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::canonical"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::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: RelateResult<I, Region<I>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.infcx.equate_regions(a, b, VisibleForLeakCheck::Yes,
                self.span);
            Ok(a)
        }
    }
}#[instrument(skip(self), level = "trace")]
418    fn regions(&mut self, a: Region<I>, b: Region<I>) -> RelateResult<I, Region<I>> {
419        self.infcx.equate_regions(a, b, VisibleForLeakCheck::Yes, self.span);
420
421        Ok(a)
422    }
423
424    {}
#[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("consts",
                                    "rustc_next_trait_solver::canonical",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_next_trait_solver/src/canonical/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(424u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::canonical"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::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: RelateResult<I, I::Const> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if a == b { return Ok(a); }
            let infcx = self.infcx;
            let a = infcx.shallow_resolve_const(a);
            let b = infcx.shallow_resolve_const(b);
            match (a.kind(), b.kind()) {
                (ty::ConstKind::Infer(ty::InferConst::Var(a_vid)),
                    ty::ConstKind::Infer(ty::InferConst::Var(b_vid))) => {
                    infcx.equate_const_vids_raw(a_vid, b_vid);
                }
                (ty::ConstKind::Infer(ty::InferConst::Var(a_vid)), _) => {
                    infcx.instantiate_const_var_raw(a_vid, b);
                }
                (_, ty::ConstKind::Infer(ty::InferConst::Var(b_vid))) => {
                    infcx.instantiate_const_var_raw(b_vid, a);
                }
                _ => { relate::structurally_relate_consts(self, a, b)?; }
            }
            Ok(a)
        }
    }
}#[instrument(skip(self), level = "trace")]
425    fn consts(&mut self, a: I::Const, b: I::Const) -> RelateResult<I, I::Const> {
426        if a == b {
427            return Ok(a);
428        }
429
430        let infcx = self.infcx;
431        // Proof tree evaluation can unify inference variables in the original
432        // values without eagerly resolving them.
433        let a = infcx.shallow_resolve_const(a);
434        let b = infcx.shallow_resolve_const(b);
435        match (a.kind(), b.kind()) {
436            (
437                ty::ConstKind::Infer(ty::InferConst::Var(a_vid)),
438                ty::ConstKind::Infer(ty::InferConst::Var(b_vid)),
439            ) => {
440                infcx.equate_const_vids_raw(a_vid, b_vid);
441            }
442
443            (ty::ConstKind::Infer(ty::InferConst::Var(a_vid)), _) => {
444                infcx.instantiate_const_var_raw(a_vid, b);
445            }
446
447            (_, ty::ConstKind::Infer(ty::InferConst::Var(b_vid))) => {
448                infcx.instantiate_const_var_raw(b_vid, a);
449            }
450
451            _ => {
452                relate::structurally_relate_consts(self, a, b)?;
453            }
454        }
455
456        Ok(a)
457    }
458
459    fn binders<T>(
460        &mut self,
461        a: ty::Binder<I, T>,
462        b: ty::Binder<I, T>,
463    ) -> RelateResult<I, ty::Binder<I, T>>
464    where
465        T: Relate<I>,
466    {
467        if a == b {
468            return Ok(a);
469        }
470
471        if true {
    {
        match (&a.bound_vars(), &b.bound_vars()) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(a.bound_vars(), b.bound_vars());
472        self.relate(a.skip_binder(), b.skip_binder())?;
473
474        Ok(a)
475    }
476}
477
478/// Unify the `original_values` with the `var_values` returned by the canonical query..
479///
480/// This assumes that this unification will always succeed. This is the case when
481/// applying a query response right away. However, calling a canonical query, doing any
482/// other kind of trait solving, and only then instantiating the result of the query
483/// can cause the instantiation to fail. This is not supported and we ICE in this case.
484///
485/// We always structurally instantiate aliases. Relating aliases needs to be different
486/// depending on whether the alias is *rigid* or not. We're only really able to tell
487/// whether an alias is rigid by using the trait solver. When instantiating a response
488/// from the solver we assume that the solver correctly handled aliases and therefore
489/// always relate them structurally here.
490{}
#[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("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_next_trait_solver/src/canonical/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(490u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::canonical"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param_env");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("original_values")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("original_values");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("var_values")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("var_values");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&original_values)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_values)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::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 mut must_eq = ResponseRelating::new(&**delegate, span);
                must_eq.relate(orig, response).unwrap();
            }
        }
    }
}#[instrument(level = "trace", skip(delegate))]
491fn unify_query_var_values<D, I>(
492    delegate: &D,
493    param_env: I::ParamEnv,
494    original_values: &[I::GenericArg],
495    var_values: CanonicalVarValues<I>,
496    span: I::Span,
497) where
498    D: SolverDelegate<Interner = I>,
499    I: Interner,
500{
501    assert_eq!(original_values.len(), var_values.len());
502
503    for (&orig, response) in iter::zip(original_values, var_values.var_values.iter()) {
504        let mut must_eq = ResponseRelating::new(&**delegate, span);
505        must_eq.relate(orig, response).unwrap();
506    }
507}
508
509fn register_region_constraints<D, I>(
510    delegate: &D,
511    constraints: impl IntoIterator<Item = (ty::RegionConstraint<I>, VisibleForLeakCheck)>,
512    span: I::Span,
513) where
514    D: SolverDelegate<Interner = I>,
515    I: Interner,
516{
517    for (constraint, vis) in constraints {
518        match constraint {
519            ty::RegionConstraint::Outlives(ty::OutlivesClause(lhs, rhs)) => match lhs.kind() {
520                ty::GenericArgKind::Lifetime(lhs) => delegate.sub_regions(rhs, lhs, vis, span),
521                ty::GenericArgKind::Type(lhs) => delegate.register_ty_outlives(lhs, rhs, span),
522                ty::GenericArgKind::Const(_) => {
    ::core::panicking::panic_fmt(format_args!("const outlives: {0:?}: {1:?}",
            lhs, rhs));
}panic!("const outlives: {lhs:?}: {rhs:?}"),
523            },
524            ty::RegionConstraint::Eq(ty::RegionEqPredicate(lhs, rhs)) => {
525                delegate.equate_regions(lhs, rhs, vis, span)
526            }
527        }
528    }
529}
530
531fn register_new_opaque_types<D, I>(
532    delegate: &D,
533    opaque_types: &[(ty::OpaqueTypeKey<I>, I::Ty)],
534    span: I::Span,
535) where
536    D: SolverDelegate<Interner = I>,
537    I: Interner,
538{
539    for &(key, ty) in opaque_types {
540        let prev = delegate.register_hidden_type_in_storage(key, ty, span);
541        // We eagerly resolve inference variables when computing the query response.
542        // This can cause previously distinct opaque type keys to now be structurally equal.
543        //
544        // To handle this, we store any duplicate entries in a separate list to check them
545        // at the end of typeck/borrowck. We could alternatively eagerly equate the hidden
546        // types here. However, doing so is difficult as it may result in nested goals and
547        // any errors may make it harder to track the control flow for diagnostics.
548        if let Some(prev) = prev {
549            delegate.add_duplicate_opaque_type(key, prev, span);
550        }
551    }
552}
553
554/// Used by proof trees to be able to recompute intermediate actions while
555/// evaluating a goal. The `var_values` not only include the bound variables
556/// of the query input, but also contain all unconstrained inference vars
557/// created while evaluating this goal.
558pub fn make_canonical_state<D, I, T>(
559    delegate: &D,
560    var_values: &[I::GenericArg],
561    max_input_universe: ty::UniverseIndex,
562    data: T,
563) -> inspect::CanonicalState<I, T>
564where
565    D: SolverDelegate<Interner = I>,
566    I: Interner,
567    T: TypeFoldable<I>,
568{
569    let var_values = CanonicalVarValues { var_values: delegate.cx().mk_args(var_values) };
570    let state = inspect::State { var_values, data };
571    let state = delegate.deeply_resolve_via_unification_table(state);
572    Canonicalizer::canonicalize_response(delegate, max_input_universe, state)
573}
574
575// FIXME: needs to be pub to be accessed by downstream
576// `rustc_trait_selection::solve::inspect::analyse`.
577pub fn instantiate_canonical_state<D, I, T>(
578    delegate: &D,
579    span: I::Span,
580    param_env: I::ParamEnv,
581    prev_universe: ty::UniverseIndex,
582    orig_values: &mut ThinVec<I::GenericArg>,
583    state: inspect::CanonicalState<I, T>,
584) -> T
585where
586    D: SolverDelegate<Interner = I>,
587    I: Interner,
588    T: TypeFoldable<I>,
589{
590    // In case any fresh inference variables have been created between `state`
591    // and the previous instantiation, extend `orig_values` for it.
592    let max_universe = prev_universe + state.max_universe.index();
593    while delegate.universe() < max_universe {
594        delegate.create_next_universe();
595    }
596    orig_values.extend(
597        state.value.var_values.var_values.as_slice()[orig_values.len()..]
598            .iter()
599            .map(|&arg| delegate.fresh_var_for_kind(arg, span, max_universe)),
600    );
601
602    let instantiation = compute_query_response_instantiation_values_in_universe(
603        delegate,
604        orig_values,
605        &state,
606        span,
607        prev_universe,
608    );
609
610    let inspect::State { var_values, data } = delegate.instantiate_canonical(state, instantiation);
611
612    unify_query_var_values(delegate, param_env, orig_values, var_values, span);
613    data
614}
615
616pub fn response_no_constraints_raw<I: Interner>(
617    cx: I,
618    max_universe: ty::UniverseIndex,
619    var_kinds: I::CanonicalVarKinds,
620    certainty: Certainty,
621) -> CanonicalResponse<I> {
622    ty::Canonical {
623        max_universe,
624        var_kinds,
625        value: Response {
626            var_values: ty::CanonicalVarValues::make_identity(cx, var_kinds),
627            // FIXME: maybe we should store the "no response" version in cx, like
628            // we do for cx.types and stuff.
629            external_constraints: cx.mk_external_constraints(ExternalConstraintsData::new(cx)),
630            certainty,
631        },
632    }
633}