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, TyVid};
27use tracing::instrument;
28
29pub use self::eval_ctxt::{
30    EvalCtxt, GenerateProofTree, SolverDelegateEvalExt,
31    evaluate_root_goal_for_proof_tree_raw_provider,
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(&["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: QueryResultOrRerunNonErased<I> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::OutlivesPredicate(ty, lt) = goal.predicate;
            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); }
            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
94        if self.cx().assumptions_on_binders() {
95            // FIXME(-Zassumptions-on-binders): we need to normalize `ty`
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        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
103    }
104
105    #[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(105u32),
                                    ::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: 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))]
106    fn compute_region_outlives_goal(
107        &mut self,
108        goal: Goal<I, ty::OutlivesPredicate<I, I::Region>>,
109    ) -> QueryResultOrRerunNonErased<I> {
110        let ty::OutlivesPredicate(a, b) = goal.predicate;
111
112        if self.cx().assumptions_on_binders() {
113            let constraint =
114                rustc_type_ir::region_constraint::RegionConstraint::RegionOutlives(a, b);
115            self.register_solver_region_constraint(constraint);
116        } else {
117            self.register_region_outlives(a, b, VisibleForLeakCheck::Yes);
118        }
119
120        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
121    }
122
123    #[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(123u32),
                                    ::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: 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))]
124    fn compute_coerce_goal(
125        &mut self,
126        goal: Goal<I, ty::CoercePredicate<I>>,
127    ) -> QueryResultOrRerunNonErased<I> {
128        self.compute_subtype_goal(Goal {
129            param_env: goal.param_env,
130            predicate: ty::SubtypePredicate {
131                a_is_expected: false,
132                a: goal.predicate.a,
133                b: goal.predicate.b,
134            },
135        })
136    }
137
138    #[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(138u32),
                                    ::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: 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))]
139    fn compute_subtype_goal(
140        &mut self,
141        goal: Goal<I, ty::SubtypePredicate<I>>,
142    ) -> QueryResultOrRerunNonErased<I> {
143        match (goal.predicate.a.kind(), goal.predicate.b.kind()) {
144            (ty::Infer(ty::TyVar(a_vid)), ty::Infer(ty::TyVar(b_vid))) => {
145                self.sub_unify_ty_vids_raw(a_vid, b_vid);
146                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
147            }
148            _ => {
149                self.sub(goal.param_env, goal.predicate.a, goal.predicate.b)?;
150                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
151            }
152        }
153    }
154
155    fn compute_dyn_compatible_goal(
156        &mut self,
157        trait_def_id: I::TraitId,
158    ) -> QueryResultOrRerunNonErased<I> {
159        if self.cx().trait_is_dyn_compatible(trait_def_id) {
160            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
161        } else {
162            Err(NoSolution.into())
163        }
164    }
165
166    #[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(166u32),
                                    ::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: 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))]
167    fn compute_well_formed_goal(
168        &mut self,
169        goal: Goal<I, I::Term>,
170    ) -> QueryResultOrRerunNonErased<I> {
171        match self.well_formed_goals(goal.param_env, goal.predicate) {
172            Some(goals) => {
173                self.add_goals(GoalSource::Misc, goals)?;
174                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
175            }
176            None => self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS),
177        }
178    }
179
180    fn compute_unstable_feature_goal(
181        &mut self,
182        param_env: <I as Interner>::ParamEnv,
183        symbol: <I as Interner>::Symbol,
184    ) -> QueryResultOrRerunNonErased<I> {
185        if self.may_use_unstable_feature(param_env, symbol)? {
186            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
187        } else {
188            self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
189        }
190    }
191
192    #[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(192u32),
                                    ::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: 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))]
193    fn compute_const_evaluatable_goal(
194        &mut self,
195        Goal { param_env, predicate: ct }: Goal<I, I::Const>,
196    ) -> QueryResultOrRerunNonErased<I> {
197        match ct.kind() {
198            ty::ConstKind::Alias(ty::IsRigid::Yes, _)
199            | ty::ConstKind::Placeholder(_)
200            | ty::ConstKind::Value(_)
201            | ty::ConstKind::Error(_) => {
202                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
203            }
204
205            ty::ConstKind::Infer(_) => {
206                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
207            }
208
209            ty::ConstKind::Alias(ty::IsRigid::No, alias_const) => {
210                // We never return `NoSolution` here as `evaluate_const` emits an
211                // error itself when failing to evaluate, so emitting an additional fulfillment
212                // error in that case is unnecessary noise. This may change in the future once
213                // evaluation failures are allowed to impact selection, e.g. generic const
214                // expressions in impl headers or `where`-clauses.
215
216                // FIXME(generic_const_exprs): Implement handling for generic
217                // const expressions here.
218                if let Some(_normalized) = self.evaluate_const(param_env, alias_const)? {
219                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
220                } else {
221                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
222                }
223            }
224
225            // We can freely ICE here as:
226            // - `Param` gets replaced with a placeholder during canonicalization
227            // - `Bound` cannot exist as we don't have a binder around the self Type
228            // - `Expr` is part of `feature(generic_const_exprs)` and is not implemented yet
229            ty::ConstKind::Param(_) | ty::ConstKind::Bound(_, _) | ty::ConstKind::Expr(_) => {
230                panic!("unexpected const kind: {:?}", ct)
231            }
232        }
233    }
234
235    x;#[instrument(level = "trace", skip(self), ret)]
236    fn compute_const_arg_has_type_goal(
237        &mut self,
238        goal: Goal<I, (I::Const, I::Ty)>,
239    ) -> QueryResultOrRerunNonErased<I> {
240        let (ct, ty) = goal.predicate;
241        let ct = self.structurally_normalize_const(goal.param_env, ct)?;
242
243        let ct_ty = match ct.kind() {
244            ty::ConstKind::Infer(_) => {
245                return self
246                    .evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
247                    .map_err(Into::into);
248            }
249            ty::ConstKind::Error(_) => {
250                return self
251                    .evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
252                    .map_err(Into::into);
253            }
254            ty::ConstKind::Alias(ty::IsRigid::Yes, alias_const) => {
255                alias_const.type_of(self.cx()).skip_norm_wip()
256            }
257            ty::ConstKind::Alias(ty::IsRigid::No, _) => unimplemented!(
258                "non-rigid unevaluated constant for compute_const_arg_has_type_goal: {ct:?}"
259            ),
260            ty::ConstKind::Expr(_) => unimplemented!(
261                "`feature(generic_const_exprs)` is not supported in the new trait solver"
262            ),
263            ty::ConstKind::Param(_) => {
264                unreachable!("`ConstKind::Param` should have been canonicalized to `Placeholder`")
265            }
266            ty::ConstKind::Bound(_, _) => panic!("escaping bound vars in {:?}", ct),
267            ty::ConstKind::Value(cv) => cv.ty(),
268            ty::ConstKind::Placeholder(placeholder) => {
269                placeholder.find_const_ty_from_env(goal.param_env)
270            }
271        };
272
273        self.eq(goal.param_env, ct_ty, ty)?;
274        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes).map_err(Into::into)
275    }
276}
277
278#[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)]
279enum MergeCandidateInfo {
280    AlwaysApplicable(usize),
281    EqualResponse,
282}
283
284impl<D, I> EvalCtxt<'_, D>
285where
286    D: SolverDelegate<Interner = I>,
287    I: Interner,
288{
289    /// Try to merge multiple possible ways to prove a goal, if that is not possible returns `None`.
290    ///
291    /// In this case we tend to flounder and return ambiguity by calling `[EvalCtxt::flounder]`.
292    x;#[instrument(level = "trace", skip(self), ret)]
293    fn try_merge_candidates(
294        &mut self,
295        candidates: &[Candidate<I>],
296    ) -> Option<(CanonicalResponse<I>, MergeCandidateInfo)> {
297        if candidates.is_empty() {
298            return None;
299        }
300
301        let always_applicable = candidates.iter().enumerate().find(|(_, candidate)| {
302            candidate.result.value.certainty == Certainty::Yes
303                && has_no_inference_or_external_constraints(candidate.result)
304        });
305        if let Some((i, c)) = always_applicable {
306            return Some((c.result, MergeCandidateInfo::AlwaysApplicable(i)));
307        }
308
309        let one: CanonicalResponse<I> = candidates[0].result;
310        if candidates[1..].iter().all(|candidate| candidate.result == one) {
311            return Some((one, MergeCandidateInfo::EqualResponse));
312        }
313
314        None
315    }
316
317    fn bail_with_ambiguity(&mut self, candidates: &[Candidate<I>]) -> CanonicalResponse<I> {
318        if true {
    if !(candidates.len() > 1) {
        ::core::panicking::panic("assertion failed: candidates.len() > 1")
    };
};debug_assert!(candidates.len() > 1);
319        let maybe = candidates.iter().fold(MaybeInfo::AMBIGUOUS, |maybe, candidate| {
320            // We pull down the certainty of `Certainty::Yes` to ambiguity when combining
321            // these responses, b/c we're combining more than one response and this we
322            // don't know which one applies.
323            match candidate.result.value.certainty {
324                Certainty::Yes => maybe,
325                Certainty::Maybe(cand_maybe) => maybe.or(cand_maybe),
326            }
327        });
328        self.make_ambiguous_response_no_constraints(maybe)
329    }
330
331    /// If we fail to merge responses we flounder and return overflow or ambiguity.
332    x;#[instrument(level = "trace", skip(self), ret)]
333    fn flounder(&mut self, candidates: &[Candidate<I>]) -> QueryResult<I> {
334        if candidates.is_empty() {
335            return Err(NoSolution);
336        } else {
337            Ok(self.bail_with_ambiguity(candidates))
338        }
339    }
340
341    /// Normalize a type for when it is structurally matched on.
342    ///
343    /// This function is necessary in nearly all cases before matching on a type.
344    /// Not doing so is likely to be incomplete and therefore unsound during
345    /// coherence.
346    x;#[instrument(level = "trace", skip(self, param_env), ret)]
347    fn structurally_normalize_ty(
348        &mut self,
349        param_env: I::ParamEnv,
350        ty: I::Ty,
351    ) -> Result<I::Ty, NoSolutionOrRerunNonErased> {
352        self.structurally_normalize_term(param_env, ty.into()).map(|term| term.expect_ty())
353    }
354
355    /// Normalize a const for when it is structurally matched on, or more likely
356    /// when it needs `.try_to_*` called on it (e.g. to turn it into a usize).
357    ///
358    /// This function is necessary in nearly all cases before matching on a const.
359    /// Not doing so is likely to be incomplete and therefore unsound during
360    /// coherence.
361    x;#[instrument(level = "trace", skip(self, param_env), ret)]
362    fn structurally_normalize_const(
363        &mut self,
364        param_env: I::ParamEnv,
365        ct: I::Const,
366    ) -> Result<I::Const, NoSolutionOrRerunNonErased> {
367        self.structurally_normalize_term(param_env, ct.into()).map(|term| term.expect_const())
368    }
369
370    /// Normalize a term for when it is structurally matched on.
371    ///
372    /// This function is necessary in nearly all cases before matching on a ty/const.
373    /// Not doing so is likely to be incomplete and therefore unsound during coherence.
374    fn structurally_normalize_term(
375        &mut self,
376        param_env: I::ParamEnv,
377        term: I::Term,
378    ) -> Result<I::Term, NoSolutionOrRerunNonErased> {
379        if !self.cx().renormalize_rigid_aliases() && !term.is_non_rigid_alias() {
380            return Ok(term);
381        }
382
383        if let Some(alias) = term.to_alias_term() {
384            let normalized_term = self.next_term_infer_of_alias_kind(alias);
385            let projection_goal = Goal::new(
386                self.cx(),
387                param_env,
388                ty::ProjectionPredicate { projection_term: alias, term: normalized_term },
389            );
390            // We normalize the self type to be able to relate it with
391            // types from candidates.
392            self.add_goal(GoalSource::TypeRelating, projection_goal)?;
393            self.try_evaluate_added_goals()?;
394            Ok(self.resolve_vars_if_possible(normalized_term))
395        } else {
396            Ok(term)
397        }
398    }
399}
400
401/// The result of evaluating a goal.
402#[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)]
403pub struct GoalEvaluation<I: Interner> {
404    /// The goal we've evaluated. This is the input goal, but potentially with its
405    /// inference variables resolved. This never applies any inference constraints
406    /// from evaluating the goal.
407    ///
408    /// We rely on this to check whether root goals in HIR typeck had an unresolved
409    /// type inference variable in the input. We must not resolve this after evaluating
410    /// the goal as even if the inference variable has been resolved by evaluating the
411    /// goal itself, this goal may still end up failing due to region uniquification
412    /// later on.
413    ///
414    /// This is used as a minor optimization to avoid re-resolving inference variables
415    /// when reevaluating ambiguous goals. E.g. if we've got a goal `?x: Trait` with `?x`
416    /// already being constrained to `Vec<?y>`, then the first evaluation resolves it to
417    /// `Vec<?y>: Trait`. If this goal is still ambiguous and we later resolve `?y` to `u32`,
418    /// then reevaluating this goal now only needs to resolve `?y` while it would otherwise
419    /// have to resolve both `?x` and `?y`,
420    pub goal: Goal<I, I::Predicate>,
421    pub certainty: Certainty,
422    pub has_changed: HasChanged,
423    /// If the [`Certainty`] was `Maybe`, then keep track of whether the goal has changed
424    /// before rerunning it.
425    pub stalled_on: Option<GoalStalledOn<I>>,
426}
427
428/// The conditions that must change for a goal to warrant
429#[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,
                previously_succeeded_in_erased: ref __field_previously_succeeded_in_erased
                } => {
                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::field(&mut __builder,
                    "previously_succeeded_in_erased",
                    __field_previously_succeeded_in_erased);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Clone, Debug; I: Interner)]
430pub struct GoalStalledOn<I: Interner> {
431    pub num_opaques: usize,
432    pub stalled_vars: Vec<I::GenericArg>,
433    pub sub_roots: Vec<TyVid>,
434    /// The certainty that will be returned on subsequent evaluations if this
435    /// goal remains stalled.
436    pub stalled_certainty: Certainty,
437    pub previously_succeeded_in_erased: SucceededInErased<I>,
438}
439
440#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for SucceededInErased<I> where
    I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            SucceededInErased::Yes {
                accessed_opaques: ref __field_accessed_opaques } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "Yes");
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "accessed_opaques", __field_accessed_opaques);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
            SucceededInErased::No =>
                ::core::fmt::Formatter::write_str(__f, "No"),
        }
    }
}#[derive_where(Clone, Debug; I: Interner)]
441pub enum SucceededInErased<I: Interner> {
442    Yes { accessed_opaques: AccessedOpaques<I> },
443    No,
444}