Skip to main content

rustc_next_trait_solver/solve/
mod.rs

1//! The next-generation trait solver, currently still WIP.
2//!
3//! As a user of rust, you can use `-Znext-solver` to enable the new trait solver.
4//!
5//! As a developer of rustc, you shouldn't be using the new trait
6//! solver without asking the trait-system-refactor-initiative, but it can
7//! be enabled with `InferCtxtBuilder::with_next_trait_solver`. This will
8//! ensure that trait solving using that inference context will be routed
9//! to the new trait solver.
10//!
11//! For a high-level overview of how this solver works, check out the relevant
12//! section of the rustc-dev-guide.
13
14mod assembly;
15mod effect_goals;
16mod eval_ctxt;
17pub mod inspect;
18mod normalizes_to;
19mod project_goals;
20mod search_graph;
21mod trait_goals;
22
23use derive_where::derive_where;
24use rustc_type_ir::inherent::*;
25pub use rustc_type_ir::solve::*;
26use rustc_type_ir::{self as ty, Interner, Region, TypeVisitableExt};
27use tracing::instrument;
28
29pub use self::eval_ctxt::{
30    EvalCtxt, GenerateProofTree, SolverDelegateEvalExt,
31    evaluate_root_goal_for_proof_tree_raw_provider, fast_path,
32};
33use crate::delegate::SolverDelegate;
34use crate::solve::assembly::Candidate;
35
36/// How many fixpoint iterations we should attempt inside of the solver before bailing
37/// with overflow.
38///
39/// We previously used  `cx.recursion_limit().0.checked_ilog2().unwrap_or(0)` for this.
40/// However, it feels unlikely that uncreasing the recursion limit by a power of two
41/// to get one more iteration is ever useful or desirable. We now instead used a constant
42/// here. If there ever ends up some use-cases where a bigger number of fixpoint iterations
43/// is required, we can add a new attribute for that or revert this to be dependent on the
44/// recursion limit again. However, this feels very unlikely.
45const FIXPOINT_STEP_LIMIT: usize = 8;
46
47/// Whether evaluating this goal ended up changing the
48/// inference state.
49#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for HasChanged {
    #[inline]
    fn eq(&self, other: &HasChanged) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for HasChanged {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for HasChanged {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { HasChanged::Yes => "Yes", HasChanged::No => "No", })
    }
}Debug, #[automatically_derived]
impl ::core::hash::Hash for HasChanged {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash, #[automatically_derived]
impl ::core::clone::Clone for HasChanged {
    #[inline]
    fn clone(&self) -> HasChanged { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for HasChanged { }Copy)]
50pub enum HasChanged {
51    Yes,
52    No,
53}
54
55// FIXME(trait-system-refactor-initiative#117): we don't detect whether a response
56// ended up pulling down any universes.
57fn has_no_inference_or_external_constraints<I: Interner>(
58    response: ty::Canonical<I, Response<I>>,
59) -> bool {
60    let ExternalConstraintsData {
61        ref region_constraints,
62        ref opaque_types,
63        ref normalization_nested_goals,
64    } = *response.value.external_constraints;
65    response.value.var_values.is_identity()
66        && region_constraints.is_empty()
67        && opaque_types.is_empty()
68        && normalization_nested_goals.is_empty()
69}
70
71fn has_only_region_constraints<I: Interner>(response: ty::Canonical<I, Response<I>>) -> bool {
72    let ExternalConstraintsData {
73        region_constraints: _,
74        ref opaque_types,
75        ref normalization_nested_goals,
76    } = *response.value.external_constraints;
77    response.value.var_values.is_identity_modulo_regions()
78        && opaque_types.is_empty()
79        && normalization_nested_goals.is_empty()
80}
81
82impl<'a, D, I> EvalCtxt<'a, D>
83where
84    D: SolverDelegate<Interner = I>,
85    I: Interner,
86{
87    #[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("compute_type_outlives_goal",
                                    "rustc_next_trait_solver::solve", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(87u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        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(&goal)
                                                            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: QueryResultOrRerunNonErased<I> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::OutlivesPredicate(ty, lt) = goal.predicate;
            let ty =
                self.normalize(GoalSource::Misc, goal.param_env,
                        ty::Unnormalized::new_wip(ty))?;
            if self.cx().assumptions_on_binders() {
                let constraint = self.destructure_type_outlives(ty, lt);
                self.register_solver_region_constraint(constraint);
            } else { self.register_ty_outlives(ty, lt); }
            if ty.has_non_region_infer() || ty.has_non_rigid_aliases() {
                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
            } else {
                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
88    fn compute_type_outlives_goal(
89        &mut self,
90        goal: Goal<I, ty::OutlivesPredicate<I, I::Ty>>,
91    ) -> QueryResultOrRerunNonErased<I> {
92        let ty::OutlivesPredicate(ty, lt) = goal.predicate;
93        let ty = self.normalize(GoalSource::Misc, goal.param_env, ty::Unnormalized::new_wip(ty))?;
94
95        if self.cx().assumptions_on_binders() {
96            let constraint = self.destructure_type_outlives(ty, lt);
97            self.register_solver_region_constraint(constraint);
98        } else {
99            self.register_ty_outlives(ty, lt);
100        }
101
102        // The normalized type can still contain non-rigid higher ranked aliases if their
103        // normalization ends up with ambiguity. Or we have non-rigid aliases inside rigid ones.
104        // Infer vars may be resolved to types/consts containing non-rigid aliases later.
105        // Thus we should stall this goal to avoid registering non-rigid type outlives into
106        // the outer infcx.
107        if ty.has_non_region_infer() || ty.has_non_rigid_aliases() {
108            self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
109        } else {
110            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
111        }
112    }
113
114    #[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("compute_region_outlives_goal",
                                    "rustc_next_trait_solver::solve", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(114u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        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(&goal)
                                                            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: QueryResultOrRerunNonErased<I> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::OutlivesPredicate(a, b) = goal.predicate;
            if self.cx().assumptions_on_binders() {
                let constraint =
                    rustc_type_ir::region_constraint::RegionConstraint::RegionOutlives(a,
                        b);
                self.register_solver_region_constraint(constraint);
            } else {
                self.register_region_outlives(a, b, VisibleForLeakCheck::Yes);
            }
            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
        }
    }
}#[instrument(level = "trace", skip(self))]
115    fn compute_region_outlives_goal(
116        &mut self,
117        goal: Goal<I, ty::OutlivesPredicate<I, Region<I>>>,
118    ) -> QueryResultOrRerunNonErased<I> {
119        let ty::OutlivesPredicate(a, b) = goal.predicate;
120
121        if self.cx().assumptions_on_binders() {
122            let constraint =
123                rustc_type_ir::region_constraint::RegionConstraint::RegionOutlives(a, b);
124            self.register_solver_region_constraint(constraint);
125        } else {
126            self.register_region_outlives(a, b, VisibleForLeakCheck::Yes);
127        }
128
129        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
130    }
131
132    #[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("compute_coerce_goal",
                                    "rustc_next_trait_solver::solve", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(132u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        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(&goal)
                                                            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: QueryResultOrRerunNonErased<I> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.compute_subtype_goal(Goal {
                    param_env: goal.param_env,
                    predicate: ty::SubtypePredicate {
                        a_is_expected: false,
                        a: goal.predicate.a,
                        b: goal.predicate.b,
                    },
                })
        }
    }
}#[instrument(level = "trace", skip(self))]
133    fn compute_coerce_goal(
134        &mut self,
135        goal: Goal<I, ty::CoercePredicate<I>>,
136    ) -> QueryResultOrRerunNonErased<I> {
137        self.compute_subtype_goal(Goal {
138            param_env: goal.param_env,
139            predicate: ty::SubtypePredicate {
140                a_is_expected: false,
141                a: goal.predicate.a,
142                b: goal.predicate.b,
143            },
144        })
145    }
146
147    #[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("compute_subtype_goal",
                                    "rustc_next_trait_solver::solve", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(147u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        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(&goal)
                                                            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: QueryResultOrRerunNonErased<I> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match (goal.predicate.a.kind(), goal.predicate.b.kind()) {
                (ty::Infer(ty::TyVar(a_vid)), ty::Infer(ty::TyVar(b_vid))) =>
                    {
                    self.sub_unify_ty_vids_raw(a_vid, b_vid);
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                }
                _ => {
                    self.sub(goal.param_env, goal.predicate.a,
                            goal.predicate.b)?;
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                }
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
148    fn compute_subtype_goal(
149        &mut self,
150        goal: Goal<I, ty::SubtypePredicate<I>>,
151    ) -> QueryResultOrRerunNonErased<I> {
152        match (goal.predicate.a.kind(), goal.predicate.b.kind()) {
153            (ty::Infer(ty::TyVar(a_vid)), ty::Infer(ty::TyVar(b_vid))) => {
154                self.sub_unify_ty_vids_raw(a_vid, b_vid);
155                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
156            }
157            _ => {
158                self.sub(goal.param_env, goal.predicate.a, goal.predicate.b)?;
159                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
160            }
161        }
162    }
163
164    fn compute_dyn_compatible_goal(
165        &mut self,
166        trait_def_id: I::TraitId,
167    ) -> QueryResultOrRerunNonErased<I> {
168        if self.cx().trait_is_dyn_compatible(trait_def_id) {
169            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
170        } else {
171            Err(NoSolution.into())
172        }
173    }
174
175    #[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("compute_well_formed_goal",
                                    "rustc_next_trait_solver::solve", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(175u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        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(&goal)
                                                            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: QueryResultOrRerunNonErased<I> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match self.well_formed_goals(goal.param_env, goal.predicate) {
                Some(goals) => {
                    self.add_goals(GoalSource::Misc, goals)?;
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                }
                None =>
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS),
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
176    fn compute_well_formed_goal(
177        &mut self,
178        goal: Goal<I, I::Term>,
179    ) -> QueryResultOrRerunNonErased<I> {
180        match self.well_formed_goals(goal.param_env, goal.predicate) {
181            Some(goals) => {
182                self.add_goals(GoalSource::Misc, goals)?;
183                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
184            }
185            None => self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS),
186        }
187    }
188
189    fn compute_unstable_feature_goal(
190        &mut self,
191        param_env: <I as Interner>::ParamEnv,
192        symbol: <I as Interner>::Symbol,
193    ) -> QueryResultOrRerunNonErased<I> {
194        if self.may_use_unstable_feature(param_env, symbol)? {
195            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
196        } else {
197            self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
198        }
199    }
200
201    #[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("compute_const_evaluatable_goal",
                                    "rustc_next_trait_solver::solve", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(201u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::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("ct")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ct");
                                                        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(&ct)
                                                            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: QueryResultOrRerunNonErased<I> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match ct.kind() {
                ty::ConstKind::Alias(ty::IsRigid::Yes, _) |
                    ty::ConstKind::Placeholder(_) | ty::ConstKind::Value(_) |
                    ty::ConstKind::Error(_) => {
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                }
                ty::ConstKind::Infer(_) => {
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                }
                ty::ConstKind::Alias(ty::IsRigid::No, alias_const) => {
                    if let Some(_normalized) =
                            self.evaluate_const(param_env, alias_const)? {
                        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                    } else {
                        self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                    }
                }
                ty::ConstKind::Param(_) | ty::ConstKind::Bound(_, _) |
                    ty::ConstKind::Expr(_) => {
                    {
                        ::core::panicking::panic_fmt(format_args!("unexpected const kind: {0:?}",
                                ct));
                    }
                }
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
202    fn compute_const_evaluatable_goal(
203        &mut self,
204        Goal { param_env, predicate: ct }: Goal<I, I::Const>,
205    ) -> QueryResultOrRerunNonErased<I> {
206        match ct.kind() {
207            ty::ConstKind::Alias(ty::IsRigid::Yes, _)
208            | ty::ConstKind::Placeholder(_)
209            | ty::ConstKind::Value(_)
210            | ty::ConstKind::Error(_) => {
211                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
212            }
213
214            ty::ConstKind::Infer(_) => {
215                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
216            }
217
218            ty::ConstKind::Alias(ty::IsRigid::No, alias_const) => {
219                // We never return `NoSolution` here as `evaluate_const` emits an
220                // error itself when failing to evaluate, so emitting an additional fulfillment
221                // error in that case is unnecessary noise. This may change in the future once
222                // evaluation failures are allowed to impact selection, e.g. generic const
223                // expressions in impl headers or `where`-clauses.
224
225                // FIXME(generic_const_exprs): Implement handling for generic
226                // const expressions here.
227                if let Some(_normalized) = self.evaluate_const(param_env, alias_const)? {
228                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
229                } else {
230                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
231                }
232            }
233
234            // We can freely ICE here as:
235            // - `Param` gets replaced with a placeholder during canonicalization
236            // - `Bound` cannot exist as we don't have a binder around the self Type
237            // - `Expr` is part of `feature(generic_const_exprs)` and is not implemented yet
238            ty::ConstKind::Param(_) | ty::ConstKind::Bound(_, _) | ty::ConstKind::Expr(_) => {
239                panic!("unexpected const kind: {:?}", ct)
240            }
241        }
242    }
243
244    x;#[instrument(level = "trace", skip(self), ret)]
245    fn compute_const_arg_has_type_goal(
246        &mut self,
247        goal: Goal<I, (I::Const, I::Ty)>,
248    ) -> QueryResultOrRerunNonErased<I> {
249        let (ct, ty) = goal.predicate;
250        let ct = self.structurally_normalize_const(goal.param_env, ct)?;
251
252        let ct_ty = match ct.kind() {
253            ty::ConstKind::Infer(_) => {
254                return self
255                    .evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
256                    .map_err(Into::into);
257            }
258            ty::ConstKind::Error(_) => {
259                return self
260                    .evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
261                    .map_err(Into::into);
262            }
263            ty::ConstKind::Alias(ty::IsRigid::Yes, alias_const) => {
264                alias_const.type_of(self.cx()).skip_norm_wip()
265            }
266            ty::ConstKind::Alias(ty::IsRigid::No, _) => unimplemented!(
267                "non-rigid unevaluated constant for compute_const_arg_has_type_goal: {ct:?}"
268            ),
269            ty::ConstKind::Expr(_) => unimplemented!(
270                "`feature(generic_const_exprs)` is not supported in the new trait solver"
271            ),
272            ty::ConstKind::Param(_) => {
273                unreachable!("`ConstKind::Param` should have been canonicalized to `Placeholder`")
274            }
275            ty::ConstKind::Bound(_, _) => panic!("escaping bound vars in {:?}", ct),
276            ty::ConstKind::Value(cv) => cv.ty(),
277            ty::ConstKind::Placeholder(placeholder) => {
278                placeholder.find_const_ty_from_env(goal.param_env)
279            }
280        };
281
282        self.eq(goal.param_env, ct_ty, ty)?;
283        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes).map_err(Into::into)
284    }
285}
286
287#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MergeCandidateInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            MergeCandidateInfo::AlwaysApplicable(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AlwaysApplicable", &__self_0),
            MergeCandidateInfo::EqualResponse =>
                ::core::fmt::Formatter::write_str(f, "EqualResponse"),
        }
    }
}Debug)]
288enum MergeCandidateInfo {
289    AlwaysApplicable(usize),
290    EqualResponse,
291}
292
293impl<D, I> EvalCtxt<'_, D>
294where
295    D: SolverDelegate<Interner = I>,
296    I: Interner,
297{
298    /// Try to merge multiple possible ways to prove a goal, if that is not possible returns `None`.
299    ///
300    /// In this case we tend to flounder and return ambiguity by calling `[EvalCtxt::flounder]`.
301    x;#[instrument(level = "trace", skip(self), ret)]
302    fn try_merge_candidates(
303        &mut self,
304        candidates: &[Candidate<I>],
305    ) -> Option<(CanonicalResponse<I>, MergeCandidateInfo)> {
306        if candidates.is_empty() {
307            return None;
308        }
309
310        let always_applicable = candidates.iter().enumerate().find(|(_, candidate)| {
311            candidate.result.value.certainty == Certainty::Yes
312                && has_no_inference_or_external_constraints(candidate.result)
313        });
314        if let Some((i, c)) = always_applicable {
315            return Some((c.result, MergeCandidateInfo::AlwaysApplicable(i)));
316        }
317
318        let one: CanonicalResponse<I> = candidates[0].result;
319        if candidates[1..].iter().all(|candidate| candidate.result == one) {
320            return Some((one, MergeCandidateInfo::EqualResponse));
321        }
322
323        None
324    }
325
326    fn bail_with_ambiguity(&mut self, candidates: &[Candidate<I>]) -> CanonicalResponse<I> {
327        if true {
    if !(candidates.len() > 1) {
        ::core::panicking::panic("assertion failed: candidates.len() > 1")
    };
};debug_assert!(candidates.len() > 1);
328        let maybe = candidates.iter().fold(MaybeInfo::AMBIGUOUS, |maybe, candidate| {
329            // We pull down the certainty of `Certainty::Yes` to ambiguity when combining
330            // these responses, b/c we're combining more than one response and this we
331            // don't know which one applies.
332            match candidate.result.value.certainty {
333                Certainty::Yes => maybe,
334                Certainty::Maybe(cand_maybe) => maybe.or(cand_maybe),
335            }
336        });
337        self.make_ambiguous_response_no_constraints(maybe)
338    }
339
340    /// If we fail to merge responses we flounder and return overflow or ambiguity.
341    x;#[instrument(level = "trace", skip(self), ret)]
342    fn flounder(&mut self, candidates: &[Candidate<I>]) -> QueryResult<I> {
343        if candidates.is_empty() {
344            return Err(NoSolution);
345        } else {
346            Ok(self.bail_with_ambiguity(candidates))
347        }
348    }
349
350    /// Normalize a type for when it is structurally matched on.
351    ///
352    /// This function is necessary in nearly all cases before matching on a type.
353    /// Not doing so is likely to be incomplete and therefore unsound during
354    /// coherence.
355    x;#[instrument(level = "trace", skip(self, param_env), ret)]
356    fn structurally_normalize_ty(
357        &mut self,
358        param_env: I::ParamEnv,
359        ty: I::Ty,
360    ) -> Result<I::Ty, NoSolutionOrRerunNonErased> {
361        self.structurally_normalize_term(param_env, ty.into()).map(|term| term.expect_ty())
362    }
363
364    /// Normalize a const for when it is structurally matched on, or more likely
365    /// when it needs `.try_to_*` called on it (e.g. to turn it into a usize).
366    ///
367    /// This function is necessary in nearly all cases before matching on a const.
368    /// Not doing so is likely to be incomplete and therefore unsound during
369    /// coherence.
370    x;#[instrument(level = "trace", skip(self, param_env), ret)]
371    fn structurally_normalize_const(
372        &mut self,
373        param_env: I::ParamEnv,
374        ct: I::Const,
375    ) -> Result<I::Const, NoSolutionOrRerunNonErased> {
376        self.structurally_normalize_term(param_env, ct.into()).map(|term| term.expect_const())
377    }
378
379    /// Normalize a term for when it is structurally matched on.
380    ///
381    /// This function is necessary in nearly all cases before matching on a ty/const.
382    /// Not doing so is likely to be incomplete and therefore unsound during coherence.
383    fn structurally_normalize_term(
384        &mut self,
385        param_env: I::ParamEnv,
386        term: I::Term,
387    ) -> Result<I::Term, NoSolutionOrRerunNonErased> {
388        if !self.cx().renormalize_rigid_aliases() && !term.is_non_rigid_alias() {
389            return Ok(term);
390        }
391
392        if let Some(alias) = term.to_alias_term() {
393            let normalized_term = self.next_term_infer_of_alias_kind(alias);
394            let projection_goal = Goal::new(
395                self.cx(),
396                param_env,
397                ty::ProjectionPredicate { projection_term: alias, term: normalized_term },
398            );
399            // We normalize the self type to be able to relate it with
400            // types from candidates.
401            self.add_goal(GoalSource::TypeRelating, projection_goal)?;
402            self.try_evaluate_added_goals()?;
403            Ok(self.resolve_vars_if_possible(normalized_term))
404        } else {
405            Ok(term)
406        }
407    }
408}
409
410/// The result of evaluating a goal.
411#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for GoalEvaluation<I> where I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            GoalEvaluation {
                goal: ref __field_goal,
                certainty: ref __field_certainty,
                has_changed: ref __field_has_changed,
                stalled_on: ref __field_stalled_on } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "GoalEvaluation");
                ::core::fmt::DebugStruct::field(&mut __builder, "goal",
                    __field_goal);
                ::core::fmt::DebugStruct::field(&mut __builder, "certainty",
                    __field_certainty);
                ::core::fmt::DebugStruct::field(&mut __builder, "has_changed",
                    __field_has_changed);
                ::core::fmt::DebugStruct::field(&mut __builder, "stalled_on",
                    __field_stalled_on);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Debug; I: Interner)]
412pub struct GoalEvaluation<I: Interner> {
413    /// The goal we've evaluated. This is the input goal, but potentially with its
414    /// inference variables resolved. This never applies any inference constraints
415    /// from evaluating the goal.
416    ///
417    /// We rely on this to check whether root goals in HIR typeck had an unresolved
418    /// type inference variable in the input. We must not resolve this after evaluating
419    /// the goal as even if the inference variable has been resolved by evaluating the
420    /// goal itself, this goal may still end up failing due to region uniquification
421    /// later on.
422    ///
423    /// This is used as a minor optimization to avoid re-resolving inference variables
424    /// when reevaluating ambiguous goals. E.g. if we've got a goal `?x: Trait` with `?x`
425    /// already being constrained to `Vec<?y>`, then the first evaluation resolves it to
426    /// `Vec<?y>: Trait`. If this goal is still ambiguous and we later resolve `?y` to `u32`,
427    /// then reevaluating this goal now only needs to resolve `?y` while it would otherwise
428    /// have to resolve both `?x` and `?y`,
429    pub goal: Goal<I, I::Predicate>,
430    pub certainty: Certainty,
431    pub has_changed: HasChanged,
432    /// If the [`Certainty`] was `Maybe`, then keep track of whether the goal has changed
433    /// before rerunning it.
434    pub stalled_on: Option<GoalStalledOn<I>>,
435}