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 alias_relate;
15mod assembly;
16mod effect_goals;
17mod eval_ctxt;
18pub mod inspect;
19mod normalizes_to;
20mod project_goals;
21mod search_graph;
22mod trait_goals;
23
24use derive_where::derive_where;
25use rustc_type_ir::inherent::*;
26pub use rustc_type_ir::solve::*;
27use rustc_type_ir::{self as ty, Interner, TyVid, TypingMode};
28use tracing::instrument;
29
30pub use self::eval_ctxt::{
31    EvalCtxt, GenerateProofTree, SolverDelegateEvalExt,
32    evaluate_root_goal_for_proof_tree_raw_provider,
33};
34use crate::delegate::SolverDelegate;
35use crate::solve::assembly::Candidate;
36
37/// How many fixpoint iterations we should attempt inside of the solver before bailing
38/// with overflow.
39///
40/// We previously used  `cx.recursion_limit().0.checked_ilog2().unwrap_or(0)` for this.
41/// However, it feels unlikely that uncreasing the recursion limit by a power of two
42/// to get one more iteration is ever useful or desirable. We now instead used a constant
43/// here. If there ever ends up some use-cases where a bigger number of fixpoint iterations
44/// is required, we can add a new attribute for that or revert this to be dependent on the
45/// recursion limit again. However, this feels very unlikely.
46const FIXPOINT_STEP_LIMIT: usize = 8;
47
48/// Whether evaluating this goal ended up changing the
49/// inference state.
50#[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)]
51pub enum HasChanged {
52    Yes,
53    No,
54}
55
56// FIXME(trait-system-refactor-initiative#117): we don't detect whether a response
57// ended up pulling down any universes.
58fn has_no_inference_or_external_constraints<I: Interner>(
59    response: ty::Canonical<I, Response<I>>,
60) -> bool {
61    let ExternalConstraintsData {
62        ref region_constraints,
63        ref opaque_types,
64        ref normalization_nested_goals,
65    } = *response.value.external_constraints;
66    response.value.var_values.is_identity()
67        && region_constraints.is_empty()
68        && opaque_types.is_empty()
69        && normalization_nested_goals.is_empty()
70}
71
72fn has_only_region_constraints<I: Interner>(response: ty::Canonical<I, Response<I>>) -> bool {
73    let ExternalConstraintsData {
74        region_constraints: _,
75        ref opaque_types,
76        ref normalization_nested_goals,
77    } = *response.value.external_constraints;
78    response.value.var_values.is_identity_modulo_regions()
79        && opaque_types.is_empty()
80        && normalization_nested_goals.is_empty()
81}
82
83impl<'a, D, I> EvalCtxt<'a, D>
84where
85    D: SolverDelegate<Interner = I>,
86    I: Interner,
87{
88    #[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(88u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&["goal"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: QueryResult<I> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::OutlivesPredicate(ty, lt) = goal.predicate;
            self.register_ty_outlives(ty, lt);
            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
        }
    }
}#[instrument(level = "trace", skip(self))]
89    fn compute_type_outlives_goal(
90        &mut self,
91        goal: Goal<I, ty::OutlivesPredicate<I, I::Ty>>,
92    ) -> QueryResult<I> {
93        let ty::OutlivesPredicate(ty, lt) = goal.predicate;
94        self.register_ty_outlives(ty, lt);
95        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
96    }
97
98    #[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(98u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&["goal"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: QueryResult<I> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::OutlivesPredicate(a, b) = goal.predicate;
            self.register_region_outlives(a, b);
            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
        }
    }
}#[instrument(level = "trace", skip(self))]
99    fn compute_region_outlives_goal(
100        &mut self,
101        goal: Goal<I, ty::OutlivesPredicate<I, I::Region>>,
102    ) -> QueryResult<I> {
103        let ty::OutlivesPredicate(a, b) = goal.predicate;
104        self.register_region_outlives(a, b);
105        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
106    }
107
108    #[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(108u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&["goal"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: QueryResult<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))]
109    fn compute_coerce_goal(&mut self, goal: Goal<I, ty::CoercePredicate<I>>) -> QueryResult<I> {
110        self.compute_subtype_goal(Goal {
111            param_env: goal.param_env,
112            predicate: ty::SubtypePredicate {
113                a_is_expected: false,
114                a: goal.predicate.a,
115                b: goal.predicate.b,
116            },
117        })
118    }
119
120    #[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(120u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&["goal"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: QueryResult<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))]
121    fn compute_subtype_goal(&mut self, goal: Goal<I, ty::SubtypePredicate<I>>) -> QueryResult<I> {
122        match (goal.predicate.a.kind(), goal.predicate.b.kind()) {
123            (ty::Infer(ty::TyVar(a_vid)), ty::Infer(ty::TyVar(b_vid))) => {
124                self.sub_unify_ty_vids_raw(a_vid, b_vid);
125                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
126            }
127            _ => {
128                self.sub(goal.param_env, goal.predicate.a, goal.predicate.b)?;
129                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
130            }
131        }
132    }
133
134    fn compute_dyn_compatible_goal(&mut self, trait_def_id: I::TraitId) -> QueryResult<I> {
135        if self.cx().trait_is_dyn_compatible(trait_def_id) {
136            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
137        } else {
138            Err(NoSolution)
139        }
140    }
141
142    #[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(142u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&["goal"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: QueryResult<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))]
143    fn compute_well_formed_goal(&mut self, goal: Goal<I, I::Term>) -> QueryResult<I> {
144        match self.well_formed_goals(goal.param_env, goal.predicate) {
145            Some(goals) => {
146                self.add_goals(GoalSource::Misc, goals);
147                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
148            }
149            None => self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS),
150        }
151    }
152
153    fn compute_unstable_feature_goal(
154        &mut self,
155        param_env: <I as Interner>::ParamEnv,
156        symbol: <I as Interner>::Symbol,
157    ) -> QueryResult<I> {
158        if self.may_use_unstable_feature(param_env, symbol) {
159            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
160        } else {
161            self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
162        }
163    }
164
165    #[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(165u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve"),
                                    ::tracing_core::field::FieldSet::new(&["param_env", "ct"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: QueryResult<I> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match ct.kind() {
                ty::ConstKind::Unevaluated(uv) => {
                    if let Some(_normalized) =
                            self.evaluate_const(param_env, uv) {
                        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                    } else {
                        self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                    }
                }
                ty::ConstKind::Infer(_) => {
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                }
                ty::ConstKind::Placeholder(_) | ty::ConstKind::Value(_) |
                    ty::ConstKind::Error(_) => {
                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                }
                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))]
166    fn compute_const_evaluatable_goal(
167        &mut self,
168        Goal { param_env, predicate: ct }: Goal<I, I::Const>,
169    ) -> QueryResult<I> {
170        match ct.kind() {
171            ty::ConstKind::Unevaluated(uv) => {
172                // We never return `NoSolution` here as `evaluate_const` emits an
173                // error itself when failing to evaluate, so emitting an additional fulfillment
174                // error in that case is unnecessary noise. This may change in the future once
175                // evaluation failures are allowed to impact selection, e.g. generic const
176                // expressions in impl headers or `where`-clauses.
177
178                // FIXME(generic_const_exprs): Implement handling for generic
179                // const expressions here.
180                if let Some(_normalized) = self.evaluate_const(param_env, uv) {
181                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
182                } else {
183                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
184                }
185            }
186            ty::ConstKind::Infer(_) => {
187                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
188            }
189            ty::ConstKind::Placeholder(_) | ty::ConstKind::Value(_) | ty::ConstKind::Error(_) => {
190                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
191            }
192            // We can freely ICE here as:
193            // - `Param` gets replaced with a placeholder during canonicalization
194            // - `Bound` cannot exist as we don't have a binder around the self Type
195            // - `Expr` is part of `feature(generic_const_exprs)` and is not implemented yet
196            ty::ConstKind::Param(_) | ty::ConstKind::Bound(_, _) | ty::ConstKind::Expr(_) => {
197                panic!("unexpected const kind: {:?}", ct)
198            }
199        }
200    }
201
202    x;#[instrument(level = "trace", skip(self), ret)]
203    fn compute_const_arg_has_type_goal(
204        &mut self,
205        goal: Goal<I, (I::Const, I::Ty)>,
206    ) -> QueryResult<I> {
207        let (ct, ty) = goal.predicate;
208        let ct = self.structurally_normalize_const(goal.param_env, ct)?;
209
210        let ct_ty = match ct.kind() {
211            ty::ConstKind::Infer(_) => {
212                return self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS);
213            }
214            ty::ConstKind::Error(_) => {
215                return self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes);
216            }
217            ty::ConstKind::Unevaluated(uv) => {
218                self.cx().type_of(uv.def.into()).instantiate(self.cx(), uv.args).skip_norm_wip()
219            }
220            ty::ConstKind::Expr(_) => unimplemented!(
221                "`feature(generic_const_exprs)` is not supported in the new trait solver"
222            ),
223            ty::ConstKind::Param(_) => {
224                unreachable!("`ConstKind::Param` should have been canonicalized to `Placeholder`")
225            }
226            ty::ConstKind::Bound(_, _) => panic!("escaping bound vars in {:?}", ct),
227            ty::ConstKind::Value(cv) => cv.ty(),
228            ty::ConstKind::Placeholder(placeholder) => {
229                placeholder.find_const_ty_from_env(goal.param_env)
230            }
231        };
232
233        self.eq(goal.param_env, ct_ty, ty)?;
234        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
235    }
236}
237
238#[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)]
239enum MergeCandidateInfo {
240    AlwaysApplicable(usize),
241    EqualResponse,
242}
243
244impl<D, I> EvalCtxt<'_, D>
245where
246    D: SolverDelegate<Interner = I>,
247    I: Interner,
248{
249    /// Try to merge multiple possible ways to prove a goal, if that is not possible returns `None`.
250    ///
251    /// In this case we tend to flounder and return ambiguity by calling `[EvalCtxt::flounder]`.
252    x;#[instrument(level = "trace", skip(self), ret)]
253    fn try_merge_candidates(
254        &mut self,
255        candidates: &[Candidate<I>],
256    ) -> Option<(CanonicalResponse<I>, MergeCandidateInfo)> {
257        if candidates.is_empty() {
258            return None;
259        }
260
261        let always_applicable = candidates.iter().enumerate().find(|(_, candidate)| {
262            candidate.result.value.certainty == Certainty::Yes
263                && has_no_inference_or_external_constraints(candidate.result)
264        });
265        if let Some((i, c)) = always_applicable {
266            return Some((c.result, MergeCandidateInfo::AlwaysApplicable(i)));
267        }
268
269        let one: CanonicalResponse<I> = candidates[0].result;
270        if candidates[1..].iter().all(|candidate| candidate.result == one) {
271            return Some((one, MergeCandidateInfo::EqualResponse));
272        }
273
274        None
275    }
276
277    fn bail_with_ambiguity(&mut self, candidates: &[Candidate<I>]) -> CanonicalResponse<I> {
278        if true {
    if !(candidates.len() > 1) {
        ::core::panicking::panic("assertion failed: candidates.len() > 1")
    };
};debug_assert!(candidates.len() > 1);
279        let maybe = candidates.iter().fold(MaybeInfo::AMBIGUOUS, |maybe, candidate| {
280            // We pull down the certainty of `Certainty::Yes` to ambiguity when combining
281            // these responses, b/c we're combining more than one response and this we
282            // don't know which one applies.
283            match candidate.result.value.certainty {
284                Certainty::Yes => maybe,
285                Certainty::Maybe(cand_maybe) => maybe.or(cand_maybe),
286            }
287        });
288        self.make_ambiguous_response_no_constraints(maybe)
289    }
290
291    /// If we fail to merge responses we flounder and return overflow or ambiguity.
292    x;#[instrument(level = "trace", skip(self), ret)]
293    fn flounder(&mut self, candidates: &[Candidate<I>]) -> QueryResult<I> {
294        if candidates.is_empty() {
295            return Err(NoSolution);
296        } else {
297            Ok(self.bail_with_ambiguity(candidates))
298        }
299    }
300
301    /// Normalize a type for when it is structurally matched on.
302    ///
303    /// This function is necessary in nearly all cases before matching on a type.
304    /// Not doing so is likely to be incomplete and therefore unsound during
305    /// coherence.
306    x;#[instrument(level = "trace", skip(self, param_env), ret)]
307    fn structurally_normalize_ty(
308        &mut self,
309        param_env: I::ParamEnv,
310        ty: I::Ty,
311    ) -> Result<I::Ty, NoSolution> {
312        self.structurally_normalize_term(param_env, ty.into()).map(|term| term.expect_ty())
313    }
314
315    /// Normalize a const for when it is structurally matched on, or more likely
316    /// when it needs `.try_to_*` called on it (e.g. to turn it into a usize).
317    ///
318    /// This function is necessary in nearly all cases before matching on a const.
319    /// Not doing so is likely to be incomplete and therefore unsound during
320    /// coherence.
321    x;#[instrument(level = "trace", skip(self, param_env), ret)]
322    fn structurally_normalize_const(
323        &mut self,
324        param_env: I::ParamEnv,
325        ct: I::Const,
326    ) -> Result<I::Const, NoSolution> {
327        self.structurally_normalize_term(param_env, ct.into()).map(|term| term.expect_const())
328    }
329
330    /// Normalize a term for when it is structurally matched on.
331    ///
332    /// This function is necessary in nearly all cases before matching on a ty/const.
333    /// Not doing so is likely to be incomplete and therefore unsound during coherence.
334    fn structurally_normalize_term(
335        &mut self,
336        param_env: I::ParamEnv,
337        term: I::Term,
338    ) -> Result<I::Term, NoSolution> {
339        if let Some(_) = term.to_alias_term(self.cx()) {
340            let normalized_term = self.next_term_infer_of_kind(term);
341            let alias_relate_goal = Goal::new(
342                self.cx(),
343                param_env,
344                ty::PredicateKind::AliasRelate(
345                    term,
346                    normalized_term,
347                    ty::AliasRelationDirection::Equate,
348                ),
349            );
350            // We normalize the self type to be able to relate it with
351            // types from candidates.
352            self.add_goal(GoalSource::TypeRelating, alias_relate_goal);
353            self.try_evaluate_added_goals()?;
354            Ok(self.resolve_vars_if_possible(normalized_term))
355        } else {
356            Ok(term)
357        }
358    }
359
360    fn opaque_type_is_rigid(&self, def_id: I::DefId) -> bool {
361        match self.typing_mode() {
362            // Opaques are never rigid outside of analysis mode.
363            TypingMode::Coherence | TypingMode::PostAnalysis => false,
364            // During analysis, opaques are rigid unless they may be defined by
365            // the current body.
366            TypingMode::Analysis { defining_opaque_types_and_generators: non_rigid_opaques }
367            | TypingMode::Borrowck { defining_opaque_types: non_rigid_opaques }
368            | TypingMode::PostBorrowckAnalysis { defined_opaque_types: non_rigid_opaques } => {
369                !def_id.as_local().is_some_and(|def_id| non_rigid_opaques.contains(&def_id))
370            }
371        }
372    }
373}
374
375/// The result of evaluating a goal.
376#[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)]
377pub struct GoalEvaluation<I: Interner> {
378    /// The goal we've evaluated. This is the input goal, but potentially with its
379    /// inference variables resolved. This never applies any inference constraints
380    /// from evaluating the goal.
381    ///
382    /// We rely on this to check whether root goals in HIR typeck had an unresolved
383    /// type inference variable in the input. We must not resolve this after evaluating
384    /// the goal as even if the inference variable has been resolved by evaluating the
385    /// goal itself, this goal may still end up failing due to region uniquification
386    /// later on.
387    ///
388    /// This is used as a minor optimization to avoid re-resolving inference variables
389    /// when reevaluating ambiguous goals. E.g. if we've got a goal `?x: Trait` with `?x`
390    /// already being constrained to `Vec<?y>`, then the first evaluation resolves it to
391    /// `Vec<?y>: Trait`. If this goal is still ambiguous and we later resolve `?y` to `u32`,
392    /// then reevaluating this goal now only needs to resolve `?y` while it would otherwise
393    /// have to resolve both `?x` and `?y`,
394    pub goal: Goal<I, I::Predicate>,
395    pub certainty: Certainty,
396    pub has_changed: HasChanged,
397    /// If the [`Certainty`] was `Maybe`, then keep track of whether the goal has changed
398    /// before rerunning it.
399    pub stalled_on: Option<GoalStalledOn<I>>,
400}
401
402/// The conditions that must change for a goal to warrant
403#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for GoalStalledOn<I> where I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            GoalStalledOn {
                num_opaques: ref __field_num_opaques,
                stalled_vars: ref __field_stalled_vars,
                sub_roots: ref __field_sub_roots,
                stalled_certainty: ref __field_stalled_certainty } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "GoalStalledOn");
                ::core::fmt::DebugStruct::field(&mut __builder, "num_opaques",
                    __field_num_opaques);
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "stalled_vars", __field_stalled_vars);
                ::core::fmt::DebugStruct::field(&mut __builder, "sub_roots",
                    __field_sub_roots);
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "stalled_certainty", __field_stalled_certainty);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Clone, Debug; I: Interner)]
404pub struct GoalStalledOn<I: Interner> {
405    pub num_opaques: usize,
406    pub stalled_vars: Vec<I::GenericArg>,
407    pub sub_roots: Vec<TyVid>,
408    /// The certainty that will be returned on subsequent evaluations if this
409    /// goal remains stalled.
410    pub stalled_certainty: Certainty,
411}