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;
9use rustc_type_ir::relate::Relate;
10use rustc_type_ir::relate::solver_relating::RelateExt;
11use rustc_type_ir::search_graph::{CandidateHeadUsages, LowerAvailableDepth, PathKind};
12use rustc_type_ir::solve::{
13    AccessedOpaques, ExternalRegionConstraints, FetchEligibleAssocItemResponse, MaybeInfo,
14    NoSolutionOrRerunNonErased, OpaqueTypesJank, QueryResultOrRerunNonErased, RerunCondition,
15    RerunNonErased, RerunReason, RerunResultExt, SmallCopyList,
16};
17use rustc_type_ir::{
18    self as ty, CanonicalVarValues, ClauseKind, InferCtxtLike, Interner, MayBeErased,
19    OpaqueTypeKey, PredicateKind, Region, TypeFoldable, TypeSuperVisitable, TypeVisitable,
20    TypeVisitableExt, TypeVisitor, TypingMode, eager_resolve_vars,
21};
22use thin_vec::ThinVec;
23use tracing::{Level, debug, instrument, trace, warn};
24
25use super::has_only_region_constraints;
26use crate::canonical::{
27    canonicalize_goal, canonicalize_response, instantiate_and_apply_query_response,
28    response_no_constraints_raw,
29};
30use crate::coherence;
31use crate::delegate::SolverDelegate;
32use crate::normalize::{NormalizationFolder, NormalizationWasAmbiguous};
33use crate::placeholder::BoundVarReplacer;
34use crate::solve::eval_ctxt::fast_path::{
35    RerunStalled, compute_goal_fast_path, rerunning_stalled_goal_may_make_progress,
36};
37use crate::solve::fast_path::compute_goal_fast_path_cold;
38use crate::solve::search_graph::SearchGraph;
39use crate::solve::ty::may_use_unstable_feature;
40use crate::solve::{
41    CanonicalInput, CanonicalResponse, Certainty, ExternalConstraintsData, FIXPOINT_STEP_LIMIT,
42    Goal, GoalEvaluation, GoalSource, GoalStalledOn, GoalStalledOnOpaques, HasChanged, MaybeCause,
43    NestedNormalizationGoals, NoSolution, QueryInput, QueryResult, Response, SucceededInErased,
44    VisibleForLeakCheck, inspect,
45};
46
47pub mod fast_path;
48mod probe;
49mod solver_region_constraints;
50
51/// The kind of goal we're currently proving.
52///
53/// This has effects on cycle handling handling and on how we compute
54/// query responses, see the variant descriptions for more info.
55#[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)]
56enum CurrentGoalKind {
57    Misc,
58    /// We're proving an trait goal for a coinductive trait, either an auto trait or `Sized`.
59    ///
60    /// These are currently the only goals whose impl where-clauses are considered to be
61    /// productive steps.
62    CoinductiveTrait,
63    // FIXME: Consider renaming `PredicateKind::NormalizesTo` to match with this
64    /// Unlike other goals, `NormalizesTo` goals aren't independent goals but just implementation
65    /// details for handling projections of associated terms. When we encounter a `Projection` goal
66    /// whose `projection_term` is an associated term, we create a `NormalizesTo` goal whose
67    /// expected term is fully unconstrained and evaluate it.
68    ///
69    /// This would weaken inference however, as the nested goals of normalizes-to never get the
70    /// inference constraints from the actual expected term. We just gather candidates from the
71    /// normalizes-to goal and return any ambiguous nested goals of it to the caller (`Projection
72    /// goal`). The caller handle and evaluate them as if they were its own nested goals.
73    ///
74    /// Because of this, evaluating a normalizes-to goal is computing candidates for projection of
75    /// an associated term and it never leaks out of the solver.
76    ProjectionComputeAssocTermCandidate,
77}
78
79impl CurrentGoalKind {
80    fn from_query_input<I: Interner>(cx: I, input: QueryInput<I, I::Predicate>) -> CurrentGoalKind {
81        match input.goal.predicate.kind().skip_binder() {
82            ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
83                if cx.trait_is_coinductive(pred.trait_ref.def_id) {
84                    CurrentGoalKind::CoinductiveTrait
85                } else {
86                    CurrentGoalKind::Misc
87                }
88            }
89            ty::PredicateKind::NormalizesTo(_) => {
90                CurrentGoalKind::ProjectionComputeAssocTermCandidate
91            }
92            _ => CurrentGoalKind::Misc,
93        }
94    }
95}
96
97pub struct EvalCtxt<'a, D, I = <D as SolverDelegate>::Interner>
98where
99    D: SolverDelegate<Interner = I>,
100    I: Interner,
101{
102    /// The inference context that backs (mostly) inference and placeholder terms
103    /// instantiated while solving goals.
104    ///
105    /// NOTE: The `InferCtxt` that backs the `EvalCtxt` is intentionally private,
106    /// because the `InferCtxt` is much more general than `EvalCtxt`. Methods such
107    /// as  `take_registered_region_obligations` can mess up query responses,
108    /// using `At::normalize` is totally wrong, calling `evaluate_root_goal` can
109    /// cause coinductive unsoundness, etc.
110    ///
111    /// Methods that are generally of use for trait solving are *intentionally*
112    /// re-declared through the `EvalCtxt` below, often with cleaner signatures
113    /// since we don't care about things like `ObligationCause`s and `Span`s here.
114    /// If some `InferCtxt` method is missing, please first think defensively about
115    /// the method's compatibility with this solver, or if an existing one does
116    /// the job already.
117    delegate: &'a D,
118
119    /// The variable info for the `var_values`, only used to make an ambiguous response
120    /// with no constraints.
121    var_kinds: I::CanonicalVarKinds,
122
123    /// What kind of goal we're currently computing, see the enum definition
124    /// for more info.
125    current_goal_kind: CurrentGoalKind,
126    pub(super) var_values: CanonicalVarValues<I>,
127
128    /// The highest universe index nameable by the caller.
129    ///
130    /// When we enter a new binder inside of the query we create new universes
131    /// which the caller cannot name. We have to be careful with variables from
132    /// these new universes when creating the query response.
133    ///
134    /// Both because these new universes can prevent us from reaching a fixpoint
135    /// if we have a coinductive cycle and because that's the only way we can return
136    /// new placeholders to the caller.
137    pub(super) max_input_universe: ty::UniverseIndex,
138    /// The opaque types from the canonical input. We only need to return opaque types
139    /// which have been added to the storage while evaluating this goal.
140    pub(super) initial_opaque_types_storage_num_entries:
141        <D::Infcx as InferCtxtLike>::OpaqueTypeStorageEntries,
142
143    pub(super) search_graph: &'a mut SearchGraph<D>,
144
145    nested_goals: Vec<(GoalSource, Goal<I, I::Predicate>, Option<GoalStalledOn<I>>)>,
146
147    pub(super) origin_span: I::Span,
148
149    // Has this `EvalCtxt` errored out with `NoSolution` in `try_evaluate_added_goals`?
150    //
151    // If so, then it can no longer be used to make a canonical query response,
152    // since subsequent calls to `try_evaluate_added_goals` have possibly dropped
153    // ambiguous goals. Instead, a probe needs to be introduced somewhere in the
154    // evaluation code.
155    tainted: Result<(), NoSolution>,
156
157    /// Tracks accesses of opaque types while in [`TypingMode::ErasedNotCoherence`].
158    pub(super) opaque_accesses: AccessedOpaques<I>,
159
160    pub(super) inspect: inspect::EvaluationStepBuilder<D>,
161}
162
163#[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)]
164#[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))]
165pub enum GenerateProofTree {
166    Yes,
167    No,
168}
169
170pub trait SolverDelegateEvalExt: SolverDelegate {
171    /// Evaluates a goal from **outside** of the trait solver.
172    ///
173    /// Using this while inside of the solver is wrong as it uses a new
174    /// search graph which would break cycle detection.
175    fn evaluate_root_goal(
176        &self,
177        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
178        span: <Self::Interner as Interner>::Span,
179        stalled_on: Option<GoalStalledOn<Self::Interner>>,
180    ) -> Result<GoalEvaluation<Self::Interner>, NoSolution>;
181
182    /// Checks whether evaluating `goal` may hold while treating not-yet-defined
183    /// opaque types as being kind of rigid.
184    ///
185    /// See the comment on [OpaqueTypesJank] for more details.
186    fn root_goal_may_hold_opaque_types_jank(
187        &self,
188        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
189    ) -> bool;
190
191    /// Check whether evaluating `goal` with a depth of `root_depth` may
192    /// succeed. This only returns `false` if the goal is guaranteed to
193    /// not hold. In case evaluation overflows and fails with ambiguity this
194    /// returns `true`.
195    ///
196    /// This is only intended to be used as a performance optimization
197    /// in coherence checking.
198    fn root_goal_may_hold_with_depth(
199        &self,
200        root_depth: usize,
201        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
202    ) -> bool;
203
204    // FIXME: This is only exposed because we need to use it in `analyse.rs`
205    // which is not yet uplifted. Once that's done, we should remove this.
206    fn evaluate_root_goal_for_proof_tree(
207        &self,
208        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
209        span: <Self::Interner as Interner>::Span,
210    ) -> (
211        Result<NestedNormalizationGoals<Self::Interner>, NoSolution>,
212        inspect::GoalEvaluation<Self::Interner>,
213    );
214}
215
216impl<D, I> SolverDelegateEvalExt for D
217where
218    D: SolverDelegate<Interner = I>,
219    I: Interner,
220{
221    x;#[instrument(level = "debug", skip(self), ret)]
222    fn evaluate_root_goal(
223        &self,
224        goal: Goal<I, I::Predicate>,
225        span: I::Span,
226        stalled_on: Option<GoalStalledOn<I>>,
227    ) -> Result<GoalEvaluation<I>, NoSolution> {
228        // Run fast paths *before* building an `EvalCtxt`, saving a little bit of time.
229        if let RerunStalled::WontMakeProgress(stalled_certainty) =
230            rerunning_stalled_goal_may_make_progress(self, stalled_on.as_ref())
231        {
232            return Ok(GoalEvaluation {
233                goal,
234                certainty: stalled_certainty,
235                has_changed: HasChanged::No,
236                stalled_on,
237            });
238        }
239
240        // No need to try the fast path if stalled_on is `None`, since we already try the fast path
241        // immediately when adding new goals. If we didn't check `stalled_on` here we'd be trying
242        // the fast path twice for some goals.
243        if stalled_on.is_some()
244            && let Some(res) = compute_goal_fast_path_cold(self, goal, span)
245        {
246            return Ok(res);
247        }
248
249        let mut result = EvalCtxt::enter_root(self, self.cx().recursion_limit(), span, |ecx| {
250            ecx.evaluate_goal_no_fast_paths(GoalSource::Misc, goal)
251        });
252        maybe_evaluate_root_goal_with_higher_recursion_limit(self, goal, span, &mut result);
253
254        match result {
255            Ok(i) => Ok(i),
256            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Err(NoSolution),
257            Err(NoSolutionOrRerunNonErased::RerunNonErased(_)) => {
258                unreachable!("this never happens at the root, we're never in erased mode here");
259            }
260        }
261    }
262
263    x;#[instrument(level = "debug", skip(self), ret)]
264    fn root_goal_may_hold_opaque_types_jank(
265        &self,
266        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
267    ) -> bool {
268        self.probe(|| {
269            EvalCtxt::enter_root(self, self.cx().recursion_limit(), I::Span::dummy(), |ecx| {
270                ecx.evaluate_goal(GoalSource::Misc, goal, None)
271            })
272            .is_ok_and(|r| match r.certainty {
273                Certainty::Yes => true,
274                Certainty::Maybe(MaybeInfo {
275                    cause: _,
276                    opaque_types_jank,
277                    stalled_on_coroutines: _,
278                }) => match opaque_types_jank {
279                    OpaqueTypesJank::AllGood => true,
280                    OpaqueTypesJank::ErrorIfRigidSelfTy => false,
281                },
282            })
283        })
284    }
285
286    fn root_goal_may_hold_with_depth(
287        &self,
288        root_depth: usize,
289        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
290    ) -> bool {
291        self.probe(|| {
292            EvalCtxt::enter_root(self, root_depth, I::Span::dummy(), |ecx| {
293                ecx.evaluate_goal(GoalSource::Misc, goal, None)
294            })
295        })
296        .is_ok()
297    }
298
299    #[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(299u32),
                                    ::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))]
300    fn evaluate_root_goal_for_proof_tree(
301        &self,
302        goal: Goal<I, I::Predicate>,
303        span: I::Span,
304    ) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
305        let mut result =
306            evaluate_root_goal_for_proof_tree(self, goal, span, self.cx().recursion_limit());
307        maybe_evaluate_root_goal_for_proof_tree_with_higher_recursion_limit(
308            self,
309            goal,
310            span,
311            &mut result,
312        );
313        result
314    }
315}
316
317/// The old solver doesn't check depth requirement when looking up cache while the next solver
318/// does so. Thus the next solver is more prone to overflow.
319/// To mitigate breakages, we re-evaluate the overflowed goal with doubled recursion limit
320/// and emit a FCW if it succeeds.
321/// See the doc comment on `RECURSION_DEPTH_EXCEEDING_LIMIT` and #159228 for more details.
322fn maybe_evaluate_root_goal_with_higher_recursion_limit<D, I>(
323    delegate: &D,
324    goal: Goal<I, I::Predicate>,
325    span: I::Span,
326    initial_result: &mut Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased>,
327) where
328    D: SolverDelegate<Interner = I>,
329    I: Interner,
330{
331    if !delegate.enable_next_solver_overflow_fcw() {
332        return;
333    }
334
335    let predicate = match initial_result {
336        Err(_) => return,
337        Ok(goal_evaluation) if !goal_evaluation.certainty.is_overflow() => return,
338        Ok(goal_evaluation) => goal_evaluation.goal.predicate,
339    };
340
341    // Some goals no longer overflow after the stalled infers are resolved.
342    // Thus we don't have to rerun eagerly here.
343    let has_stalled_infers = match predicate.kind().skip_binder() {
344        ty::PredicateKind::Clause(ty::ClauseKind::Projection(projection)) => {
345            projection.projection_term.has_non_region_infer()
346        }
347        _ => predicate.has_non_region_infer(),
348    };
349    if has_stalled_infers {
350        return;
351    }
352
353    let rerun_result = delegate.commit_if_ok(|| {
354        let rerun_result =
355            EvalCtxt::enter_root(delegate, delegate.cx().recursion_limit() * 2, span, |ecx| {
356                ecx.evaluate_goal_no_fast_paths(GoalSource::Misc, goal)
357            });
358        if let Ok(goal_evaluation) = &rerun_result
359            && goal_evaluation.certainty.is_yes()
360        {
361            Ok(rerun_result)
362        } else {
363            Err(())
364        }
365    });
366    if let Ok(rerun_result) = rerun_result {
367        delegate.cx().emit_next_solver_overflow_fcw(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.
374/// To mitigate breakages, we re-evaluate the overflowed goal with doubled recursion limit
375/// and emit a FCW if it succeeds.
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    // Some goals no longer overflow after the stalled infers are resolved.
401    // Thus we don't have to rerun eagerly here.
402    let predicate: I::Predicate = goal_evaluation.uncanonicalized_goal.predicate;
403    let has_stalled_infers = match predicate.kind().skip_binder() {
404        ty::PredicateKind::Clause(ty::ClauseKind::Projection(projection)) => {
405            projection.projection_term.has_non_region_infer()
406        }
407        _ => predicate.has_non_region_infer(),
408    };
409    if has_stalled_infers {
410        return;
411    }
412
413    let rerun_result = delegate.commit_if_ok(|| {
414        let (new_result, new_goal_evaluation) = evaluate_root_goal_for_proof_tree(
415            delegate,
416            goal,
417            span,
418            delegate.cx().recursion_limit() * 2,
419        );
420        if let Ok(response) = &new_goal_evaluation.result
421            && response.value.certainty.is_yes()
422        {
423            Ok((new_result, new_goal_evaluation))
424        } else {
425            Err(())
426        }
427    });
428    if let Ok(rerun_result) = rerun_result {
429        delegate.cx().emit_next_solver_overflow_fcw(predicate, span);
430        *initial_result = rerun_result;
431    }
432}
433
434impl<'a, D, I> EvalCtxt<'a, D>
435where
436    D: SolverDelegate<Interner = I>,
437    I: Interner,
438{
439    pub(super) fn typing_mode(&self) -> TypingMode<I> {
440        self.delegate.typing_mode_raw()
441    }
442
443    /// Computes the `PathKind` for the step from the current goal to the
444    /// nested goal required due to `source`.
445    ///
446    /// See #136824 for a more detailed reasoning for this behavior. We
447    /// consider cycles to be coinductive if they 'step into' a where-clause
448    /// of a coinductive trait. We will likely extend this function in the future
449    /// and will need to clearly document it in the rustc-dev-guide before
450    /// stabilization.
451    pub(super) fn step_kind_for_source(&self, source: GoalSource) -> PathKind {
452        match source {
453            // We treat these goals as unknown for now. It is likely that most miscellaneous
454            // nested goals will be converted to an inductive variant in the future.
455            //
456            // Having unknown cycles is always the safer option, as changing that to either
457            // succeed or hard error is backwards compatible. If we incorrectly treat a cycle
458            // as inductive even though it should not be, it may be unsound during coherence and
459            // fixing it may cause inference breakage or introduce ambiguity.
460            GoalSource::Misc => PathKind::Unknown,
461            GoalSource::NormalizeGoal(path_kind) => path_kind,
462            GoalSource::ImplWhereBound => match self.current_goal_kind {
463                // We currently only consider a cycle coinductive if it steps
464                // into a where-clause of a coinductive trait.
465                CurrentGoalKind::CoinductiveTrait => PathKind::Coinductive,
466                // We probably want to make all traits coinductive in the future,
467                // so we treat cycles involving where-clauses of not-yet coinductive
468                // traits as ambiguous for now.
469                CurrentGoalKind::Misc | CurrentGoalKind::ProjectionComputeAssocTermCandidate => {
470                    PathKind::Unknown
471                }
472            },
473            // Relating types is always unproductive. If we were to map proof trees to
474            // corecursive functions as explained in #136824, relating types never
475            // introduces a constructor which could cause the recursion to be guarded.
476            GoalSource::TypeRelating => PathKind::Inductive,
477            // These goal sources are likely unproductive and can be changed to
478            // `PathKind::Inductive`. Keeping them as unknown until we're confident
479            // about this and have an example where it is necessary.
480            GoalSource::AliasBoundConstCondition | GoalSource::AliasWellFormed => PathKind::Unknown,
481        }
482    }
483
484    /// Creates a root evaluation context and search graph. This should only be
485    /// used from outside of any evaluation, and other methods should be preferred
486    /// over using this manually (such as [`SolverDelegateEvalExt::evaluate_root_goal`]).
487    pub(super) fn enter_root<R>(
488        delegate: &D,
489        root_depth: usize,
490        origin_span: I::Span,
491        f: impl FnOnce(&mut EvalCtxt<'_, D>) -> R,
492    ) -> R {
493        let mut search_graph = SearchGraph::new(root_depth);
494
495        let mut ecx = EvalCtxt {
496            delegate,
497            search_graph: &mut search_graph,
498            nested_goals: Default::default(),
499            inspect: inspect::EvaluationStepBuilder::new_noop(),
500
501            // Only relevant when canonicalizing the response,
502            // which we don't do within this evaluation context.
503            max_input_universe: ty::UniverseIndex::ROOT,
504            initial_opaque_types_storage_num_entries: Default::default(),
505            var_kinds: Default::default(),
506            var_values: CanonicalVarValues::dummy(),
507            current_goal_kind: CurrentGoalKind::Misc,
508            origin_span,
509            tainted: Ok(()),
510            opaque_accesses: AccessedOpaques::default(),
511        };
512        let result = f(&mut ecx);
513        if !ecx.nested_goals.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("root `EvalCtxt` should not have any goals added to it"));
    }
};assert!(
514            ecx.nested_goals.is_empty(),
515            "root `EvalCtxt` should not have any goals added to it"
516        );
517        if !!ecx.opaque_accesses.might_rerun() {
    ::core::panicking::panic("assertion failed: !ecx.opaque_accesses.might_rerun()")
};assert!(!ecx.opaque_accesses.might_rerun());
518        if !search_graph.is_empty() {
    ::core::panicking::panic("assertion failed: search_graph.is_empty()")
};assert!(search_graph.is_empty());
519        result
520    }
521
522    /// Creates a nested evaluation context that shares the same search graph as the
523    /// one passed in. This is suitable for evaluation, granted that the search graph
524    /// has had the nested goal recorded on its stack. This method only be used by
525    /// `search_graph::Delegate::compute_goal`.
526    ///
527    /// This function takes care of setting up the inference context, setting the anchor,
528    /// and registering opaques from the canonicalized input.
529    pub(super) fn enter_canonical<T>(
530        cx: I,
531        search_graph: &'a mut SearchGraph<D>,
532        canonical_input: CanonicalInput<I>,
533        proof_tree_builder: &mut inspect::ProofTreeBuilder<D>,
534        f: impl FnOnce(
535            &mut EvalCtxt<'_, D>,
536            Goal<I, I::Predicate>,
537        ) -> Result<T, NoSolutionOrRerunNonErased>,
538    ) -> (Result<T, NoSolution>, AccessedOpaques<I>) {
539        let (ref delegate, input, var_values) = D::build_with_canonical(cx, &canonical_input);
540        for (key, ty) in input.predefined_opaques_in_body.iter() {
541            let prev = delegate.register_hidden_type_in_storage(key, ty, I::Span::dummy());
542            // It may be possible that two entries in the opaque type storage end up
543            // with the same key after resolving contained inference variables.
544            //
545            // We could put them in the duplicate list but don't have to. The opaques we
546            // encounter here are already tracked in the caller, so there's no need to
547            // also store them here. We'd take them out when computing the query response
548            // and then discard them, as they're already present in the input.
549            //
550            // Ideally we'd drop duplicate opaque type definitions when computing
551            // the canonical input. This is more annoying to implement and may cause a
552            // perf regression, so we do it inside of the query for now.
553            if let Some(prev) = prev {
554                {
    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:554",
                        "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(554u32),
                        ::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`");
555            }
556        }
557
558        let initial_opaque_types_storage_num_entries = delegate.opaque_types_storage_num_entries();
559        if truecfg!(debug_assertions) && delegate.typing_mode_raw().is_erased_not_coherence() {
560            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());
561        }
562
563        let mut ecx = EvalCtxt {
564            delegate,
565            var_kinds: canonical_input.canonical.var_kinds,
566            var_values,
567            current_goal_kind: CurrentGoalKind::from_query_input(cx, input),
568            max_input_universe: canonical_input.canonical.max_universe,
569            initial_opaque_types_storage_num_entries,
570            search_graph,
571            nested_goals: Default::default(),
572            origin_span: I::Span::dummy(),
573            tainted: Ok(()),
574            inspect: proof_tree_builder.new_evaluation_step(var_values),
575            opaque_accesses: AccessedOpaques::default(),
576        };
577
578        let result = f(&mut ecx, input.goal);
579        ecx.inspect.probe_final_state(ecx.delegate, ecx.max_input_universe);
580        proof_tree_builder.finish_evaluation_step(ecx.inspect);
581
582        if canonical_input.typing_mode.0.is_erased_not_coherence() {
583            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());
584        }
585
586        // When creating a query response we clone the opaque type constraints
587        // instead of taking them. This would cause an ICE here, since we have
588        // assertions against dropping an `InferCtxt` without taking opaques.
589        // FIXME: Once we remove support for the old impl we can remove this.
590        // FIXME: Could we make `build_with_canonical` into `enter_with_canonical` and call this at the end?
591        delegate.reset_opaque_types();
592
593        let opaque_accesses = ecx.opaque_accesses;
594        (
595            match result {
596                Ok(i) => Ok(i),
597                Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Err(NoSolution),
598                Err(NoSolutionOrRerunNonErased::RerunNonErased(_)) => {
599                    // Check that the opaque_accesses state mirrors the result we got.
600                    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());
601                    Err(NoSolution)
602                }
603            },
604            opaque_accesses,
605        )
606    }
607
608    pub(super) fn ignore_candidate_head_usages(&mut self, usages: CandidateHeadUsages) {
609        self.search_graph.ignore_candidate_head_usages(usages);
610    }
611
612    /// Recursively evaluates `goal`, returning whether any inference vars have
613    /// been constrained and the certainty of the result.
614    fn evaluate_goal(
615        &mut self,
616        source: GoalSource,
617        goal: Goal<I, I::Predicate>,
618        stalled_on: Option<GoalStalledOn<I>>,
619    ) -> Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased> {
620        if let RerunStalled::WontMakeProgress(stalled_certainty) =
621            rerunning_stalled_goal_may_make_progress(self.delegate, stalled_on.as_ref())
622        {
623            return Ok(GoalEvaluation {
624                goal,
625                certainty: stalled_certainty,
626                has_changed: HasChanged::No,
627                stalled_on,
628            });
629        }
630
631        // No need to try the fast path if stalled_on is `None`, since we already try the fast path
632        // immediately when adding new goals. If we didn't check `stalled_on` here we'd be trying
633        // the fast path twice for some goals.
634        if stalled_on.is_some()
635            && let Some(res) = compute_goal_fast_path_cold(self.delegate, goal, self.origin_span)
636        {
637            return Ok(res);
638        }
639
640        self.evaluate_goal_no_fast_paths(source, goal)
641    }
642
643    // Outlining and `#[cold]` matter here because fast paths make it less likely to get here.
644    #[cold]
645    #[inline(never)]
646    fn evaluate_goal_no_fast_paths(
647        &mut self,
648        source: GoalSource,
649        goal: Goal<I, I::Predicate>,
650    ) -> Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased> {
651        let (normalization_nested_goals, goal_evaluation) =
652            self.evaluate_goal_raw(source, goal, LowerAvailableDepth::Yes)?;
653        if !normalization_nested_goals.is_empty() {
    ::core::panicking::panic("assertion failed: normalization_nested_goals.is_empty()")
};assert!(normalization_nested_goals.is_empty());
654        Ok(goal_evaluation)
655    }
656
657    /// Recursively evaluates `goal`, returning the nested goals in case
658    /// the nested goal is a `NormalizesTo` goal.
659    ///
660    /// As all other goal kinds do not return any nested goals and
661    /// `NormalizesTo` is only used by `Projection`, all other callsites
662    /// should use [`EvalCtxt::evaluate_goal`] which discards that empty
663    /// storage.
664    pub(super) fn evaluate_goal_raw(
665        &mut self,
666        source: GoalSource,
667        goal: Goal<I, I::Predicate>,
668        increase_depth_for_nested: LowerAvailableDepth,
669    ) -> Result<(NestedNormalizationGoals<I>, GoalEvaluation<I>), NoSolutionOrRerunNonErased> {
670        // We only care about one entry per `OpaqueTypeKey` here,
671        // so we only canonicalize the lookup table and ignore
672        // duplicate entries.
673        let opaque_types = self.delegate.clone_opaque_types_lookup_table();
674        let (goal, opaque_types) = eager_resolve_vars(&**self.delegate, (goal, opaque_types));
675        let typing_mode = self.typing_mode();
676        let step_kind = self.step_kind_for_source(source);
677
678        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(678u32),
                        ::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!(
679            Level::DEBUG,
680            "evaluate_goal_raw in typing mode",
681            "{:?} opaques={:?}",
682            typing_mode,
683            opaque_types
684        )
685        .entered();
686
687        let (result, orig_values, canonical_goal, succeeded_in_erased) = 'retry_canonicalize: {
688            let skip_erased_attempt = match typing_mode {
689                TypingMode::Reflection | TypingMode::Coherence => true,
690                TypingMode::Typeck { .. }
691                | TypingMode::PostTypeckUntilBorrowck { .. }
692                | TypingMode::PostBorrowck { .. }
693                | TypingMode::Codegen
694                | TypingMode::PostAnalysis
695                | TypingMode::ErasedNotCoherence(_) => {
696                    let mut skip = false;
697                    if opaque_types.iter().any(|(_, ty)| ty.is_ty_var())
698                        && let PredicateKind::Clause(ClauseKind::Trait(..)) =
699                            goal.predicate.kind().skip_binder()
700                    {
701                        skip = true;
702                    }
703
704                    if let PredicateKind::Clause(ClauseKind::Trait(tr)) =
705                        goal.predicate.kind().skip_binder()
706                        && tr.self_ty().has_coroutines()
707                        && self.cx().trait_is_auto(tr.trait_ref.def_id)
708                    {
709                        // FIXME(#155443): this doesn't make a difference now, but with eager normalization
710                        // it likely will.
711                        // skip_erased_attempt = true;
712                    }
713
714                    skip
715                }
716            };
717
718            if skip_erased_attempt {
719                if typing_mode.is_erased_not_coherence() {
720                    match self.opaque_accesses.rerun_always(RerunReason::SkipErasedAttempt)? {}
721                } else {
722                    {
    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:722",
                        "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(722u32),
                        ::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");
723                }
724            } else {
725                {
    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:725",
                        "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(725u32),
                        ::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:?}");
726
727                let (orig_values, canonical_goal) = canonicalize_goal(
728                    self.delegate,
729                    goal,
730                    &[],
731                    TypingMode::ErasedNotCoherence(MayBeErased),
732                );
733
734                let (canonical_result, accessed_opaques) = self.search_graph.evaluate_goal(
735                    self.cx(),
736                    canonical_goal,
737                    step_kind,
738                    increase_depth_for_nested,
739                    &mut inspect::ProofTreeBuilder::new_noop(),
740                );
741
742                let should_rerun = should_rerun_after_erased_canonicalization(
743                    accessed_opaques,
744                    self.typing_mode(),
745                    &opaque_types,
746                );
747                match should_rerun {
748                    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:748",
                        "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(748u32),
                        ::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"),
749                    RerunDecision::No => {
750                        break 'retry_canonicalize (
751                            canonical_result,
752                            orig_values,
753                            canonical_goal,
754                            SucceededInErased::Yes { accessed_opaques },
755                        );
756                    }
757                    RerunDecision::EagerlyPropagateToParent => {
758                        self.opaque_accesses.update(accessed_opaques)?;
759                        break 'retry_canonicalize (
760                            canonical_result,
761                            orig_values,
762                            canonical_goal,
763                            // If we're propagating up, we should never retry the goal.
764                            // That means `No` is fine to return, it doesn't really matter.
765                            SucceededInErased::No,
766                        );
767                    }
768                }
769            }
770
771            let (orig_values, canonical_goal) =
772                canonicalize_goal(self.delegate, goal, &opaque_types, typing_mode);
773
774            let (canonical_result, accessed_opaques) = self.search_graph.evaluate_goal(
775                self.cx(),
776                canonical_goal,
777                step_kind,
778                increase_depth_for_nested,
779                &mut inspect::ProofTreeBuilder::new_noop(),
780            );
781            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!(
782                !accessed_opaques.might_rerun(),
783                "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:?}"
784            );
785
786            (canonical_result, orig_values, canonical_goal, SucceededInErased::No)
787        };
788
789        {
    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:789",
                        "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(789u32),
                        ::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);
790        let response = match result {
791            Ok(response) => {
792                {
    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:792",
                        "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(792u32),
                        ::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");
793                response
794            }
795            Err(NoSolution) => {
796                {
    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:796",
                        "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(796u32),
                        ::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");
797                return Err(NoSolution.into());
798            }
799        };
800
801        drop(tracing_span);
802
803        let has_changed =
804            if !has_only_region_constraints(response) { HasChanged::Yes } else { HasChanged::No };
805
806        let (normalization_nested_goals, certainty) = instantiate_and_apply_query_response(
807            self.delegate,
808            goal.param_env,
809            &orig_values,
810            response,
811            self.origin_span,
812        );
813
814        // FIXME: We previously had an assert here that checked that recomputing
815        // a goal after applying its constraints did not change its response.
816        //
817        // This assert was removed as it did not hold for goals constraining
818        // an inference variable to a recursive alias, e.g. in
819        // tests/ui/traits/next-solver/overflow/recursive-self-normalization.rs.
820        //
821        // Once we have decided on how to handle trait-system-refactor-initiative#75,
822        // we should re-add an assert here.
823
824        let stalled_on = match certainty {
825            Certainty::Yes => None,
826            Certainty::Maybe { .. } => match has_changed {
827                // FIXME: We could recompute a *new* set of stalled variables by walking
828                // through the orig values, resolving, and computing the root vars of anything
829                // that is not resolved. Only when *these* have changed is it meaningful
830                // to recompute this goal.
831                HasChanged::Yes => None,
832                HasChanged::No => Some(self.build_stalled_on(
833                    canonical_goal,
834                    certainty,
835                    orig_values,
836                    succeeded_in_erased,
837                )),
838            },
839        };
840
841        Ok((
842            normalization_nested_goals,
843            GoalEvaluation { goal, certainty, has_changed, stalled_on },
844        ))
845    }
846
847    fn build_stalled_on(
848        &self,
849        canonical_goal: CanonicalInput<I>,
850        certainty: Certainty,
851        mut stalled_vars: ThinVec<I::GenericArg>,
852        previously_succeeded_in_erased: SucceededInErased<I>,
853    ) -> GoalStalledOn<I> {
854        // Remove the canonicalized universal vars, since we only care about stalled existentials.
855        let mut sub_roots = ThinVec::new();
856        stalled_vars.retain(|arg| match arg.kind() {
857            // Lifetimes can never stall goals.
858            ty::GenericArgKind::Lifetime(_) => false,
859            ty::GenericArgKind::Type(ty) => match ty.kind() {
860                ty::Infer(ty::TyVar(vid)) => {
861                    sub_roots.push(self.delegate.sub_unification_table_root_var(vid));
862                    true
863                }
864                ty::Infer(_) => true,
865                ty::Param(_) | ty::Placeholder(_) => false,
866                _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected orig_value: {0:?}", ty)));
}unreachable!("unexpected orig_value: {ty:?}"),
867            },
868            ty::GenericArgKind::Const(ct) => match ct.kind() {
869                ty::ConstKind::Infer(_) => true,
870                ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(_) => false,
871                _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected orig_value: {0:?}", ct)));
}unreachable!("unexpected orig_value: {ct:?}"),
872            },
873        });
874
875        GoalStalledOn {
876            stalled_vars,
877            sub_roots,
878            stalled_certainty: certainty,
879            opaques: GoalStalledOnOpaques::Yes {
880                num_opaques_in_storage: canonical_goal
881                    .canonical
882                    .value
883                    .predefined_opaques_in_body
884                    .len(),
885                previously_succeeded_in_erased,
886            },
887        }
888    }
889
890    pub(super) fn compute_goal(
891        &mut self,
892        goal: Goal<I, I::Predicate>,
893    ) -> QueryResultOrRerunNonErased<I> {
894        let Goal { param_env, predicate } = goal;
895        let kind = predicate.kind();
896        self.enter_forall_with_assumptions(kind, param_env, |ecx, kind| {
897            Ok(match kind {
898                ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
899                    ecx.compute_trait_goal(Goal { param_env, predicate }).map(|(r, _via)| r)?
900                }
901                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
902                    ecx.compute_host_effect_goal(Goal { param_env, predicate })?
903                }
904                ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) => {
905                    ecx.compute_projection_goal(Goal { param_env, predicate })?
906                }
907                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(predicate)) => {
908                    ecx.compute_type_outlives_goal(Goal { param_env, predicate })?
909                }
910                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(predicate)) => {
911                    ecx.compute_region_outlives_goal(Goal { param_env, predicate })?
912                }
913                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
914                    ecx.compute_const_arg_has_type_goal(Goal { param_env, predicate: (ct, ty) })?
915                }
916                ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
917                    ecx.compute_unstable_feature_goal(param_env, symbol)?
918                }
919                ty::PredicateKind::Subtype(predicate) => {
920                    ecx.compute_subtype_goal(Goal { param_env, predicate })?
921                }
922                ty::PredicateKind::Coerce(predicate) => {
923                    ecx.compute_coerce_goal(Goal { param_env, predicate })?
924                }
925                ty::PredicateKind::DynCompatible(trait_def_id) => {
926                    ecx.compute_dyn_compatible_goal(trait_def_id)?
927                }
928                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
929                    ecx.compute_well_formed_goal(Goal { param_env, predicate: term })?
930                }
931                ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
932                    ecx.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })?
933                }
934                ty::PredicateKind::ConstEquate(_, _) => {
935                    {
    ::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")
936                }
937                ty::PredicateKind::NormalizesTo(predicate) => {
938                    ecx.compute_normalizes_to_goal(Goal { param_env, predicate })?
939                }
940                ty::PredicateKind::Ambiguous => {
941                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)?
942                }
943            })
944        })
945    }
946
947    // Recursively evaluates all the goals added to this `EvalCtxt` to completion, returning
948    // the certainty of all the goals.
949    #[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(949u32),
                                    ::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:964",
                                    "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(964u32),
                                    ::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))]
950    pub(super) fn try_evaluate_added_goals(
951        &mut self,
952    ) -> Result<Certainty, NoSolutionOrRerunNonErased> {
953        for _ in 0..FIXPOINT_STEP_LIMIT {
954            match self.evaluate_added_goals_step().map_err_to_rerun()? {
955                Ok(None) => {}
956                Ok(Some(cert)) => return Ok(cert),
957                Err(NoSolution) => {
958                    self.tainted = Err(NoSolution);
959                    return Err(NoSolution.into());
960                }
961            }
962        }
963
964        debug!("try_evaluate_added_goals: encountered overflow");
965        Ok(Certainty::overflow(false))
966    }
967
968    /// Iterate over all added goals: returning `Ok(Some(_))` in case we can stop rerunning.
969    ///
970    /// Goals for the next step get directly added to the nested goals of the `EvalCtxt`.
971    fn evaluate_added_goals_step(
972        &mut self,
973    ) -> Result<Option<Certainty>, NoSolutionOrRerunNonErased> {
974        // If this loop did not result in any progress, what's our final certainty.
975        let mut unchanged_certainty = Some(Certainty::Yes);
976        // This mem::take seems super inefficient, given that we push to it again later.
977        // Despite that, replacing it has no effect on performance. We tried.
978        // (https://github.com/rust-lang/rust/pull/158126)
979        for (source, goal, stalled_on) in mem::take(&mut self.nested_goals) {
980            // We never handle `NormalizesTo` as a nested goal
981            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!(
982                goal.predicate.kind().skip_binder(),
983                PredicateKind::NormalizesTo(_)
984            ));
985
986            let GoalEvaluation { goal, certainty, has_changed, stalled_on } =
987                self.evaluate_goal(source, goal, stalled_on)?;
988            if has_changed == HasChanged::Yes {
989                unchanged_certainty = None;
990            }
991
992            match certainty {
993                Certainty::Yes => {}
994                Certainty::Maybe { .. } => {
995                    self.nested_goals.push((source, goal, stalled_on));
996                    unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
997                }
998            }
999        }
1000
1001        Ok(unchanged_certainty)
1002    }
1003
1004    /// Record impl args in the proof tree for later access by `InspectCandidate`.
1005    pub(crate) fn record_impl_args(&mut self, impl_args: I::GenericArgs) {
1006        self.inspect.record_impl_args(self.delegate, self.max_input_universe, impl_args)
1007    }
1008
1009    pub(super) fn cx(&self) -> I {
1010        self.delegate.cx()
1011    }
1012
1013    #[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(1013u32),
                                    ::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))]
1014    pub(super) fn add_goal(
1015        &mut self,
1016        source: GoalSource,
1017        mut goal: Goal<I, I::Predicate>,
1018    ) -> Result<(), NoSolutionOrRerunNonErased> {
1019        goal.predicate = self.normalize(
1020            GoalSource::NormalizeGoal(self.step_kind_for_source(source)),
1021            goal.param_env,
1022            ty::Unnormalized::new_wip(goal.predicate),
1023        )?;
1024        self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
1025
1026        if let Some(GoalEvaluation { goal, certainty, has_changed: _, stalled_on }) =
1027            compute_goal_fast_path(self.delegate, goal, self.origin_span)
1028        {
1029            match certainty {
1030                // We're done here
1031                Certainty::Yes => {}
1032                Certainty::Maybe(_) => {
1033                    self.nested_goals.push((source, goal, stalled_on));
1034                }
1035            }
1036        } else {
1037            self.nested_goals.push((source, goal, None));
1038        }
1039        Ok(())
1040    }
1041
1042    #[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(1042u32),
                                    ::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))]
1043    pub(super) fn add_goals(
1044        &mut self,
1045        source: GoalSource,
1046        goals: impl IntoIterator<Item = Goal<I, I::Predicate>>,
1047    ) -> Result<(), NoSolutionOrRerunNonErased> {
1048        for goal in goals {
1049            self.add_goal(source, goal)?;
1050        }
1051        Ok(())
1052    }
1053
1054    pub(super) fn next_region_var(&mut self) -> Region<I> {
1055        let region = self.delegate.next_region_infer();
1056        self.inspect.add_var_value(region);
1057        region
1058    }
1059
1060    pub(super) fn next_ty_infer(&mut self) -> I::Ty {
1061        let ty = self.delegate.next_ty_infer();
1062        self.inspect.add_var_value(ty);
1063        ty
1064    }
1065
1066    pub(super) fn next_const_infer(&mut self) -> I::Const {
1067        let ct = self.delegate.next_const_infer();
1068        self.inspect.add_var_value(ct);
1069        ct
1070    }
1071
1072    /// Returns a ty infer or a const infer depending on whether `kind` is a `Ty` or `Const`.
1073    /// If `kind` is an integer inference variable this will still return a ty infer var.
1074    pub(super) fn next_term_infer_of_alias_kind(
1075        &mut self,
1076        alias_term: ty::AliasTerm<I>,
1077    ) -> I::Term {
1078        match alias_term.kind {
1079            ty::AliasTermKind::ProjectionTy { .. }
1080            | ty::AliasTermKind::InherentTy { .. }
1081            | ty::AliasTermKind::OpaqueTy { .. }
1082            | ty::AliasTermKind::FreeTy { .. } => self.next_ty_infer().into(),
1083            ty::AliasTermKind::FreeConst { .. }
1084            | ty::AliasTermKind::InherentConst { .. }
1085            | ty::AliasTermKind::AnonConst { .. }
1086            | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_infer().into(),
1087        }
1088    }
1089
1090    /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
1091    ///
1092    /// This is the case if the `term` does not occur in any other part of the predicate
1093    /// and is able to name all other placeholder and inference variables.
1094    x;#[instrument(level = "trace", skip(self), ret)]
1095    pub(super) fn term_is_fully_unconstrained(&self, goal: Goal<I, ty::NormalizesTo<I>>) -> bool {
1096        let universe_of_term = match goal.predicate.term.kind() {
1097            ty::TermKind::Ty(ty) => {
1098                if let ty::Infer(ty::TyVar(vid)) = ty.kind() {
1099                    self.delegate.universe_of_ty(vid).unwrap()
1100                } else {
1101                    return false;
1102                }
1103            }
1104            ty::TermKind::Const(ct) => {
1105                if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
1106                    self.delegate.universe_of_ct(vid).unwrap()
1107                } else {
1108                    return false;
1109                }
1110            }
1111        };
1112
1113        struct ContainsTermOrNotNameable<'a, D: SolverDelegate<Interner = I>, I: Interner> {
1114            term: I::Term,
1115            universe_of_term: ty::UniverseIndex,
1116            delegate: &'a D,
1117            cache: HashSet<I::Ty>,
1118        }
1119
1120        impl<D: SolverDelegate<Interner = I>, I: Interner> ContainsTermOrNotNameable<'_, D, I> {
1121            fn check_nameable(&self, universe: ty::UniverseIndex) -> ControlFlow<()> {
1122                if self.universe_of_term.can_name(universe) {
1123                    ControlFlow::Continue(())
1124                } else {
1125                    ControlFlow::Break(())
1126                }
1127            }
1128        }
1129
1130        impl<D: SolverDelegate<Interner = I>, I: Interner> TypeVisitor<I>
1131            for ContainsTermOrNotNameable<'_, D, I>
1132        {
1133            type Result = ControlFlow<()>;
1134            fn visit_ty(&mut self, t: I::Ty) -> Self::Result {
1135                if self.cache.contains(&t) {
1136                    return ControlFlow::Continue(());
1137                }
1138
1139                match t.kind() {
1140                    ty::Infer(ty::TyVar(vid)) => {
1141                        if let ty::TermKind::Ty(term) = self.term.kind()
1142                            && let ty::Infer(ty::TyVar(term_vid)) = term.kind()
1143                            && self.delegate.root_ty_var(vid) == self.delegate.root_ty_var(term_vid)
1144                        {
1145                            return ControlFlow::Break(());
1146                        }
1147
1148                        self.check_nameable(self.delegate.universe_of_ty(vid).unwrap())?;
1149                    }
1150                    ty::Placeholder(p) => self.check_nameable(p.universe())?,
1151                    _ => {
1152                        if t.has_non_region_infer() || t.has_placeholders() {
1153                            t.super_visit_with(self)?
1154                        }
1155                    }
1156                }
1157
1158                assert!(self.cache.insert(t));
1159                ControlFlow::Continue(())
1160            }
1161
1162            fn visit_const(&mut self, c: I::Const) -> Self::Result {
1163                match c.kind() {
1164                    ty::ConstKind::Infer(ty::InferConst::Var(vid)) => {
1165                        if let ty::TermKind::Const(term) = self.term.kind()
1166                            && let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
1167                            && self.delegate.root_const_var(vid)
1168                                == self.delegate.root_const_var(term_vid)
1169                        {
1170                            return ControlFlow::Break(());
1171                        }
1172
1173                        self.check_nameable(self.delegate.universe_of_ct(vid).unwrap())
1174                    }
1175                    ty::ConstKind::Placeholder(p) => self.check_nameable(p.universe()),
1176                    _ => {
1177                        if c.has_non_region_infer() || c.has_placeholders() {
1178                            c.super_visit_with(self)
1179                        } else {
1180                            ControlFlow::Continue(())
1181                        }
1182                    }
1183                }
1184            }
1185
1186            fn visit_predicate(&mut self, p: I::Predicate) -> Self::Result {
1187                if p.has_non_region_infer() || p.has_placeholders() {
1188                    p.super_visit_with(self)
1189                } else {
1190                    ControlFlow::Continue(())
1191                }
1192            }
1193
1194            fn visit_clauses(&mut self, c: I::Clauses) -> Self::Result {
1195                if c.has_non_region_infer() || c.has_placeholders() {
1196                    c.super_visit_with(self)
1197                } else {
1198                    ControlFlow::Continue(())
1199                }
1200            }
1201        }
1202
1203        let mut visitor = ContainsTermOrNotNameable {
1204            delegate: self.delegate,
1205            universe_of_term,
1206            term: goal.predicate.term,
1207            cache: Default::default(),
1208        };
1209        goal.predicate.alias.visit_with(&mut visitor).is_continue()
1210            && goal.param_env.visit_with(&mut visitor).is_continue()
1211    }
1212
1213    pub(super) fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1214        self.delegate.sub_unify_ty_vids_raw(a, b)
1215    }
1216
1217    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1218    pub(super) fn eq<T: Relate<I>>(
1219        &mut self,
1220        param_env: I::ParamEnv,
1221        lhs: T,
1222        rhs: T,
1223    ) -> Result<(), NoSolutionOrRerunNonErased> {
1224        self.relate(param_env, lhs, ty::Variance::Invariant, rhs)
1225    }
1226
1227    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1228    pub(super) fn sub<T: Relate<I>>(
1229        &mut self,
1230        param_env: I::ParamEnv,
1231        sub: T,
1232        sup: T,
1233    ) -> Result<(), NoSolutionOrRerunNonErased> {
1234        self.relate(param_env, sub, ty::Variance::Covariant, sup)
1235    }
1236
1237    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1238    pub(super) fn relate<T: Relate<I>>(
1239        &mut self,
1240        param_env: I::ParamEnv,
1241        lhs: T,
1242        variance: ty::Variance,
1243        rhs: T,
1244    ) -> Result<(), NoSolutionOrRerunNonErased> {
1245        let goals = self.delegate.relate(param_env, lhs, variance, rhs, self.origin_span)?;
1246        for &goal in goals.iter() {
1247            let source = match goal.predicate.kind().skip_binder() {
1248                ty::PredicateKind::Subtype { .. }
1249                | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
1250                    GoalSource::TypeRelating
1251                }
1252                // FIXME(-Znext-solver=coinductive): should these WF goals also be unproductive?
1253                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => GoalSource::Misc,
1254                p => unreachable!("unexpected nested goal in `relate`: {p:?}"),
1255            };
1256            self.add_goal(source, goal)?;
1257        }
1258        Ok(())
1259    }
1260
1261    /// Equates two values returning the nested goals without adding them
1262    /// to the nested goals of the `EvalCtxt`.
1263    ///
1264    /// If possible, try using `eq` instead which automatically handles nested
1265    /// goals correctly.
1266    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1267    pub(super) fn eq_and_get_goals<T: Relate<I>>(
1268        &self,
1269        param_env: I::ParamEnv,
1270        lhs: T,
1271        rhs: T,
1272    ) -> Result<Vec<Goal<I, I::Predicate>>, NoSolution> {
1273        Ok(self.delegate.relate(param_env, lhs, ty::Variance::Invariant, rhs, self.origin_span)?)
1274    }
1275
1276    pub(super) fn instantiate_binder_with_infer<T: TypeFoldable<I> + Copy>(
1277        &self,
1278        value: ty::Binder<I, T>,
1279    ) -> T {
1280        self.delegate.instantiate_binder_with_infer(value)
1281    }
1282
1283    /// `enter_forall_with_assumptions`, but takes `&mut self` and passes it back through
1284    /// the callback since it can't be aliased during the call.
1285    ///
1286    /// The `param_env` is used to *compute* the assumptions of the binder, not *as* the
1287    /// assumptions associated with the binder.
1288    ///
1289    /// FIXME(inherent_associated_types): fix this?
1290    pub(super) fn enter_forall_with_assumptions<T: TypeFoldable<I>, U>(
1291        &mut self,
1292        value: ty::Binder<I, T>,
1293        param_env: I::ParamEnv,
1294        f: impl FnOnce(&mut Self, T) -> U,
1295    ) -> U {
1296        self.delegate.enter_forall_without_assumptions(value, |value| {
1297            let u = self.delegate.universe();
1298            let assumptions = if self.cx().assumptions_on_binders() {
1299                self.region_assumptions_for_placeholders_in_universe(value.clone(), u, param_env)
1300            } else {
1301                None
1302            };
1303            self.delegate.insert_placeholder_assumptions(u, assumptions);
1304            f(self, value)
1305        })
1306    }
1307
1308    pub(super) fn resolve_vars_if_possible<T>(&self, value: T) -> T
1309    where
1310        T: TypeFoldable<I>,
1311    {
1312        self.delegate.resolve_vars_if_possible(value)
1313    }
1314
1315    pub(super) fn shallow_resolve(&self, ty: I::Ty) -> I::Ty {
1316        self.delegate.shallow_resolve(ty)
1317    }
1318
1319    pub(super) fn eager_resolve_region(&self, r: Region<I>) -> Region<I> {
1320        if let ty::ReVar(vid) = r.kind() {
1321            self.delegate.opportunistic_resolve_lt_var(vid)
1322        } else {
1323            r
1324        }
1325    }
1326
1327    pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
1328        let args = self.delegate.fresh_args_for_item(def_id);
1329        for arg in args.iter() {
1330            self.inspect.add_var_value(arg);
1331        }
1332        args
1333    }
1334
1335    pub(super) fn register_solver_region_constraint(&self, c: RegionConstraint<I>) {
1336        self.delegate.register_solver_region_constraint(c);
1337    }
1338
1339    pub(super) fn register_ty_outlives(&self, ty: I::Ty, lt: Region<I>) {
1340        self.delegate.register_ty_outlives(ty, lt, self.origin_span);
1341    }
1342
1343    pub(super) fn register_region_outlives(
1344        &self,
1345        a: Region<I>,
1346        b: Region<I>,
1347        vis: VisibleForLeakCheck,
1348    ) {
1349        // `'a: 'b` ==> `'b <= 'a`
1350        self.delegate.sub_regions(b, a, vis, self.origin_span);
1351    }
1352
1353    /// Computes the list of goals required for `arg` to be well-formed
1354    pub(super) fn well_formed_goals(
1355        &self,
1356        param_env: I::ParamEnv,
1357        term: I::Term,
1358    ) -> Option<Vec<Goal<I, I::Predicate>>> {
1359        self.delegate.well_formed_goals(param_env, term)
1360    }
1361
1362    pub(super) fn trait_ref_is_knowable(
1363        &mut self,
1364        param_env: I::ParamEnv,
1365        trait_ref: ty::TraitRef<I>,
1366    ) -> Result<bool, NoSolutionOrRerunNonErased> {
1367        let delegate = self.delegate;
1368        let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
1369        coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
1370            .map(|is_knowable| is_knowable.is_ok())
1371    }
1372
1373    pub(super) fn fetch_eligible_assoc_item(
1374        &self,
1375        goal_trait_ref: ty::TraitRef<I>,
1376        trait_assoc_def_id: I::TraitAssocTermId,
1377        impl_def_id: I::ImplId,
1378    ) -> FetchEligibleAssocItemResponse<I> {
1379        self.delegate.fetch_eligible_assoc_item(goal_trait_ref, trait_assoc_def_id, impl_def_id)
1380    }
1381
1382    x;#[instrument(level = "debug", skip(self), ret)]
1383    pub(super) fn register_hidden_type_in_storage(
1384        &mut self,
1385        opaque_type_key: ty::OpaqueTypeKey<I>,
1386        hidden_ty: I::Ty,
1387    ) -> Option<I::Ty> {
1388        self.delegate.register_hidden_type_in_storage(opaque_type_key, hidden_ty, self.origin_span)
1389    }
1390
1391    pub(super) fn add_item_bounds_for_hidden_type(
1392        &mut self,
1393        opaque_def_id: I::OpaqueTyId,
1394        opaque_args: I::GenericArgs,
1395        param_env: I::ParamEnv,
1396        hidden_ty: I::Ty,
1397    ) -> Result<(), NoSolutionOrRerunNonErased> {
1398        let mut goals = Vec::new();
1399        self.delegate.add_item_bounds_for_hidden_type(
1400            opaque_def_id,
1401            opaque_args,
1402            param_env,
1403            hidden_ty,
1404            &mut goals,
1405        );
1406        self.add_goals(GoalSource::AliasWellFormed, goals)?;
1407        Ok(())
1408    }
1409
1410    // Try to evaluate a const, or return `None` if the const is too generic.
1411    // This doesn't mean the const isn't evaluatable, though, and should be treated
1412    // as an ambiguity rather than no-solution.
1413    pub(super) fn evaluate_const(
1414        &mut self,
1415        param_env: I::ParamEnv,
1416        alias_const: ty::AliasConst<I>,
1417    ) -> Result<Option<I::Const>, RerunNonErased> {
1418        if self.typing_mode().is_erased_not_coherence() {
1419            match self.opaque_accesses.rerun_always(RerunReason::EvaluateConst)? {}
1420        }
1421
1422        Ok(self.delegate.evaluate_const(param_env, alias_const))
1423    }
1424
1425    pub(super) fn evaluate_const_and_instantiate_projection_term(
1426        &mut self,
1427        param_env: I::ParamEnv,
1428        projection_term: ty::AliasTerm<I>,
1429        expected_term: I::Term,
1430        alias_const: ty::AliasConst<I>,
1431    ) -> QueryResultOrRerunNonErased<I> {
1432        match self.evaluate_const(param_env, alias_const)? {
1433            Some(evaluated) => {
1434                self.eq(param_env, expected_term, evaluated.into())?;
1435                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1436            }
1437            None if self.cx().features().generic_const_args() => {
1438                // HACK(khyperia): calling `resolve_vars_if_possible` here shouldn't be necessary,
1439                // `try_evaluate_const` calls `resolve_vars_if_possible` already. However, we want
1440                // to check `has_non_region_infer` against the type with vars resolved (i.e. check
1441                // if there are vars we failed to resolve), so we need to call it again here.
1442                // Perhaps we could split EvaluateConstErr::HasGenericsOrInfers into HasGenerics and
1443                // HasInfers or something, make evaluate_const return that, and make this branch be
1444                // based on that, rather than checking `has_non_region_infer`.
1445                if self.resolve_vars_if_possible(alias_const).has_non_region_infer() {
1446                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1447                } else {
1448                    // We do not instantiate to the `alias_const` passed in, but rather
1449                    // `goal.predicate.alias`. The `alias_const` passed in might correspond to the `impl`
1450                    // form of a constant (with generic arguments corresponding to the impl block),
1451                    // however, we want to structurally instantiate to the original, non-rebased,
1452                    // trait `Self` form of the constant (with generic arguments being the trait
1453                    // `Self` type).
1454                    self.eq(
1455                        param_env,
1456                        projection_term.to_term(self.cx(), ty::IsRigid::Yes),
1457                        expected_term,
1458                    )?;
1459                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1460                }
1461            }
1462            None => {
1463                // Legacy behavior: always treat as ambiguous
1464                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1465            }
1466        }
1467    }
1468
1469    pub(super) fn is_transmutable(
1470        &mut self,
1471        src: I::Ty,
1472        dst: I::Ty,
1473        assume: I::Const,
1474    ) -> Result<Certainty, NoSolution> {
1475        self.delegate.is_transmutable(dst, src, assume)
1476    }
1477
1478    pub(super) fn replace_bound_vars<T: TypeFoldable<I>>(
1479        &self,
1480        t: T,
1481        universes: &mut Vec<Option<ty::UniverseIndex>>,
1482    ) -> T {
1483        BoundVarReplacer::replace_bound_vars(&**self.delegate, universes, t).0
1484    }
1485
1486    pub(super) fn may_use_unstable_feature(
1487        &mut self,
1488        param_env: I::ParamEnv,
1489        symbol: I::Symbol,
1490    ) -> Result<bool, RerunNonErased> {
1491        if self.typing_mode().is_erased_not_coherence() {
1492            match self.opaque_accesses.rerun_always(RerunReason::MayUseUnstableFeature)? {}
1493        }
1494
1495        Ok(may_use_unstable_feature(&**self.delegate, param_env, symbol))
1496    }
1497
1498    pub(crate) fn opaques_with_sub_unified_hidden_type(
1499        &self,
1500        self_ty: I::Ty,
1501    ) -> Vec<ty::OpaqueAliasTy<I>> {
1502        if let ty::Infer(ty::TyVar(vid)) = self_ty.kind() {
1503            self.delegate.opaques_with_sub_unified_hidden_type(vid)
1504        } else {
1505            ::alloc::vec::Vec::new()vec![]
1506        }
1507    }
1508
1509    /// To return the constraints of a canonical query to the caller, we canonicalize:
1510    ///
1511    /// - `var_values`: a map from bound variables in the canonical goal to
1512    ///   the values inferred while solving the instantiated goal.
1513    /// - `external_constraints`: additional constraints which aren't expressible
1514    ///   using simple unification of inference variables.
1515    ///
1516    /// This takes the `shallow_certainty` which represents whether we're confident
1517    /// that the final result of the current goal only depends on the nested goals.
1518    ///
1519    /// In case this is `Certainty::Maybe`, there may still be additional nested goals
1520    /// or inference constraints required for this candidate to be hold. The candidate
1521    /// always requires all already added constraints and nested goals.
1522    x;#[instrument(level = "trace", skip(self), ret)]
1523    pub(in crate::solve) fn evaluate_added_goals_and_make_canonical_response(
1524        &mut self,
1525        shallow_certainty: Certainty,
1526    ) -> QueryResultOrRerunNonErased<I> {
1527        self.inspect.make_canonical_response(shallow_certainty);
1528
1529        let goals_certainty = self.try_evaluate_added_goals()?;
1530        assert_eq!(
1531            self.tainted,
1532            Ok(()),
1533            "EvalCtxt is tainted -- nested goals may have been dropped in a \
1534            previous call to `try_evaluate_added_goals!`"
1535        );
1536
1537        let goals_certainty = match self.delegate.cx().assumptions_on_binders() {
1538            true => {
1539                let certainty = self.eagerly_handle_placeholders()?;
1540                certainty.and(goals_certainty)
1541            }
1542            false => {
1543                // We only check for leaks from universes which were entered inside
1544                // of the query.
1545                self.delegate.leak_check(self.max_input_universe).map_err(|NoSolution| {
1546                    trace!("failed the leak check");
1547                    NoSolution
1548                })?;
1549
1550                goals_certainty
1551            }
1552        };
1553
1554        let (certainty, normalization_nested_goals) =
1555            match (self.current_goal_kind, shallow_certainty) {
1556                // When normalizing, we've replaced the expected term with an unconstrained
1557                // inference variable. This means that we dropped information which could
1558                // have been important. We handle this by instead returning the nested goals
1559                // to the caller, where they are then handled. We only do so if we do not
1560                // need to recompute the `NormalizesTo` goal afterwards to avoid repeatedly
1561                // uplifting its nested goals. This is the case if the `shallow_certainty` is
1562                // `Certainty::Yes`.
1563                (CurrentGoalKind::ProjectionComputeAssocTermCandidate, Certainty::Yes) => {
1564                    let goals = std::mem::take(&mut self.nested_goals);
1565                    // As we return all ambiguous nested goals, we can ignore the certainty
1566                    // returned by `self.try_evaluate_added_goals()`.
1567                    if goals.is_empty() {
1568                        assert!(matches!(goals_certainty, Certainty::Yes));
1569                    }
1570                    (
1571                        Certainty::Yes,
1572                        NestedNormalizationGoals(
1573                            goals.into_iter().map(|(s, g, _)| (s, g)).collect(),
1574                        ),
1575                    )
1576                }
1577                _ => {
1578                    let certainty = shallow_certainty.and(goals_certainty);
1579                    (certainty, NestedNormalizationGoals::empty())
1580                }
1581            };
1582
1583        if let Certainty::Maybe(
1584            maybe_info @ MaybeInfo {
1585                cause: MaybeCause::Overflow { keep_constraints: false, .. },
1586                opaque_types_jank: _,
1587                stalled_on_coroutines: _,
1588            },
1589        ) = certainty
1590        {
1591            // If we have overflow, it's probable that we're substituting a type
1592            // into itself infinitely and any partial substitutions in the query
1593            // response are probably not useful anyways, so just return an empty
1594            // query response.
1595            //
1596            // This may prevent us from potentially useful inference, e.g.
1597            // 2 candidates, one ambiguous and one overflow, which both
1598            // have the same inference constraints.
1599            //
1600            // Changing this to retain some constraints in the future
1601            // won't be a breaking change, so this is good enough for now.
1602            return Ok(self.make_ambiguous_response_no_constraints(maybe_info));
1603        }
1604
1605        let external_constraints =
1606            self.compute_external_query_constraints(certainty, normalization_nested_goals);
1607        let (var_values, mut external_constraints) =
1608            eager_resolve_vars(&**self.delegate, (self.var_values, external_constraints));
1609
1610        // Remove any trivial or duplicated region constraints once we've resolved regions
1611        let mut unique = HashSet::default();
1612        if let ExternalRegionConstraints::Old(r) = &mut external_constraints.region_constraints {
1613            r.retain(|(outlives, _)| !outlives.is_trivial() && unique.insert(*outlives));
1614        }
1615
1616        let canonical = canonicalize_response(
1617            self.delegate,
1618            self.max_input_universe,
1619            Response {
1620                var_values,
1621                certainty,
1622                external_constraints: self.cx().mk_external_constraints(external_constraints),
1623            },
1624        );
1625
1626        Ok(canonical)
1627    }
1628
1629    /// Constructs a totally unconstrained, ambiguous response to a goal.
1630    ///
1631    /// Take care when using this, since often it's useful to respond with
1632    /// ambiguity but return constrained variables to guide inference.
1633    pub(in crate::solve) fn make_ambiguous_response_no_constraints(
1634        &self,
1635        maybe: MaybeInfo,
1636    ) -> CanonicalResponse<I> {
1637        response_no_constraints_raw(
1638            self.cx(),
1639            self.max_input_universe,
1640            self.var_kinds,
1641            Certainty::Maybe(maybe),
1642        )
1643    }
1644
1645    /// Computes the region constraints and *new* opaque types registered when
1646    /// proving a goal.
1647    ///
1648    /// If an opaque was already constrained before proving this goal, then the
1649    /// external constraints do not need to record that opaque, since if it is
1650    /// further constrained by inference, that will be passed back in the var
1651    /// values.
1652    x;#[instrument(level = "trace", skip(self), ret)]
1653    fn compute_external_query_constraints(
1654        &self,
1655        certainty: Certainty,
1656        normalization_nested_goals: NestedNormalizationGoals<I>,
1657    ) -> ExternalConstraintsData<I> {
1658        // We only return region constraints once the certainty is `Yes`. This
1659        // is necessary as we may drop nested goals on ambiguity, which may result
1660        // in unconstrained inference variables in the region constraints. It also
1661        // prevents us from emitting duplicate region constraints, avoiding some
1662        // unnecessary work. This slightly weakens the leak check in case it uses
1663        // region constraints from an ambiguous nested goal. This is tested in both
1664        // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-5-ambig.rs` and
1665        // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-6-ambig-unify.rs`.
1666        let region_constraints = if self.cx().assumptions_on_binders() {
1667            ExternalRegionConstraints::NextGen(if let Certainty::Yes = certainty {
1668                self.delegate.get_solver_region_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::ProjectionPredicate { 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: SmallCopyList<_>| {
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) {
1833    let mut inspect = inspect::ProofTreeBuilder::new();
1834    let (canonical_result, accessed_opaques) = SearchGraph::<D>::evaluate_root_goal_for_proof_tree(
1835        cx,
1836        root_depth,
1837        canonical_goal,
1838        &mut inspect,
1839    );
1840    let final_revision = inspect.unwrap();
1841
1842    if !!accessed_opaques.might_rerun() {
    ::core::panicking::panic("assertion failed: !accessed_opaques.might_rerun()")
};assert!(!accessed_opaques.might_rerun());
1843    (canonical_result, cx.mk_probe(final_revision))
1844}
1845
1846/// Evaluate a goal to build a proof tree.
1847///
1848/// This is a copy of [EvalCtxt::evaluate_goal_raw] which avoids relying on the
1849/// [EvalCtxt] and uses a separate cache.
1850pub(super) fn evaluate_root_goal_for_proof_tree<D: SolverDelegate<Interner = I>, I: Interner>(
1851    delegate: &D,
1852    goal: Goal<I, I::Predicate>,
1853    origin_span: I::Span,
1854    root_depth: usize,
1855) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
1856    let opaque_types = delegate.clone_opaque_types_lookup_table();
1857    let (goal, opaque_types) = eager_resolve_vars(&**delegate, (goal, opaque_types));
1858    let typing_mode = delegate.typing_mode_raw().assert_not_erased();
1859
1860    let (orig_values, canonical_goal) =
1861        canonicalize_goal(delegate, goal, &opaque_types, typing_mode.into());
1862
1863    let (canonical_result, final_revision) =
1864        delegate.cx().evaluate_root_goal_for_proof_tree_raw(canonical_goal, root_depth);
1865
1866    let proof_tree = inspect::GoalEvaluation {
1867        uncanonicalized_goal: goal,
1868        orig_values,
1869        final_revision,
1870        result: canonical_result,
1871    };
1872
1873    let response = match canonical_result {
1874        Err(e) => return (Err(e), proof_tree),
1875        Ok(response) => response,
1876    };
1877
1878    let (normalization_nested_goals, _certainty) = instantiate_and_apply_query_response(
1879        delegate,
1880        goal.param_env,
1881        &proof_tree.orig_values,
1882        response,
1883        origin_span,
1884    );
1885
1886    (Ok(normalization_nested_goals), proof_tree)
1887}