Skip to main content

rustc_next_trait_solver/solve/eval_ctxt/
mod.rs

1use std::mem;
2use std::ops::ControlFlow;
3
4#[cfg(feature = "nightly")]
5use rustc_macros::StableHash;
6use rustc_type_ir::data_structures::HashSet;
7use rustc_type_ir::inherent::*;
8use rustc_type_ir::region_constraint::{RegionConstraint, evaluate_solver_constraint};
9use rustc_type_ir::relate::Relate;
10use rustc_type_ir::relate::solver_relating::RelateExt;
11use rustc_type_ir::search_graph::{
12    CandidateHeadUsages, LowerAvailableDepth, PathKind, RequiredDepth,
13};
14use rustc_type_ir::solve::{
15    AccessedOpaques, ExternalRegionConstraints, FetchEligibleAssocItemResponse, MaybeInfo,
16    NoSolutionOrRerunNonErased, OpaqueTypesJank, QueryResultOrRerunNonErased, RerunCondition,
17    RerunNonErased, RerunReason, RerunResultExt, SmallCopySet, TyOrConstInferVar,
18};
19use rustc_type_ir::{
20    self as ty, CanonicalVarValues, ClauseKind, InferCtxtLike, Interner, MayBeErased,
21    OpaqueTypeKey, PredicateKind, Region, TypeFoldable, TypeSuperVisitable, TypeVisitable,
22    TypeVisitableExt, TypeVisitor, TypingMode, eager_resolve_vars,
23};
24use thin_vec::ThinVec;
25use tracing::{Level, debug, instrument, trace, warn};
26
27use super::has_only_region_constraints;
28use crate::canonical::{
29    canonicalize_goal, canonicalize_response, instantiate_and_apply_query_response,
30    response_no_constraints_raw,
31};
32use crate::coherence;
33use crate::delegate::SolverDelegate;
34use crate::normalize::{NormalizationFolder, NormalizationWasAmbiguous};
35use crate::placeholder::BoundVarReplacer;
36use crate::solve::eval_ctxt::fast_path::{
37    RerunStalled, compute_goal_fast_path, inlined_rerunning_stalled_goal_may_make_progress,
38    rerunning_stalled_goal_may_make_progress,
39};
40use crate::solve::fast_path::compute_goal_fast_path_cold;
41use crate::solve::search_graph::SearchGraph;
42use crate::solve::ty::may_use_unstable_feature;
43use crate::solve::{
44    CanonicalInput, CanonicalResponse, Certainty, ExternalConstraintsData, FIXPOINT_STEP_LIMIT,
45    Goal, GoalEvaluation, GoalSource, GoalStalledOn, GoalStalledOnOpaques, HasChanged, MaybeCause,
46    NestedNormalizationGoals, NoSolution, QueryInput, QueryResult, Response, SucceededInErased,
47    VisibleForLeakCheck, inspect,
48};
49
50pub mod fast_path;
51mod probe;
52mod solver_region_constraints;
53
54/// The kind of goal we're currently proving.
55///
56/// This has effects on cycle handling handling and on how we compute
57/// query responses, see the variant descriptions for more info.
58#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CurrentGoalKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CurrentGoalKind::Misc => "Misc",
                CurrentGoalKind::CoinductiveTrait => "CoinductiveTrait",
                CurrentGoalKind::ProjectionComputeAssocTermCandidate =>
                    "ProjectionComputeAssocTermCandidate",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for CurrentGoalKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CurrentGoalKind {
    #[inline]
    fn clone(&self) -> CurrentGoalKind { *self }
}Clone)]
59enum CurrentGoalKind {
60    Misc,
61    /// We're proving an trait goal for a coinductive trait, either an auto trait or `Sized`.
62    ///
63    /// These are currently the only goals whose impl where-clauses are considered to be
64    /// productive steps.
65    CoinductiveTrait,
66    // FIXME: Consider renaming `PredicateKind::NormalizesTo` to match with this
67    /// Unlike other goals, `NormalizesTo` goals aren't independent goals but just implementation
68    /// details for handling projections of associated terms. When we encounter a `Projection` goal
69    /// whose `projection_term` is an associated term, we create a `NormalizesTo` goal whose
70    /// expected term is fully unconstrained and evaluate it.
71    ///
72    /// This would weaken inference however, as the nested goals of normalizes-to never get the
73    /// inference constraints from the actual expected term. We just gather candidates from the
74    /// normalizes-to goal and return any ambiguous nested goals of it to the caller (`Projection
75    /// goal`). The caller handle and evaluate them as if they were its own nested goals.
76    ///
77    /// Because of this, evaluating a normalizes-to goal is computing candidates for projection of
78    /// an associated term and it never leaks out of the solver.
79    ProjectionComputeAssocTermCandidate,
80}
81
82impl CurrentGoalKind {
83    fn from_query_input<I: Interner>(cx: I, input: QueryInput<I, I::Predicate>) -> CurrentGoalKind {
84        match input.goal.predicate.kind().skip_binder() {
85            ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
86                if cx.trait_is_coinductive(pred.trait_ref.def_id) {
87                    CurrentGoalKind::CoinductiveTrait
88                } else {
89                    CurrentGoalKind::Misc
90                }
91            }
92            ty::PredicateKind::NormalizesTo(_) => {
93                CurrentGoalKind::ProjectionComputeAssocTermCandidate
94            }
95            _ => CurrentGoalKind::Misc,
96        }
97    }
98}
99
100pub struct EvalCtxt<'a, D, I = <D as SolverDelegate>::Interner>
101where
102    D: SolverDelegate<Interner = I>,
103    I: Interner,
104{
105    /// The inference context that backs (mostly) inference and placeholder terms
106    /// instantiated while solving goals.
107    ///
108    /// NOTE: The `InferCtxt` that backs the `EvalCtxt` is intentionally private,
109    /// because the `InferCtxt` is much more general than `EvalCtxt`. Methods such
110    /// as  `take_registered_region_obligations` can mess up query responses,
111    /// using `At::normalize` is totally wrong, calling `evaluate_root_goal` can
112    /// cause coinductive unsoundness, etc.
113    ///
114    /// Methods that are generally of use for trait solving are *intentionally*
115    /// re-declared through the `EvalCtxt` below, often with cleaner signatures
116    /// since we don't care about things like `ObligationCause`s and `Span`s here.
117    /// If some `InferCtxt` method is missing, please first think defensively about
118    /// the method's compatibility with this solver, or if an existing one does
119    /// the job already.
120    delegate: &'a D,
121
122    /// The variable info for the `var_values`, only used to make an ambiguous response
123    /// with no constraints.
124    var_kinds: I::CanonicalVarKinds,
125
126    /// What kind of goal we're currently computing, see the enum definition
127    /// for more info.
128    current_goal_kind: CurrentGoalKind,
129    pub(super) var_values: CanonicalVarValues<I>,
130
131    /// The highest universe index nameable by the caller.
132    ///
133    /// When we enter a new binder inside of the query we create new universes
134    /// which the caller cannot name. We have to be careful with variables from
135    /// these new universes when creating the query response.
136    ///
137    /// Both because these new universes can prevent us from reaching a fixpoint
138    /// if we have a coinductive cycle and because that's the only way we can return
139    /// new placeholders to the caller.
140    pub(super) max_input_universe: ty::UniverseIndex,
141    /// The opaque types from the canonical input. We only need to return opaque types
142    /// which have been added to the storage while evaluating this goal.
143    pub(super) initial_opaque_types_storage_num_entries:
144        <D::Infcx as InferCtxtLike>::OpaqueTypeStorageEntries,
145
146    pub(super) search_graph: &'a mut SearchGraph<D>,
147
148    nested_goals: Vec<(GoalSource, Goal<I, I::Predicate>, Option<GoalStalledOn<I>>)>,
149
150    pub(super) origin_span: I::Span,
151
152    // Has this `EvalCtxt` errored out with `NoSolution` in `try_evaluate_added_goals`?
153    //
154    // If so, then it can no longer be used to make a canonical query response,
155    // since subsequent calls to `try_evaluate_added_goals` have possibly dropped
156    // ambiguous goals. Instead, a probe needs to be introduced somewhere in the
157    // evaluation code.
158    tainted: Result<(), NoSolution>,
159
160    /// Tracks accesses of opaque types while in [`TypingMode::ErasedNotCoherence`].
161    pub(super) opaque_accesses: AccessedOpaques<I>,
162
163    pub(super) inspect: inspect::EvaluationStepBuilder<D>,
164}
165
166#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for GenerateProofTree {
    #[inline]
    fn eq(&self, other: &GenerateProofTree) -> 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 GenerateProofTree {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for GenerateProofTree {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                GenerateProofTree::Yes => "Yes",
                GenerateProofTree::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::hash::Hash for GenerateProofTree {
    #[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 GenerateProofTree {
    #[inline]
    fn clone(&self) -> GenerateProofTree { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for GenerateProofTree { }Copy)]
167#[cfg_attr(feature = "nightly", derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            GenerateProofTree {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    GenerateProofTree::Yes => {}
                    GenerateProofTree::No => {}
                }
            }
        }
    };StableHash))]
168pub enum GenerateProofTree {
169    Yes,
170    No,
171}
172
173pub trait SolverDelegateEvalExt: SolverDelegate {
174    /// Evaluates a goal from **outside** of the trait solver.
175    ///
176    /// Using this while inside of the solver is wrong as it uses a new
177    /// search graph which would break cycle detection.
178    fn evaluate_root_goal(
179        &self,
180        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
181        span: <Self::Interner as Interner>::Span,
182        stalled_on: Option<GoalStalledOn<Self::Interner>>,
183    ) -> Result<GoalEvaluation<Self::Interner>, NoSolution>;
184
185    /// Checks whether a stalled goal would remain stalled if re-evaluated, without consuming
186    /// `stalled_on`.
187    fn goal_remains_stalled(&self, stalled_on: &GoalStalledOn<Self::Interner>) -> bool;
188
189    /// Checks whether evaluating `goal` may hold while treating not-yet-defined
190    /// opaque types as being kind of rigid.
191    ///
192    /// See the comment on [OpaqueTypesJank] for more details.
193    fn root_goal_may_hold_opaque_types_jank(
194        &self,
195        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
196    ) -> bool;
197
198    /// Check whether evaluating `goal` with a depth of `root_depth` may
199    /// succeed. This only returns `false` if the goal is guaranteed to
200    /// not hold. In case evaluation overflows and fails with ambiguity this
201    /// returns `true`.
202    ///
203    /// This is only intended to be used as a performance optimization
204    /// in coherence checking.
205    fn root_goal_may_hold_with_depth(
206        &self,
207        root_depth: usize,
208        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
209    ) -> bool;
210
211    // FIXME: This is only exposed because we need to use it in `analyse.rs`
212    // which is not yet uplifted. Once that's done, we should remove this.
213    fn evaluate_root_goal_for_proof_tree(
214        &self,
215        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
216        span: <Self::Interner as Interner>::Span,
217    ) -> (
218        Result<NestedNormalizationGoals<Self::Interner>, NoSolution>,
219        inspect::GoalEvaluation<Self::Interner>,
220    );
221}
222
223impl<D, I> SolverDelegateEvalExt for D
224where
225    D: SolverDelegate<Interner = I>,
226    I: Interner,
227{
228    x;#[instrument(level = "debug", skip(self), ret)]
229    fn evaluate_root_goal(
230        &self,
231        goal: Goal<I, I::Predicate>,
232        span: I::Span,
233        stalled_on: Option<GoalStalledOn<I>>,
234    ) -> Result<GoalEvaluation<I>, NoSolution> {
235        // Run fast paths *before* building an `EvalCtxt`, saving a little bit of time.
236        if let RerunStalled::WontMakeProgress(stalled_maybe_info) =
237            rerunning_stalled_goal_may_make_progress(self, stalled_on.as_ref())
238        {
239            return Ok(GoalEvaluation {
240                goal,
241                certainty: Certainty::Maybe(stalled_maybe_info),
242                has_changed: HasChanged::No,
243                stalled_on,
244            });
245        }
246
247        // No need to try the fast path if stalled_on is `None`, since we already try the fast path
248        // immediately when adding new goals. If we didn't check `stalled_on` here we'd be trying
249        // the fast path twice for some goals.
250        if stalled_on.is_some()
251            && let Some(res) = compute_goal_fast_path_cold(self, goal, span)
252        {
253            return Ok(res);
254        }
255
256        let mut result = EvalCtxt::enter_root(self, self.cx().recursion_limit(), span, |ecx| {
257            ecx.evaluate_goal_no_fast_paths(GoalSource::Misc, goal)
258        });
259        maybe_evaluate_root_goal_with_higher_recursion_limit(self, goal, span, &mut result);
260
261        match result {
262            Ok(i) => Ok(i),
263            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Err(NoSolution),
264            Err(NoSolutionOrRerunNonErased::RerunNonErased(_)) => {
265                unreachable!("this never happens at the root, we're never in erased mode here");
266            }
267        }
268    }
269
270    // This function is very hot and has a single call site.
271    #[inline(always)]
272    fn goal_remains_stalled(&self, stalled_on: &GoalStalledOn<Self::Interner>) -> bool {
273        match inlined_rerunning_stalled_goal_may_make_progress(self, Some(stalled_on)) {
274            RerunStalled::WontMakeProgress(_) => true,
275            RerunStalled::MayMakeProgress => false,
276        }
277    }
278
279    x;#[instrument(level = "debug", skip(self), ret)]
280    fn root_goal_may_hold_opaque_types_jank(
281        &self,
282        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
283    ) -> bool {
284        self.probe(|| {
285            self.evaluate_root_goal(goal, I::Span::dummy(), None).is_ok_and(|r| match r.certainty {
286                Certainty::Yes => true,
287                Certainty::Maybe(MaybeInfo {
288                    cause: _,
289                    opaque_types_jank,
290                    stalled_on_coroutines: _,
291                }) => match opaque_types_jank {
292                    OpaqueTypesJank::AllGood => true,
293                    OpaqueTypesJank::ErrorIfRigidSelfTy => false,
294                },
295            })
296        })
297    }
298
299    fn root_goal_may_hold_with_depth(
300        &self,
301        root_depth: usize,
302        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
303    ) -> bool {
304        self.probe(|| {
305            EvalCtxt::enter_root(self, root_depth, I::Span::dummy(), |ecx| {
306                ecx.evaluate_goal(GoalSource::Misc, goal, None)
307            })
308        })
309        .is_ok()
310    }
311
312    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("evaluate_root_goal_for_proof_tree",
                                    "rustc_next_trait_solver::solve::eval_ctxt",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(312u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    (Result<NestedNormalizationGoals<I>, NoSolution>,
                    inspect::GoalEvaluation<I>) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut result =
                evaluate_root_goal_for_proof_tree(self, goal, span,
                    self.cx().recursion_limit());
            maybe_evaluate_root_goal_for_proof_tree_with_higher_recursion_limit(self,
                goal, span, &mut result);
            result
        }
    }
}#[instrument(level = "debug", skip(self))]
313    fn evaluate_root_goal_for_proof_tree(
314        &self,
315        goal: Goal<I, I::Predicate>,
316        span: I::Span,
317    ) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
318        let mut result =
319            evaluate_root_goal_for_proof_tree(self, goal, span, self.cx().recursion_limit());
320        maybe_evaluate_root_goal_for_proof_tree_with_higher_recursion_limit(
321            self,
322            goal,
323            span,
324            &mut result,
325        );
326        result
327    }
328}
329
330/// The old solver doesn't check depth requirement when looking up cache while the next solver
331/// does so. Thus the next solver is more prone to overflow. To mitigate breakages, we re-evaluate
332/// the overflowed goal with doubled recursion limit and emit a FCW if doing so prevents overflow.
333///
334/// See the doc comment on `RECURSION_DEPTH_EXCEEDING_LIMIT` and #159228 for more details.
335fn maybe_evaluate_root_goal_with_higher_recursion_limit<D, I>(
336    delegate: &D,
337    goal: Goal<I, I::Predicate>,
338    span: I::Span,
339    initial_result: &mut Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased>,
340) where
341    D: SolverDelegate<Interner = I>,
342    I: Interner,
343{
344    if !delegate.enable_next_solver_overflow_fcw() {
345        return;
346    }
347
348    let predicate = match initial_result {
349        Err(_) => return,
350        Ok(goal_evaluation) if !goal_evaluation.certainty.is_overflow() => return,
351        Ok(goal_evaluation) => goal_evaluation.goal.predicate,
352    };
353
354    let rerun_result = delegate.commit_if_ok(|| {
355        let rerun_result =
356            EvalCtxt::enter_root(delegate, delegate.cx().recursion_limit() * 2, span, |ecx| {
357                ecx.evaluate_goal_no_fast_paths(GoalSource::Misc, goal)
358            });
359
360        if rerun_result.as_ref().is_ok_and(|evaluation| evaluation.certainty.is_overflow()) {
361            Err(())
362        } else {
363            Ok(rerun_result)
364        }
365    });
366    if let Ok(rerun_result) = rerun_result {
367        delegate.emit_next_solver_overflow_fcw(goal.with(delegate.cx(), predicate), span);
368        *initial_result = rerun_result;
369    }
370}
371
372/// The old solver doesn't check depth requirement when looking up cache while the next solver
373/// does so. Thus the next solver is more prone to overflow. To mitigate breakages, we re-evaluate
374/// the overflowed goal with doubled recursion limit and emit a FCW if doing so prevents overflow.
375///
376/// See the doc comment on `RECURSION_DEPTH_EXCEEDING_LIMIT` and #159228 for more details.
377fn maybe_evaluate_root_goal_for_proof_tree_with_higher_recursion_limit<D, I>(
378    delegate: &D,
379    goal: Goal<I, I::Predicate>,
380    span: I::Span,
381    initial_result: &mut (
382        Result<NestedNormalizationGoals<I>, NoSolution>,
383        inspect::GoalEvaluation<I>,
384    ),
385) where
386    D: SolverDelegate<Interner = I>,
387    I: Interner,
388{
389    if !delegate.enable_next_solver_overflow_fcw() {
390        return;
391    }
392
393    let goal_evaluation = &initial_result.1;
394    match goal_evaluation.result {
395        Err(_) => return,
396        Ok(response) if !response.value.certainty.is_overflow() => return,
397        Ok(_) => {}
398    }
399
400    let rerun_result = delegate.commit_if_ok(|| {
401        let (new_result, new_goal_evaluation) = evaluate_root_goal_for_proof_tree(
402            delegate,
403            goal,
404            span,
405            delegate.cx().recursion_limit() * 2,
406        );
407
408        if new_goal_evaluation.result.is_ok_and(|response| response.value.certainty.is_overflow()) {
409            Err(())
410        } else {
411            Ok((new_result, new_goal_evaluation))
412        }
413    });
414    if let Ok(rerun_result) = rerun_result {
415        let predicate: I::Predicate = goal_evaluation.uncanonicalized_goal.predicate;
416        delegate.emit_next_solver_overflow_fcw(goal.with(delegate.cx(), predicate), span);
417        *initial_result = rerun_result;
418    }
419}
420
421impl<'a, D, I> EvalCtxt<'a, D>
422where
423    D: SolverDelegate<Interner = I>,
424    I: Interner,
425{
426    pub(super) fn typing_mode(&self) -> TypingMode<I> {
427        self.delegate.typing_mode_raw()
428    }
429
430    /// Computes the `PathKind` for the step from the current goal to the
431    /// nested goal required due to `source`.
432    ///
433    /// See #136824 for a more detailed reasoning for this behavior. We
434    /// consider cycles to be coinductive if they 'step into' a where-clause
435    /// of a coinductive trait. We will likely extend this function in the future
436    /// and will need to clearly document it in the rustc-dev-guide before
437    /// stabilization.
438    pub(super) fn step_kind_for_source(&self, source: GoalSource) -> PathKind {
439        match source {
440            // We treat these goals as unknown for now. It is likely that most miscellaneous
441            // nested goals will be converted to an inductive variant in the future.
442            //
443            // Having unknown cycles is always the safer option, as changing that to either
444            // succeed or hard error is backwards compatible. If we incorrectly treat a cycle
445            // as inductive even though it should not be, it may be unsound during coherence and
446            // fixing it may cause inference breakage or introduce ambiguity.
447            GoalSource::Misc => PathKind::Unknown,
448            GoalSource::NormalizeGoal(path_kind) => path_kind,
449            GoalSource::ImplWhereBound => match self.current_goal_kind {
450                // We currently only consider a cycle coinductive if it steps
451                // into a where-clause of a coinductive trait.
452                CurrentGoalKind::CoinductiveTrait => PathKind::Coinductive,
453                // We probably want to make all traits coinductive in the future,
454                // so we treat cycles involving where-clauses of not-yet coinductive
455                // traits as ambiguous for now.
456                CurrentGoalKind::Misc | CurrentGoalKind::ProjectionComputeAssocTermCandidate => {
457                    PathKind::Unknown
458                }
459            },
460            // Relating types is always unproductive. If we were to map proof trees to
461            // corecursive functions as explained in #136824, relating types never
462            // introduces a constructor which could cause the recursion to be guarded.
463            GoalSource::TypeRelating => PathKind::Inductive,
464            // These goal sources are likely unproductive and can be changed to
465            // `PathKind::Inductive`. Keeping them as unknown until we're confident
466            // about this and have an example where it is necessary.
467            GoalSource::AliasBoundConstCondition | GoalSource::AliasWellFormed => PathKind::Unknown,
468        }
469    }
470
471    /// Creates a root evaluation context and search graph. This should only be
472    /// used from outside of any evaluation, and other methods should be preferred
473    /// over using this manually (such as [`SolverDelegateEvalExt::evaluate_root_goal`]).
474    pub(super) fn enter_root<R>(
475        delegate: &D,
476        root_depth: usize,
477        origin_span: I::Span,
478        f: impl FnOnce(&mut EvalCtxt<'_, D>) -> R,
479    ) -> R {
480        let mut search_graph = SearchGraph::new(root_depth);
481
482        let mut ecx = EvalCtxt {
483            delegate,
484            search_graph: &mut search_graph,
485            nested_goals: Default::default(),
486            inspect: inspect::EvaluationStepBuilder::new_noop(),
487
488            // Only relevant when canonicalizing the response,
489            // which we don't do within this evaluation context.
490            max_input_universe: ty::UniverseIndex::ROOT,
491            initial_opaque_types_storage_num_entries: Default::default(),
492            var_kinds: Default::default(),
493            var_values: CanonicalVarValues::dummy(),
494            current_goal_kind: CurrentGoalKind::Misc,
495            origin_span,
496            tainted: Ok(()),
497            opaque_accesses: AccessedOpaques::default(),
498        };
499        let result = f(&mut ecx);
500        if !ecx.nested_goals.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("root `EvalCtxt` should not have any goals added to it"));
    }
};assert!(
501            ecx.nested_goals.is_empty(),
502            "root `EvalCtxt` should not have any goals added to it"
503        );
504        if !!ecx.opaque_accesses.might_rerun() {
    ::core::panicking::panic("assertion failed: !ecx.opaque_accesses.might_rerun()")
};assert!(!ecx.opaque_accesses.might_rerun());
505        if !search_graph.is_empty() {
    ::core::panicking::panic("assertion failed: search_graph.is_empty()")
};assert!(search_graph.is_empty());
506        result
507    }
508
509    /// Creates a nested evaluation context that shares the same search graph as the
510    /// one passed in. This is suitable for evaluation, granted that the search graph
511    /// has had the nested goal recorded on its stack. This method only be used by
512    /// `search_graph::Delegate::compute_goal`.
513    ///
514    /// This function takes care of setting up the inference context, setting the anchor,
515    /// and registering opaques from the canonicalized input.
516    pub(super) fn enter_canonical<T>(
517        cx: I,
518        search_graph: &'a mut SearchGraph<D>,
519        canonical_input: CanonicalInput<I>,
520        proof_tree_builder: &mut inspect::ProofTreeBuilder<D>,
521        f: impl FnOnce(
522            &mut EvalCtxt<'_, D>,
523            Goal<I, I::Predicate>,
524        ) -> Result<T, NoSolutionOrRerunNonErased>,
525    ) -> (Result<T, NoSolution>, AccessedOpaques<I>) {
526        let (ref delegate, input, var_values) = D::build_with_canonical(cx, &canonical_input);
527        for (key, ty) in input.predefined_opaques_in_body.iter() {
528            let prev = delegate.register_hidden_type_in_storage(key, ty, I::Span::dummy());
529            // It may be possible that two entries in the opaque type storage end up
530            // with the same key after resolving contained inference variables.
531            //
532            // We could put them in the duplicate list but don't have to. The opaques we
533            // encounter here are already tracked in the caller, so there's no need to
534            // also store them here. We'd take them out when computing the query response
535            // and then discard them, as they're already present in the input.
536            //
537            // Ideally we'd drop duplicate opaque type definitions when computing
538            // the canonical input. This is more annoying to implement and may cause a
539            // perf regression, so we do it inside of the query for now.
540            if let Some(prev) = prev {
541                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:541",
                        "rustc_next_trait_solver::solve::eval_ctxt",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(541u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("key")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("key");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("ty");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("prev")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("prev");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ignore duplicate in `opaque_types_storage`")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&key)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&prev)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?key, ?ty, ?prev, "ignore duplicate in `opaque_types_storage`");
542            }
543        }
544
545        let initial_opaque_types_storage_num_entries = delegate.opaque_types_storage_num_entries();
546        if truecfg!(debug_assertions) && delegate.typing_mode_raw().is_erased_not_coherence() {
547            if !delegate.clone_opaque_types_lookup_table().is_empty() {
    ::core::panicking::panic("assertion failed: delegate.clone_opaque_types_lookup_table().is_empty()")
};assert!(delegate.clone_opaque_types_lookup_table().is_empty());
548        }
549
550        let mut ecx = EvalCtxt {
551            delegate,
552            var_kinds: canonical_input.canonical.var_kinds,
553            var_values,
554            current_goal_kind: CurrentGoalKind::from_query_input(cx, input),
555            max_input_universe: canonical_input.canonical.max_universe,
556            initial_opaque_types_storage_num_entries,
557            search_graph,
558            nested_goals: Default::default(),
559            origin_span: I::Span::dummy(),
560            tainted: Ok(()),
561            inspect: proof_tree_builder.new_evaluation_step(var_values),
562            opaque_accesses: AccessedOpaques::default(),
563        };
564
565        let result = f(&mut ecx, input.goal);
566        ecx.inspect.probe_final_state(ecx.delegate, ecx.max_input_universe);
567        proof_tree_builder.finish_evaluation_step(ecx.inspect);
568
569        if canonical_input.typing_mode.0.is_erased_not_coherence() {
570            if true {
    if !delegate.clone_opaque_types_lookup_table().is_empty() {
        ::core::panicking::panic("assertion failed: delegate.clone_opaque_types_lookup_table().is_empty()")
    };
};debug_assert!(delegate.clone_opaque_types_lookup_table().is_empty());
571        }
572
573        // When creating a query response we clone the opaque type constraints
574        // instead of taking them. This would cause an ICE here, since we have
575        // assertions against dropping an `InferCtxt` without taking opaques.
576        // FIXME: Once we remove support for the old impl we can remove this.
577        // FIXME: Could we make `build_with_canonical` into `enter_with_canonical` and call this at the end?
578        delegate.reset_opaque_types();
579
580        let opaque_accesses = ecx.opaque_accesses;
581        (
582            match result {
583                Ok(i) => Ok(i),
584                Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Err(NoSolution),
585                Err(NoSolutionOrRerunNonErased::RerunNonErased(_)) => {
586                    // Check that the opaque_accesses state mirrors the result we got.
587                    if !opaque_accesses.should_bail().is_err() {
    ::core::panicking::panic("assertion failed: opaque_accesses.should_bail().is_err()")
};assert!(opaque_accesses.should_bail().is_err());
588                    Err(NoSolution)
589                }
590            },
591            opaque_accesses,
592        )
593    }
594
595    pub(super) fn ignore_candidate_head_usages(&mut self, usages: CandidateHeadUsages) {
596        self.search_graph.ignore_candidate_head_usages(usages);
597    }
598
599    /// Recursively evaluates `goal`, returning whether any inference vars have
600    /// been constrained and the certainty of the result.
601    fn evaluate_goal(
602        &mut self,
603        source: GoalSource,
604        goal: Goal<I, I::Predicate>,
605        stalled_on: Option<GoalStalledOn<I>>,
606    ) -> Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased> {
607        if let RerunStalled::WontMakeProgress(stalled_maybe_info) =
608            rerunning_stalled_goal_may_make_progress(self.delegate, stalled_on.as_ref())
609        {
610            return Ok(GoalEvaluation {
611                goal,
612                certainty: Certainty::Maybe(stalled_maybe_info),
613                has_changed: HasChanged::No,
614                stalled_on,
615            });
616        }
617
618        // No need to try the fast path if stalled_on is `None`, since we already try the fast path
619        // immediately when adding new goals. If we didn't check `stalled_on` here we'd be trying
620        // the fast path twice for some goals.
621        if stalled_on.is_some()
622            && let Some(res) = compute_goal_fast_path_cold(self.delegate, goal, self.origin_span)
623        {
624            return Ok(res);
625        }
626
627        self.evaluate_goal_no_fast_paths(source, goal)
628    }
629
630    // Outlining and `#[cold]` matter here because fast paths make it less likely to get here.
631    #[cold]
632    #[inline(never)]
633    fn evaluate_goal_no_fast_paths(
634        &mut self,
635        source: GoalSource,
636        goal: Goal<I, I::Predicate>,
637    ) -> Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased> {
638        let (normalization_nested_goals, goal_evaluation) =
639            self.evaluate_goal_raw(source, goal, LowerAvailableDepth::Yes)?;
640        if !normalization_nested_goals.is_empty() {
    ::core::panicking::panic("assertion failed: normalization_nested_goals.is_empty()")
};assert!(normalization_nested_goals.is_empty());
641        Ok(goal_evaluation)
642    }
643
644    /// Recursively evaluates `goal`, returning the nested goals in case
645    /// the nested goal is a `NormalizesTo` goal.
646    ///
647    /// As all other goal kinds do not return any nested goals and
648    /// `NormalizesTo` is only used by `Projection`, all other callsites
649    /// should use [`EvalCtxt::evaluate_goal`] which discards that empty
650    /// storage.
651    pub(super) fn evaluate_goal_raw(
652        &mut self,
653        source: GoalSource,
654        goal: Goal<I, I::Predicate>,
655        increase_depth_for_nested: LowerAvailableDepth,
656    ) -> Result<(NestedNormalizationGoals<I>, GoalEvaluation<I>), NoSolutionOrRerunNonErased> {
657        // We only care about one entry per `OpaqueTypeKey` here,
658        // so we only canonicalize the lookup table and ignore
659        // duplicate entries.
660        let opaque_types = self.delegate.clone_opaque_types_lookup_table();
661        let (goal, opaque_types) = eager_resolve_vars(&**self.delegate, (goal, opaque_types));
662        let typing_mode = self.typing_mode();
663        let step_kind = self.step_kind_for_source(source);
664
665        let tracing_span = {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("evaluate_goal_raw in typing mode",
                        "rustc_next_trait_solver::solve::eval_ctxt", Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(665u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::SPAN)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let mut interest = ::tracing::subscriber::Interest::never();
    if Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                    Level::DEBUG <=
                        ::tracing::level_filters::LevelFilter::current() &&
                { interest = __CALLSITE.interest(); !interest.is_never() } &&
            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                interest) {
        let meta = __CALLSITE.metadata();
        ::tracing::Span::new(meta,
            &{
                    #[allow(unused_imports)]
                    use ::tracing::field::{debug, display, Value};
                    meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?} opaques={1:?}",
                                                        typing_mode, opaque_types) as
                                                &dyn ::tracing::field::Value))])
                })
    } else {
        let span =
            ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
        {};
        span
    }
}tracing::span!(
666            Level::DEBUG,
667            "evaluate_goal_raw in typing mode",
668            "{:?} opaques={:?}",
669            typing_mode,
670            opaque_types
671        )
672        .entered();
673
674        let (result, orig_values, canonical_goal, succeeded_in_erased) = 'retry_canonicalize: {
675            let skip_erased_attempt = match typing_mode {
676                TypingMode::Reflection | TypingMode::Coherence => true,
677                TypingMode::Typeck { .. }
678                | TypingMode::PostTypeckUntilBorrowck { .. }
679                | TypingMode::PostBorrowck { .. }
680                | TypingMode::Codegen
681                | TypingMode::PostAnalysis
682                | TypingMode::ErasedNotCoherence(_) => {
683                    let mut skip = false;
684                    if opaque_types.iter().any(|(_, ty)| ty.is_ty_var())
685                        && let PredicateKind::Clause(ClauseKind::Trait(..)) =
686                            goal.predicate.kind().skip_binder()
687                    {
688                        skip = true;
689                    }
690
691                    if let PredicateKind::Clause(ClauseKind::Trait(tr)) =
692                        goal.predicate.kind().skip_binder()
693                        && tr.self_ty().has_coroutines()
694                        && self.cx().trait_is_auto(tr.trait_ref.def_id)
695                    {
696                        // FIXME(#155443): this doesn't make a difference now, but with eager normalization
697                        // it likely will.
698                        // skip_erased_attempt = true;
699                    }
700
701                    skip
702                }
703            };
704
705            if skip_erased_attempt {
706                if typing_mode.is_erased_not_coherence() {
707                    match self.opaque_accesses.rerun_always(RerunReason::SkipErasedAttempt)? {}
708                } else {
709                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:709",
                        "rustc_next_trait_solver::solve::eval_ctxt",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(709u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("running in original typing mode")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("running in original typing mode");
710                }
711            } else {
712                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:712",
                        "rustc_next_trait_solver::solve::eval_ctxt",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(712u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("trying without opaques: {0:?}",
                                                    goal) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("trying without opaques: {goal:?}");
713
714                let (orig_values, canonical_goal) = canonicalize_goal(
715                    self.delegate,
716                    goal,
717                    &[],
718                    TypingMode::ErasedNotCoherence(MayBeErased),
719                );
720
721                let (canonical_result, accessed_opaques) = self.search_graph.evaluate_goal(
722                    self.cx(),
723                    canonical_goal,
724                    step_kind,
725                    increase_depth_for_nested,
726                    &mut inspect::ProofTreeBuilder::new_noop(),
727                );
728
729                let should_rerun = should_rerun_after_erased_canonicalization(
730                    accessed_opaques,
731                    self.typing_mode(),
732                    &opaque_types,
733                );
734                match should_rerun {
735                    RerunDecision::Yes => {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:735",
                        "rustc_next_trait_solver::solve::eval_ctxt",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(735u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("rerunning in original typing mode")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
}debug!("rerunning in original typing mode"),
736                    RerunDecision::No => {
737                        break 'retry_canonicalize (
738                            canonical_result,
739                            orig_values,
740                            canonical_goal,
741                            SucceededInErased::Yes { accessed_opaques },
742                        );
743                    }
744                    RerunDecision::EagerlyPropagateToParent => {
745                        self.opaque_accesses.update(accessed_opaques)?;
746                        break 'retry_canonicalize (
747                            canonical_result,
748                            orig_values,
749                            canonical_goal,
750                            // If we're propagating up, we should never retry the goal.
751                            // That means `No` is fine to return, it doesn't really matter.
752                            SucceededInErased::No,
753                        );
754                    }
755                }
756            }
757
758            let (orig_values, canonical_goal) =
759                canonicalize_goal(self.delegate, goal, &opaque_types, typing_mode);
760
761            let (canonical_result, accessed_opaques) = self.search_graph.evaluate_goal(
762                self.cx(),
763                canonical_goal,
764                step_kind,
765                increase_depth_for_nested,
766                &mut inspect::ProofTreeBuilder::new_noop(),
767            );
768            if !!accessed_opaques.might_rerun() {
    {
        ::core::panicking::panic_fmt(format_args!("we run without TypingMode::ErasedNotCoherence, so opaques are available, and we don\'t retry if the outer typing mode is ErasedNotCoherence: {0:?} after {1:?}",
                accessed_opaques, goal));
    }
};assert!(
769                !accessed_opaques.might_rerun(),
770                "we run without TypingMode::ErasedNotCoherence, so opaques are available, and we don't retry if the outer typing mode is ErasedNotCoherence: {accessed_opaques:?} after {goal:?}"
771            );
772
773            (canonical_result, orig_values, canonical_goal, SucceededInErased::No)
774        };
775
776        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:776",
                        "rustc_next_trait_solver::solve::eval_ctxt",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(776u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("result")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("result");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&result)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?result);
777        let response = match result {
778            Ok(response) => {
779                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:779",
                        "rustc_next_trait_solver::solve::eval_ctxt",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(779u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("success")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("success");
780                response
781            }
782            Err(NoSolution) => {
783                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:783",
                        "rustc_next_trait_solver::solve::eval_ctxt",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(783u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normal failure")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("normal failure");
784                return Err(NoSolution.into());
785            }
786        };
787
788        drop(tracing_span);
789
790        let has_changed =
791            if !has_only_region_constraints(response) { HasChanged::Yes } else { HasChanged::No };
792
793        let (normalization_nested_goals, certainty) = instantiate_and_apply_query_response(
794            self.delegate,
795            goal.param_env,
796            &orig_values,
797            response,
798            self.origin_span,
799        );
800
801        // FIXME: We previously had an assert here that checked that recomputing
802        // a goal after applying its constraints did not change its response.
803        //
804        // This assert was removed as it did not hold for goals constraining
805        // an inference variable to a recursive alias, e.g. in
806        // tests/ui/traits/next-solver/overflow/recursive-self-normalization.rs.
807        //
808        // Once we have decided on how to handle trait-system-refactor-initiative#75,
809        // we should re-add an assert here.
810
811        let stalled_on = match certainty {
812            Certainty::Yes => None,
813            Certainty::Maybe(maybe_info) => match has_changed {
814                // FIXME: We could recompute a *new* set of stalled variables by walking
815                // through the orig values, resolving, and computing the root vars of anything
816                // that is not resolved. Only when *these* have changed is it meaningful
817                // to recompute this goal.
818                HasChanged::Yes => None,
819                HasChanged::No => Some(self.build_stalled_on(
820                    canonical_goal,
821                    maybe_info,
822                    orig_values,
823                    succeeded_in_erased,
824                )),
825            },
826        };
827
828        Ok((
829            normalization_nested_goals,
830            GoalEvaluation { goal, certainty, has_changed, stalled_on },
831        ))
832    }
833
834    fn build_stalled_on(
835        &self,
836        canonical_goal: CanonicalInput<I>,
837        maybe_info: MaybeInfo,
838        stalled_vars: ThinVec<I::GenericArg>,
839        previously_succeeded_in_erased: SucceededInErased<I>,
840    ) -> GoalStalledOn<I> {
841        // Remove the canonicalized universal vars, since we only care about stalled existentials.
842        let mut sub_roots = ThinVec::new();
843        let stalled_vars = stalled_vars
844            .into_iter()
845            .filter_map(|arg| match arg.kind() {
846                // Lifetimes can never stall goals.
847                ty::GenericArgKind::Lifetime(_) => None,
848                ty::GenericArgKind::Type(ty) => match ty.kind() {
849                    ty::Infer(ty::TyVar(vid)) => {
850                        sub_roots.push(self.delegate.sub_unification_table_root_var(vid));
851                        Some(TyOrConstInferVar::Ty(vid))
852                    }
853                    ty::Infer(ty::IntVar(vid)) => Some(TyOrConstInferVar::TyInt(vid)),
854                    ty::Infer(ty::FloatVar(vid)) => Some(TyOrConstInferVar::TyFloat(vid)),
855                    ty::Param(_) | ty::Placeholder(_) => None,
856                    _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected orig_value: {0:?}", ty)));
}unreachable!("unexpected orig_value: {ty:?}"),
857                },
858                ty::GenericArgKind::Const(ct) => match ct.kind() {
859                    ty::ConstKind::Infer(ty::InferConst::Var(v)) => {
860                        Some(TyOrConstInferVar::Const(v))
861                    }
862                    ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(_) => None,
863                    _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected orig_value: {0:?}", ct)));
}unreachable!("unexpected orig_value: {ct:?}"),
864                },
865            })
866            .collect();
867
868        GoalStalledOn {
869            stalled_vars,
870            sub_roots,
871            stalled_maybe_info: maybe_info,
872            opaques: GoalStalledOnOpaques::Yes {
873                num_opaques_in_storage: canonical_goal
874                    .canonical
875                    .value
876                    .predefined_opaques_in_body
877                    .len(),
878                previously_succeeded_in_erased,
879            },
880        }
881    }
882
883    pub(super) fn compute_goal(
884        &mut self,
885        goal: Goal<I, I::Predicate>,
886    ) -> QueryResultOrRerunNonErased<I> {
887        let Goal { param_env, predicate } = goal;
888        let kind = predicate.kind();
889        self.enter_forall_with_assumptions(kind, param_env, |ecx, kind| {
890            Ok(match kind {
891                ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
892                    ecx.compute_trait_goal(Goal { param_env, predicate }).map(|(r, _via)| r)?
893                }
894                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
895                    ecx.compute_host_effect_goal(Goal { param_env, predicate })?
896                }
897                ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) => {
898                    ecx.compute_projection_goal(Goal { param_env, predicate })?
899                }
900                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(predicate)) => {
901                    ecx.compute_type_outlives_goal(Goal { param_env, predicate })?
902                }
903                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(predicate)) => {
904                    ecx.compute_region_outlives_goal(Goal { param_env, predicate })?
905                }
906                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
907                    ecx.compute_const_arg_has_type_goal(Goal { param_env, predicate: (ct, ty) })?
908                }
909                ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
910                    ecx.compute_unstable_feature_goal(param_env, symbol)?
911                }
912                ty::PredicateKind::Subtype(predicate) => {
913                    ecx.compute_subtype_goal(Goal { param_env, predicate })?
914                }
915                ty::PredicateKind::Coerce(predicate) => {
916                    ecx.compute_coerce_goal(Goal { param_env, predicate })?
917                }
918                ty::PredicateKind::DynCompatible(trait_def_id) => {
919                    ecx.compute_dyn_compatible_goal(trait_def_id)?
920                }
921                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
922                    ecx.compute_well_formed_goal(Goal { param_env, predicate: term })?
923                }
924                ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
925                    ecx.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })?
926                }
927                ty::PredicateKind::ConstEquate(_, _) => {
928                    {
    ::core::panicking::panic_fmt(format_args!("ConstEquate should not be emitted when `-Znext-solver` is active"));
}panic!("ConstEquate should not be emitted when `-Znext-solver` is active")
929                }
930                ty::PredicateKind::NormalizesTo(predicate) => {
931                    ecx.compute_normalizes_to_goal(Goal { param_env, predicate })?
932                }
933                ty::PredicateKind::Ambiguous => {
934                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)?
935                }
936            })
937        })
938    }
939
940    // Recursively evaluates all the goals added to this `EvalCtxt` to completion, returning
941    // the certainty of all the goals.
942    #[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("try_evaluate_added_goals",
                                    "rustc_next_trait_solver::solve::eval_ctxt",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(942u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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:
                    Result<Certainty, NoSolutionOrRerunNonErased> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            for _ in 0..FIXPOINT_STEP_LIMIT {
                match self.evaluate_added_goals_step().map_err_to_rerun()? {
                    Ok(None) => {}
                    Ok(Some(cert)) => return Ok(cert),
                    Err(NoSolution) => {
                        self.tainted = Err(NoSolution);
                        return Err(NoSolution.into());
                    }
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs:957",
                                    "rustc_next_trait_solver::solve::eval_ctxt",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(957u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_evaluate_added_goals: encountered overflow")
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            Ok(Certainty::overflow(false))
        }
    }
}#[instrument(level = "trace", skip(self))]
943    pub(super) fn try_evaluate_added_goals(
944        &mut self,
945    ) -> Result<Certainty, NoSolutionOrRerunNonErased> {
946        for _ in 0..FIXPOINT_STEP_LIMIT {
947            match self.evaluate_added_goals_step().map_err_to_rerun()? {
948                Ok(None) => {}
949                Ok(Some(cert)) => return Ok(cert),
950                Err(NoSolution) => {
951                    self.tainted = Err(NoSolution);
952                    return Err(NoSolution.into());
953                }
954            }
955        }
956
957        debug!("try_evaluate_added_goals: encountered overflow");
958        Ok(Certainty::overflow(false))
959    }
960
961    /// Iterate over all added goals: returning `Ok(Some(_))` in case we can stop rerunning.
962    ///
963    /// Goals for the next step get directly added to the nested goals of the `EvalCtxt`.
964    fn evaluate_added_goals_step(
965        &mut self,
966    ) -> Result<Option<Certainty>, NoSolutionOrRerunNonErased> {
967        // If this loop did not result in any progress, what's our final certainty.
968        let mut unchanged_certainty = Some(Certainty::Yes);
969        // This mem::take seems super inefficient, given that we push to it again later.
970        // Despite that, replacing it has no effect on performance. We tried.
971        // (https://github.com/rust-lang/rust/pull/158126)
972        for (source, goal, stalled_on) in mem::take(&mut self.nested_goals) {
973            // We never handle `NormalizesTo` as a nested goal
974            if true {
    if !!#[allow(non_exhaustive_omitted_patterns)] match goal.predicate.kind().skip_binder()
                    {
                    PredicateKind::NormalizesTo(_) => true,
                    _ => false,
                } {
        ::core::panicking::panic("assertion failed: !matches!(goal.predicate.kind().skip_binder(), PredicateKind::NormalizesTo(_))")
    };
};debug_assert!(!matches!(
975                goal.predicate.kind().skip_binder(),
976                PredicateKind::NormalizesTo(_)
977            ));
978
979            let GoalEvaluation { goal, certainty, has_changed, stalled_on } =
980                self.evaluate_goal(source, goal, stalled_on)?;
981            if has_changed == HasChanged::Yes {
982                unchanged_certainty = None;
983            }
984
985            match certainty {
986                Certainty::Yes => {}
987                Certainty::Maybe { .. } => {
988                    self.nested_goals.push((source, goal, stalled_on));
989                    unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
990                }
991            }
992        }
993
994        Ok(unchanged_certainty)
995    }
996
997    /// Record impl args in the proof tree for later access by `InspectCandidate`.
998    pub(crate) fn record_impl_args(&mut self, impl_args: I::GenericArgs) {
999        self.inspect.record_impl_args(self.delegate, self.max_input_universe, impl_args)
1000    }
1001
1002    pub(super) fn cx(&self) -> I {
1003        self.delegate.cx()
1004    }
1005
1006    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("add_goal",
                                    "rustc_next_trait_solver::solve::eval_ctxt",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1006u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<(), NoSolutionOrRerunNonErased> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            goal.predicate =
                self.normalize(GoalSource::NormalizeGoal(self.step_kind_for_source(source)),
                        goal.param_env, ty::Unnormalized::new_wip(goal.predicate))?;
            self.inspect.add_goal(self.delegate, self.max_input_universe,
                source, goal);
            if let Some(GoalEvaluation {
                    goal, certainty, has_changed: _, stalled_on }) =
                    compute_goal_fast_path(self.delegate, goal,
                        self.origin_span) {
                match certainty {
                    Certainty::Yes => {}
                    Certainty::Maybe(_) => {
                        self.nested_goals.push((source, goal, stalled_on));
                    }
                }
            } else { self.nested_goals.push((source, goal, None)); }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(self))]
1007    pub(super) fn add_goal(
1008        &mut self,
1009        source: GoalSource,
1010        mut goal: Goal<I, I::Predicate>,
1011    ) -> Result<(), NoSolutionOrRerunNonErased> {
1012        goal.predicate = self.normalize(
1013            GoalSource::NormalizeGoal(self.step_kind_for_source(source)),
1014            goal.param_env,
1015            ty::Unnormalized::new_wip(goal.predicate),
1016        )?;
1017        self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
1018
1019        if let Some(GoalEvaluation { goal, certainty, has_changed: _, stalled_on }) =
1020            compute_goal_fast_path(self.delegate, goal, self.origin_span)
1021        {
1022            match certainty {
1023                // We're done here
1024                Certainty::Yes => {}
1025                Certainty::Maybe(_) => {
1026                    self.nested_goals.push((source, goal, stalled_on));
1027                }
1028            }
1029        } else {
1030            self.nested_goals.push((source, goal, None));
1031        }
1032        Ok(())
1033    }
1034
1035    #[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("add_goals",
                                    "rustc_next_trait_solver::solve::eval_ctxt",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1035u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<(), NoSolutionOrRerunNonErased> = loop {};
            return __tracing_attr_fake_return;
        }
        { for goal in goals { self.add_goal(source, goal)?; } Ok(()) }
    }
}#[instrument(level = "trace", skip(self, goals))]
1036    pub(super) fn add_goals(
1037        &mut self,
1038        source: GoalSource,
1039        goals: impl IntoIterator<Item = Goal<I, I::Predicate>>,
1040    ) -> Result<(), NoSolutionOrRerunNonErased> {
1041        for goal in goals {
1042            self.add_goal(source, goal)?;
1043        }
1044        Ok(())
1045    }
1046
1047    pub(super) fn next_region_var(&mut self) -> Region<I> {
1048        let region = self.delegate.next_region_infer();
1049        self.inspect.add_var_value(region);
1050        region
1051    }
1052
1053    pub(super) fn next_ty_infer(&mut self) -> I::Ty {
1054        let ty = self.delegate.next_ty_infer();
1055        self.inspect.add_var_value(ty);
1056        ty
1057    }
1058
1059    pub(super) fn next_const_infer(&mut self) -> I::Const {
1060        let ct = self.delegate.next_const_infer();
1061        self.inspect.add_var_value(ct);
1062        ct
1063    }
1064
1065    /// Returns a ty infer or a const infer depending on whether `kind` is a `Ty` or `Const`.
1066    /// If `kind` is an integer inference variable this will still return a ty infer var.
1067    pub(super) fn next_term_infer_of_alias_kind(
1068        &mut self,
1069        alias_term: ty::AliasTerm<I>,
1070    ) -> I::Term {
1071        match alias_term.kind {
1072            ty::AliasTermKind::ProjectionTy { .. }
1073            | ty::AliasTermKind::InherentTy { .. }
1074            | ty::AliasTermKind::OpaqueTy { .. }
1075            | ty::AliasTermKind::FreeTy { .. } => self.next_ty_infer().into(),
1076            ty::AliasTermKind::FreeConst { .. }
1077            | ty::AliasTermKind::InherentConst { .. }
1078            | ty::AliasTermKind::AnonConst { .. }
1079            | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_infer().into(),
1080        }
1081    }
1082
1083    /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
1084    ///
1085    /// This is the case if the `term` does not occur in any other part of the predicate
1086    /// and is able to name all other placeholder and inference variables.
1087    x;#[instrument(level = "trace", skip(self), ret)]
1088    pub(super) fn term_is_fully_unconstrained(&self, goal: Goal<I, ty::NormalizesTo<I>>) -> bool {
1089        let universe_of_term = match goal.predicate.term.kind() {
1090            ty::TermKind::Ty(ty) => {
1091                if let ty::Infer(ty::TyVar(vid)) = ty.kind() {
1092                    self.delegate.universe_of_ty(vid).unwrap()
1093                } else {
1094                    return false;
1095                }
1096            }
1097            ty::TermKind::Const(ct) => {
1098                if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
1099                    self.delegate.universe_of_ct(vid).unwrap()
1100                } else {
1101                    return false;
1102                }
1103            }
1104        };
1105
1106        struct ContainsTermOrNotNameable<'a, D: SolverDelegate<Interner = I>, I: Interner> {
1107            term: I::Term,
1108            universe_of_term: ty::UniverseIndex,
1109            delegate: &'a D,
1110            cache: HashSet<I::Ty>,
1111        }
1112
1113        impl<D: SolverDelegate<Interner = I>, I: Interner> ContainsTermOrNotNameable<'_, D, I> {
1114            fn check_nameable(&self, universe: ty::UniverseIndex) -> ControlFlow<()> {
1115                if self.universe_of_term.can_name(universe) {
1116                    ControlFlow::Continue(())
1117                } else {
1118                    ControlFlow::Break(())
1119                }
1120            }
1121        }
1122
1123        impl<D: SolverDelegate<Interner = I>, I: Interner> TypeVisitor<I>
1124            for ContainsTermOrNotNameable<'_, D, I>
1125        {
1126            type Result = ControlFlow<()>;
1127            fn visit_ty(&mut self, t: I::Ty) -> Self::Result {
1128                if self.cache.contains(&t) {
1129                    return ControlFlow::Continue(());
1130                }
1131
1132                match t.kind() {
1133                    ty::Infer(ty::TyVar(vid)) => {
1134                        if let ty::TermKind::Ty(term) = self.term.kind()
1135                            && let ty::Infer(ty::TyVar(term_vid)) = term.kind()
1136                            && self.delegate.root_ty_var(vid) == self.delegate.root_ty_var(term_vid)
1137                        {
1138                            return ControlFlow::Break(());
1139                        }
1140
1141                        self.check_nameable(self.delegate.universe_of_ty(vid).unwrap())?;
1142                    }
1143                    ty::Placeholder(p) => self.check_nameable(p.universe())?,
1144                    _ => {
1145                        if t.has_non_region_infer() || t.has_placeholders() {
1146                            t.super_visit_with(self)?
1147                        }
1148                    }
1149                }
1150
1151                assert!(self.cache.insert(t));
1152                ControlFlow::Continue(())
1153            }
1154
1155            fn visit_const(&mut self, c: I::Const) -> Self::Result {
1156                match c.kind() {
1157                    ty::ConstKind::Infer(ty::InferConst::Var(vid)) => {
1158                        if let ty::TermKind::Const(term) = self.term.kind()
1159                            && let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
1160                            && self.delegate.root_const_var(vid)
1161                                == self.delegate.root_const_var(term_vid)
1162                        {
1163                            return ControlFlow::Break(());
1164                        }
1165
1166                        self.check_nameable(self.delegate.universe_of_ct(vid).unwrap())
1167                    }
1168                    ty::ConstKind::Placeholder(p) => self.check_nameable(p.universe()),
1169                    _ => {
1170                        if c.has_non_region_infer() || c.has_placeholders() {
1171                            c.super_visit_with(self)
1172                        } else {
1173                            ControlFlow::Continue(())
1174                        }
1175                    }
1176                }
1177            }
1178
1179            fn visit_predicate(&mut self, p: I::Predicate) -> Self::Result {
1180                if p.has_non_region_infer() || p.has_placeholders() {
1181                    p.super_visit_with(self)
1182                } else {
1183                    ControlFlow::Continue(())
1184                }
1185            }
1186
1187            fn visit_clauses(&mut self, c: I::Clauses) -> Self::Result {
1188                if c.has_non_region_infer() || c.has_placeholders() {
1189                    c.super_visit_with(self)
1190                } else {
1191                    ControlFlow::Continue(())
1192                }
1193            }
1194        }
1195
1196        let mut visitor = ContainsTermOrNotNameable {
1197            delegate: self.delegate,
1198            universe_of_term,
1199            term: goal.predicate.term,
1200            cache: Default::default(),
1201        };
1202        goal.predicate.alias.visit_with(&mut visitor).is_continue()
1203            && goal.param_env.visit_with(&mut visitor).is_continue()
1204    }
1205
1206    pub(super) fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1207        self.delegate.sub_unify_ty_vids_raw(a, b)
1208    }
1209
1210    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1211    pub(super) fn eq<T: Relate<I>>(
1212        &mut self,
1213        param_env: I::ParamEnv,
1214        lhs: T,
1215        rhs: T,
1216    ) -> Result<(), NoSolutionOrRerunNonErased> {
1217        self.relate(param_env, lhs, ty::Variance::Invariant, rhs)
1218    }
1219
1220    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1221    pub(super) fn sub<T: Relate<I>>(
1222        &mut self,
1223        param_env: I::ParamEnv,
1224        sub: T,
1225        sup: T,
1226    ) -> Result<(), NoSolutionOrRerunNonErased> {
1227        self.relate(param_env, sub, ty::Variance::Covariant, sup)
1228    }
1229
1230    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1231    pub(super) fn relate<T: Relate<I>>(
1232        &mut self,
1233        param_env: I::ParamEnv,
1234        lhs: T,
1235        variance: ty::Variance,
1236        rhs: T,
1237    ) -> Result<(), NoSolutionOrRerunNonErased> {
1238        let goals = self.delegate.relate(param_env, lhs, variance, rhs, self.origin_span)?;
1239        for &goal in goals.iter() {
1240            let source = match goal.predicate.kind().skip_binder() {
1241                ty::PredicateKind::Subtype { .. }
1242                | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
1243                    GoalSource::TypeRelating
1244                }
1245                // FIXME(-Znext-solver=coinductive): should these WF goals also be unproductive?
1246                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => GoalSource::Misc,
1247                p => unreachable!("unexpected nested goal in `relate`: {p:?}"),
1248            };
1249            self.add_goal(source, goal)?;
1250        }
1251        Ok(())
1252    }
1253
1254    /// Equates two values returning the nested goals without adding them
1255    /// to the nested goals of the `EvalCtxt`.
1256    ///
1257    /// If possible, try using `eq` instead which automatically handles nested
1258    /// goals correctly.
1259    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1260    pub(super) fn eq_and_get_goals<T: Relate<I>>(
1261        &self,
1262        param_env: I::ParamEnv,
1263        lhs: T,
1264        rhs: T,
1265    ) -> Result<Vec<Goal<I, I::Predicate>>, NoSolution> {
1266        Ok(self.delegate.relate(param_env, lhs, ty::Variance::Invariant, rhs, self.origin_span)?)
1267    }
1268
1269    pub(super) fn instantiate_binder_with_infer<T: TypeFoldable<I> + Copy>(
1270        &self,
1271        value: ty::Binder<I, T>,
1272    ) -> T {
1273        self.delegate.instantiate_binder_with_infer(value)
1274    }
1275
1276    /// `enter_forall_with_assumptions`, but takes `&mut self` and passes it back through
1277    /// the callback since it can't be aliased during the call.
1278    ///
1279    /// The `param_env` is used to *compute* the assumptions of the binder, not *as* the
1280    /// assumptions associated with the binder.
1281    ///
1282    /// FIXME(inherent_associated_types): fix this?
1283    pub(super) fn enter_forall_with_assumptions<T: TypeFoldable<I>, U>(
1284        &mut self,
1285        value: ty::Binder<I, T>,
1286        param_env: I::ParamEnv,
1287        f: impl FnOnce(&mut Self, T) -> U,
1288    ) -> U {
1289        self.delegate.enter_forall_without_assumptions(value, |value| {
1290            let u = self.delegate.universe();
1291            let assumptions = if self.cx().assumptions_on_binders() {
1292                self.region_assumptions_for_placeholders_in_universe(value.clone(), u, param_env)
1293            } else {
1294                None
1295            };
1296            self.delegate.insert_placeholder_assumptions(u, assumptions);
1297            f(self, value)
1298        })
1299    }
1300
1301    pub(super) fn resolve_vars_if_possible<T>(&self, value: T) -> T
1302    where
1303        T: TypeFoldable<I>,
1304    {
1305        self.delegate.resolve_vars_if_possible(value)
1306    }
1307
1308    pub(super) fn shallow_resolve(&self, ty: I::Ty) -> I::Ty {
1309        self.delegate.shallow_resolve(ty)
1310    }
1311
1312    pub(super) fn eager_resolve_region(&self, r: Region<I>) -> Region<I> {
1313        if let ty::ReVar(vid) = r.kind() {
1314            self.delegate.opportunistic_resolve_lt_var(vid)
1315        } else {
1316            r
1317        }
1318    }
1319
1320    pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
1321        let args = self.delegate.fresh_args_for_item(def_id);
1322        for arg in args.iter() {
1323            self.inspect.add_var_value(arg);
1324        }
1325        args
1326    }
1327
1328    pub(super) fn register_solver_region_constraint(&self, c: RegionConstraint<I>) {
1329        self.delegate.register_solver_region_constraint(c, self.origin_span);
1330    }
1331
1332    pub(super) fn register_ty_outlives(&self, ty: I::Ty, lt: Region<I>) {
1333        self.delegate.register_ty_outlives(ty, lt, self.origin_span);
1334    }
1335
1336    pub(super) fn register_region_outlives(
1337        &self,
1338        a: Region<I>,
1339        b: Region<I>,
1340        vis: VisibleForLeakCheck,
1341    ) {
1342        // `'a: 'b` ==> `'b <= 'a`
1343        self.delegate.sub_regions(b, a, vis, self.origin_span);
1344    }
1345
1346    /// Computes the list of goals required for `arg` to be well-formed
1347    pub(super) fn well_formed_goals(
1348        &self,
1349        param_env: I::ParamEnv,
1350        term: I::Term,
1351    ) -> Option<Vec<Goal<I, I::Predicate>>> {
1352        self.delegate.well_formed_goals(param_env, term)
1353    }
1354
1355    pub(super) fn trait_ref_is_knowable(
1356        &mut self,
1357        param_env: I::ParamEnv,
1358        trait_ref: ty::TraitRef<I>,
1359    ) -> Result<bool, NoSolutionOrRerunNonErased> {
1360        let delegate = self.delegate;
1361        let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
1362        coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
1363            .map(|is_knowable| is_knowable.is_ok())
1364    }
1365
1366    pub(super) fn fetch_eligible_assoc_item(
1367        &self,
1368        goal_trait_ref: ty::TraitRef<I>,
1369        trait_assoc_def_id: I::TraitAssocTermId,
1370        impl_def_id: I::ImplId,
1371    ) -> FetchEligibleAssocItemResponse<I> {
1372        self.delegate.fetch_eligible_assoc_item(goal_trait_ref, trait_assoc_def_id, impl_def_id)
1373    }
1374
1375    x;#[instrument(level = "debug", skip(self), ret)]
1376    pub(super) fn register_hidden_type_in_storage(
1377        &mut self,
1378        opaque_type_key: ty::OpaqueTypeKey<I>,
1379        hidden_ty: I::Ty,
1380    ) -> Option<I::Ty> {
1381        self.delegate.register_hidden_type_in_storage(opaque_type_key, hidden_ty, self.origin_span)
1382    }
1383
1384    pub(super) fn add_item_bounds_for_hidden_type(
1385        &mut self,
1386        opaque_def_id: I::OpaqueTyId,
1387        opaque_args: I::GenericArgs,
1388        param_env: I::ParamEnv,
1389        hidden_ty: I::Ty,
1390    ) -> Result<(), NoSolutionOrRerunNonErased> {
1391        let mut goals = Vec::new();
1392        self.delegate.add_item_bounds_for_hidden_type(
1393            opaque_def_id,
1394            opaque_args,
1395            param_env,
1396            hidden_ty,
1397            &mut goals,
1398        );
1399        self.add_goals(GoalSource::AliasWellFormed, goals)?;
1400        Ok(())
1401    }
1402
1403    // Try to evaluate a const and normalize the type of the resulting value, or return `None` if
1404    // the const is too generic. This doesn't mean the const isn't evaluatable, though, and should
1405    // be treated as an ambiguity rather than no-solution.
1406    pub(super) fn evaluate_const(
1407        &mut self,
1408        param_env: I::ParamEnv,
1409        alias_const: ty::AliasConst<I>,
1410    ) -> Result<Option<I::Const>, NoSolutionOrRerunNonErased> {
1411        if self.typing_mode().is_erased_not_coherence() {
1412            match self.opaque_accesses.rerun_always(RerunReason::EvaluateConst)? {}
1413        }
1414
1415        self.delegate.evaluate_const(param_env, alias_const, |ty| {
1416            self.normalize(GoalSource::Misc, param_env, ty)
1417        })
1418    }
1419
1420    pub(super) fn evaluate_const_and_instantiate_projection_term(
1421        &mut self,
1422        param_env: I::ParamEnv,
1423        projection_term: ty::AliasTerm<I>,
1424        expected_term: I::Term,
1425        alias_const: ty::AliasConst<I>,
1426    ) -> QueryResultOrRerunNonErased<I> {
1427        match self.evaluate_const(param_env, alias_const)? {
1428            Some(evaluated) => {
1429                self.eq(param_env, expected_term, evaluated.into())?;
1430                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1431            }
1432            None if self.cx().features().generic_const_args() => {
1433                // HACK(khyperia): calling `resolve_vars_if_possible` here shouldn't be necessary,
1434                // `try_evaluate_const` calls `resolve_vars_if_possible` already. However, we want
1435                // to check `has_non_region_infer` against the type with vars resolved (i.e. check
1436                // if there are vars we failed to resolve), so we need to call it again here.
1437                // Perhaps we could split EvaluateConstErr::HasGenericsOrInfers into HasGenerics and
1438                // HasInfers or something, make evaluate_const return that, and make this branch be
1439                // based on that, rather than checking `has_non_region_infer`.
1440                if self.resolve_vars_if_possible(alias_const).has_non_region_infer() {
1441                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1442                } else {
1443                    // We do not instantiate to the `alias_const` passed in, but rather
1444                    // `goal.predicate.alias`. The `alias_const` passed in might correspond to the `impl`
1445                    // form of a constant (with generic arguments corresponding to the impl block),
1446                    // however, we want to structurally instantiate to the original, non-rebased,
1447                    // trait `Self` form of the constant (with generic arguments being the trait
1448                    // `Self` type).
1449                    self.eq(
1450                        param_env,
1451                        projection_term.to_term(self.cx(), ty::IsRigid::Yes),
1452                        expected_term,
1453                    )?;
1454                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1455                }
1456            }
1457            None => {
1458                // Legacy behavior: always treat as ambiguous
1459                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1460            }
1461        }
1462    }
1463
1464    pub(super) fn is_transmutable(
1465        &mut self,
1466        src: I::Ty,
1467        dst: I::Ty,
1468        assume: I::Const,
1469    ) -> Result<Certainty, NoSolution> {
1470        self.delegate.is_transmutable(dst, src, assume)
1471    }
1472
1473    pub(super) fn replace_bound_vars<T: TypeFoldable<I>>(
1474        &self,
1475        t: T,
1476        universes: &mut Vec<Option<ty::UniverseIndex>>,
1477    ) -> T {
1478        BoundVarReplacer::replace_bound_vars(&**self.delegate, universes, t).0
1479    }
1480
1481    pub(super) fn may_use_unstable_feature(
1482        &mut self,
1483        param_env: I::ParamEnv,
1484        symbol: I::Symbol,
1485    ) -> Result<bool, RerunNonErased> {
1486        if self.typing_mode().is_erased_not_coherence() {
1487            match self.opaque_accesses.rerun_always(RerunReason::MayUseUnstableFeature)? {}
1488        }
1489
1490        Ok(may_use_unstable_feature(&**self.delegate, param_env, symbol))
1491    }
1492
1493    pub(crate) fn opaques_with_sub_unified_hidden_type(
1494        &self,
1495        self_ty: I::Ty,
1496    ) -> Vec<ty::OpaqueAliasTy<I>> {
1497        if let ty::Infer(ty::TyVar(vid)) = self_ty.kind() {
1498            self.delegate.opaques_with_sub_unified_hidden_type(vid)
1499        } else {
1500            ::alloc::vec::Vec::new()vec![]
1501        }
1502    }
1503
1504    /// To return the constraints of a canonical query to the caller, we canonicalize:
1505    ///
1506    /// - `var_values`: a map from bound variables in the canonical goal to
1507    ///   the values inferred while solving the instantiated goal.
1508    /// - `external_constraints`: additional constraints which aren't expressible
1509    ///   using simple unification of inference variables.
1510    ///
1511    /// This takes the `shallow_certainty` which represents whether we're confident
1512    /// that the final result of the current goal only depends on the nested goals.
1513    ///
1514    /// In case this is `Certainty::Maybe`, there may still be additional nested goals
1515    /// or inference constraints required for this candidate to be hold. The candidate
1516    /// always requires all already added constraints and nested goals.
1517    x;#[instrument(level = "trace", skip(self), ret)]
1518    pub(in crate::solve) fn evaluate_added_goals_and_make_canonical_response(
1519        &mut self,
1520        shallow_certainty: Certainty,
1521    ) -> QueryResultOrRerunNonErased<I> {
1522        self.inspect.make_canonical_response(shallow_certainty);
1523
1524        let goals_certainty = self.try_evaluate_added_goals()?;
1525        assert_eq!(
1526            self.tainted,
1527            Ok(()),
1528            "EvalCtxt is tainted -- nested goals may have been dropped in a \
1529            previous call to `try_evaluate_added_goals!`"
1530        );
1531
1532        let goals_certainty = match self.delegate.cx().assumptions_on_binders() {
1533            true => {
1534                let certainty = self.eagerly_handle_placeholders()?;
1535                certainty.and(goals_certainty)
1536            }
1537            false => {
1538                // We only check for leaks from universes which were entered inside
1539                // of the query.
1540                self.delegate.leak_check(self.max_input_universe).map_err(|NoSolution| {
1541                    trace!("failed the leak check");
1542                    NoSolution
1543                })?;
1544
1545                goals_certainty
1546            }
1547        };
1548
1549        let (certainty, normalization_nested_goals) =
1550            match (self.current_goal_kind, shallow_certainty) {
1551                // When normalizing, we've replaced the expected term with an unconstrained
1552                // inference variable. This means that we dropped information which could
1553                // have been important. We handle this by instead returning the nested goals
1554                // to the caller, where they are then handled. We only do so if we do not
1555                // need to recompute the `NormalizesTo` goal afterwards to avoid repeatedly
1556                // uplifting its nested goals. This is the case if the `shallow_certainty` is
1557                // `Certainty::Yes`.
1558                (CurrentGoalKind::ProjectionComputeAssocTermCandidate, Certainty::Yes) => {
1559                    let goals = std::mem::take(&mut self.nested_goals);
1560                    // As we return all ambiguous nested goals, we can ignore the certainty
1561                    // returned by `self.try_evaluate_added_goals()`.
1562                    if goals.is_empty() {
1563                        assert!(matches!(goals_certainty, Certainty::Yes));
1564                    }
1565                    (
1566                        Certainty::Yes,
1567                        NestedNormalizationGoals(
1568                            goals.into_iter().map(|(s, g, _)| (s, g)).collect(),
1569                        ),
1570                    )
1571                }
1572                _ => {
1573                    let certainty = shallow_certainty.and(goals_certainty);
1574                    (certainty, NestedNormalizationGoals::empty())
1575                }
1576            };
1577
1578        if let Certainty::Maybe(
1579            maybe_info @ MaybeInfo {
1580                cause: MaybeCause::Overflow { keep_constraints: false, .. },
1581                opaque_types_jank: _,
1582                stalled_on_coroutines: _,
1583            },
1584        ) = certainty
1585        {
1586            // If we have overflow, it's probable that we're substituting a type
1587            // into itself infinitely and any partial substitutions in the query
1588            // response are probably not useful anyways, so just return an empty
1589            // query response.
1590            //
1591            // This may prevent us from potentially useful inference, e.g.
1592            // 2 candidates, one ambiguous and one overflow, which both
1593            // have the same inference constraints.
1594            //
1595            // Changing this to retain some constraints in the future
1596            // won't be a breaking change, so this is good enough for now.
1597            return Ok(self.make_ambiguous_response_no_constraints(maybe_info));
1598        }
1599
1600        let external_constraints =
1601            self.compute_external_query_constraints(certainty, normalization_nested_goals);
1602        let (var_values, mut external_constraints) =
1603            eager_resolve_vars(&**self.delegate, (self.var_values, external_constraints));
1604
1605        // Remove any trivial or duplicated region constraints once we've resolved regions
1606        let mut unique = HashSet::default();
1607        if let ExternalRegionConstraints::Old(r) = &mut external_constraints.region_constraints {
1608            r.retain(|(outlives, _)| !outlives.is_trivial() && unique.insert(*outlives));
1609        }
1610
1611        let canonical = canonicalize_response(
1612            self.delegate,
1613            self.max_input_universe,
1614            Response {
1615                var_values,
1616                certainty,
1617                external_constraints: self.cx().mk_external_constraints(external_constraints),
1618            },
1619        );
1620
1621        Ok(canonical)
1622    }
1623
1624    /// Constructs a totally unconstrained, ambiguous response to a goal.
1625    ///
1626    /// Take care when using this, since often it's useful to respond with
1627    /// ambiguity but return constrained variables to guide inference.
1628    pub(in crate::solve) fn make_ambiguous_response_no_constraints(
1629        &self,
1630        maybe: MaybeInfo,
1631    ) -> CanonicalResponse<I> {
1632        response_no_constraints_raw(
1633            self.cx(),
1634            self.max_input_universe,
1635            self.var_kinds,
1636            Certainty::Maybe(maybe),
1637        )
1638    }
1639
1640    /// Computes the region constraints and *new* opaque types registered when
1641    /// proving a goal.
1642    ///
1643    /// If an opaque was already constrained before proving this goal, then the
1644    /// external constraints do not need to record that opaque, since if it is
1645    /// further constrained by inference, that will be passed back in the var
1646    /// values.
1647    x;#[instrument(level = "trace", skip(self), ret)]
1648    fn compute_external_query_constraints(
1649        &self,
1650        certainty: Certainty,
1651        normalization_nested_goals: NestedNormalizationGoals<I>,
1652    ) -> ExternalConstraintsData<I> {
1653        // We only return region constraints once the certainty is `Yes`. This
1654        // is necessary as we may drop nested goals on ambiguity, which may result
1655        // in unconstrained inference variables in the region constraints. It also
1656        // prevents us from emitting duplicate region constraints, avoiding some
1657        // unnecessary work. This slightly weakens the leak check in case it uses
1658        // region constraints from an ambiguous nested goal. This is tested in both
1659        // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-5-ambig.rs` and
1660        // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-6-ambig-unify.rs`.
1661        let region_constraints = if self.cx().assumptions_on_binders() {
1662            ExternalRegionConstraints::NextGen(if let Certainty::Yes = certainty {
1663                let constraint = self.delegate.get_solver_region_constraint();
1664                debug_assert_eq!(
1665                    constraint,
1666                    evaluate_solver_constraint(&constraint.clone().canonical_form())
1667                );
1668                constraint
1669            } else {
1670                RegionConstraint::new_true()
1671            })
1672        } else {
1673            ExternalRegionConstraints::Old(if let Certainty::Yes = certainty {
1674                self.delegate.make_deduplicated_region_constraints()
1675            } else {
1676                vec![]
1677            })
1678        };
1679
1680        // We only return *newly defined* opaque types from canonical queries.
1681        //
1682        // Constraints for any existing opaque types are already tracked by changes
1683        // to the `var_values`.
1684        let opaque_types = self
1685            .delegate
1686            .clone_opaque_types_added_since(self.initial_opaque_types_storage_num_entries);
1687
1688        if self.typing_mode().is_erased_not_coherence() {
1689            assert!(opaque_types.is_empty());
1690        }
1691
1692        ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals }
1693    }
1694
1695    pub(super) fn normalize<T: TypeFoldable<I>>(
1696        &mut self,
1697        source: GoalSource,
1698        param_env: I::ParamEnv,
1699        value: ty::Unnormalized<I, T>,
1700    ) -> Result<T, NoSolutionOrRerunNonErased> {
1701        let value = self.delegate.resolve_vars_if_possible(value.skip_normalization());
1702
1703        if !self.cx().renormalize_rigid_aliases() && !value.has_non_rigid_aliases() {
1704            return Ok(value);
1705        }
1706
1707        // To drop the mutable borrow of self early.
1708        let infcx = self.delegate.deref();
1709        let mut folder = NormalizationFolder::new(infcx, ::alloc::vec::Vec::new()vec![], |alias_term| {
1710            let infer_term = self.next_term_infer_of_alias_kind(alias_term);
1711            let pred = ty::ProjectionClause { projection_term: alias_term, term: infer_term };
1712            let goal = Goal::new(self.cx(), param_env, pred);
1713            self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
1714            let GoalEvaluation { goal, certainty, has_changed: _, stalled_on } =
1715                self.evaluate_goal(source, goal, None)?;
1716            let normalization_was_ambiguous = match certainty {
1717                Certainty::Yes => NormalizationWasAmbiguous::No,
1718                Certainty::Maybe(_) => {
1719                    self.nested_goals.push((source, goal, stalled_on));
1720                    NormalizationWasAmbiguous::Yes
1721                }
1722            };
1723
1724            Ok((self.resolve_vars_if_possible(infer_term), normalization_was_ambiguous))
1725        });
1726        value.try_fold_with(&mut folder)
1727    }
1728}
1729
1730#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RerunDecision {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RerunDecision::Yes => "Yes",
                RerunDecision::No => "No",
                RerunDecision::EagerlyPropagateToParent =>
                    "EagerlyPropagateToParent",
            })
    }
}Debug)]
1731enum RerunDecision {
1732    Yes,
1733    No,
1734    EagerlyPropagateToParent,
1735}
1736
1737x;#[tracing::instrument(ret)]
1738fn should_rerun_after_erased_canonicalization<I: Interner>(
1739    AccessedOpaques { reason: _, rerun }: AccessedOpaques<I>,
1740    original_typing_mode: TypingMode<I>,
1741    parent_opaque_types: &[(OpaqueTypeKey<I>, I::Ty)],
1742) -> RerunDecision {
1743    let parent_opaque_def_ids = parent_opaque_types.iter().map(|(key, _)| key.def_id.into());
1744    let opaque_in_storage = |opaques: I::LocalDefIds, def_ids: SmallCopySet<_>| {
1745        if def_ids.as_ref().is_empty() {
1746            RerunDecision::No
1747        } else if opaques
1748            .iter()
1749            .chain(parent_opaque_def_ids)
1750            .any(|opaque| def_ids.as_ref().contains(&opaque))
1751        {
1752            RerunDecision::Yes
1753        } else {
1754            RerunDecision::No
1755        }
1756    };
1757    let any_opaque_has_infer_as_hidden = || {
1758        if parent_opaque_types.iter().any(|(_, ty)| ty.is_ty_var()) {
1759            RerunDecision::Yes
1760        } else {
1761            RerunDecision::No
1762        }
1763    };
1764
1765    match (rerun, original_typing_mode) {
1766        // =============================
1767        (RerunCondition::Never, _) => RerunDecision::No,
1768        // =============================
1769        (_, TypingMode::ErasedNotCoherence(MayBeErased)) => RerunDecision::EagerlyPropagateToParent,
1770        // =============================
1771        // In coherence, we never switch to erased mode, so we will never register anything
1772        // in the rerun state, so we should've taken the first branch of this match
1773        (_, TypingMode::Coherence) => unreachable!(),
1774        // =============================
1775        (RerunCondition::Always, _) => RerunDecision::Yes,
1776        // =============================
1777        (
1778            RerunCondition::OpaqueInStorage(..),
1779            TypingMode::PostAnalysis | TypingMode::Codegen | TypingMode::Reflection,
1780        ) => RerunDecision::Yes,
1781        (
1782            RerunCondition::OpaqueInStorage(defids),
1783            TypingMode::PostBorrowck { defined_opaque_types: opaques }
1784            | TypingMode::Typeck { defining_opaque_types_and_generators: opaques }
1785            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: opaques },
1786        ) => opaque_in_storage(opaques, defids),
1787        // =============================
1788        (RerunCondition::AnyOpaqueHasInferAsHidden, TypingMode::Typeck { .. }) => {
1789            any_opaque_has_infer_as_hidden()
1790        }
1791        (
1792            RerunCondition::AnyOpaqueHasInferAsHidden,
1793            TypingMode::PostBorrowck { .. }
1794            | TypingMode::PostAnalysis
1795            | TypingMode::Codegen
1796            | TypingMode::Reflection
1797            | TypingMode::PostTypeckUntilBorrowck { .. },
1798        ) => RerunDecision::No,
1799        // =============================
1800        (
1801            RerunCondition::OpaqueInStorageOrAnyOpaqueHasInferAsHidden(_),
1802            TypingMode::PostAnalysis | TypingMode::Codegen | TypingMode::Reflection,
1803        ) => RerunDecision::Yes,
1804        (
1805            RerunCondition::OpaqueInStorageOrAnyOpaqueHasInferAsHidden(defids),
1806            TypingMode::Typeck { defining_opaque_types_and_generators: opaques },
1807        ) => {
1808            if let RerunDecision::Yes = any_opaque_has_infer_as_hidden() {
1809                RerunDecision::Yes
1810            } else if let RerunDecision::Yes = opaque_in_storage(opaques, defids) {
1811                RerunDecision::Yes
1812            } else {
1813                RerunDecision::No
1814            }
1815        }
1816        (
1817            RerunCondition::OpaqueInStorageOrAnyOpaqueHasInferAsHidden(defids),
1818            TypingMode::PostBorrowck { defined_opaque_types: opaques }
1819            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: opaques },
1820        ) => opaque_in_storage(opaques, defids),
1821    }
1822}
1823
1824/// Do not call this directly, use the `tcx` query instead.
1825pub fn evaluate_root_goal_for_proof_tree_raw_provider<
1826    D: SolverDelegate<Interner = I>,
1827    I: Interner,
1828>(
1829    cx: I,
1830    canonical_goal: CanonicalInput<I>,
1831    root_depth: usize,
1832) -> (QueryResult<I>, I::Probe, RequiredDepth) {
1833    let mut inspect = inspect::ProofTreeBuilder::new();
1834    let ((canonical_result, accessed_opaques), required_depth) =
1835        SearchGraph::<D>::evaluate_root_goal_for_proof_tree(
1836            cx,
1837            root_depth,
1838            canonical_goal,
1839            &mut inspect,
1840        );
1841    let final_revision = inspect.unwrap();
1842
1843    if !!accessed_opaques.might_rerun() {
    ::core::panicking::panic("assertion failed: !accessed_opaques.might_rerun()")
};assert!(!accessed_opaques.might_rerun());
1844    (canonical_result, cx.mk_probe(final_revision), required_depth)
1845}
1846
1847/// Evaluate a goal to build a proof tree.
1848///
1849/// This is a copy of [EvalCtxt::evaluate_goal_raw] which avoids relying on the
1850/// [EvalCtxt] and uses a separate cache.
1851pub(super) fn evaluate_root_goal_for_proof_tree<D: SolverDelegate<Interner = I>, I: Interner>(
1852    delegate: &D,
1853    goal: Goal<I, I::Predicate>,
1854    origin_span: I::Span,
1855    root_depth: usize,
1856) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
1857    let opaque_types = delegate.clone_opaque_types_lookup_table();
1858    let (goal, opaque_types) = eager_resolve_vars(&**delegate, (goal, opaque_types));
1859    let typing_mode = delegate.typing_mode_raw().assert_not_erased();
1860
1861    let (orig_values, canonical_goal) =
1862        canonicalize_goal(delegate, goal, &opaque_types, typing_mode.into());
1863
1864    let (canonical_result, final_revision, required_depth) =
1865        delegate.cx().evaluate_root_goal_for_proof_tree_raw(canonical_goal, root_depth);
1866
1867    let proof_tree = inspect::GoalEvaluation {
1868        uncanonicalized_goal: goal,
1869        orig_values,
1870        final_revision,
1871        result: canonical_result,
1872        required_depth,
1873    };
1874
1875    let response = match canonical_result {
1876        Err(e) => return (Err(e), proof_tree),
1877        Ok(response) => response,
1878    };
1879
1880    let (normalization_nested_goals, _certainty) = instantiate_and_apply_query_response(
1881        delegate,
1882        goal.param_env,
1883        &proof_tree.orig_values,
1884        response,
1885        origin_span,
1886    );
1887
1888    (Ok(normalization_nested_goals), proof_tree)
1889}