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,
21};
22use tracing::{Level, debug, instrument, trace, warn};
23
24use super::has_only_region_constraints;
25use crate::canonical::{
26    canonicalize_goal, canonicalize_response, instantiate_and_apply_query_response,
27    response_no_constraints_raw,
28};
29use crate::coherence;
30use crate::delegate::SolverDelegate;
31use crate::normalize::{NormalizationFolder, NormalizationWasAmbiguous};
32use crate::placeholder::BoundVarReplacer;
33use crate::resolve::eager_resolve_vars;
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 result = EvalCtxt::enter_root(self, self.cx().recursion_limit(), span, |ecx| {
250            // Fast paths handled above
251            ecx.evaluate_goal_no_fast_paths(GoalSource::Misc, goal)
252        });
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;
        }
        { evaluate_root_goal_for_proof_tree(self, goal, span) }
    }
}#[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        evaluate_root_goal_for_proof_tree(self, goal, span)
306    }
307}
308
309impl<'a, D, I> EvalCtxt<'a, D>
310where
311    D: SolverDelegate<Interner = I>,
312    I: Interner,
313{
314    pub(super) fn typing_mode(&self) -> TypingMode<I> {
315        self.delegate.typing_mode_raw()
316    }
317
318    /// Computes the `PathKind` for the step from the current goal to the
319    /// nested goal required due to `source`.
320    ///
321    /// See #136824 for a more detailed reasoning for this behavior. We
322    /// consider cycles to be coinductive if they 'step into' a where-clause
323    /// of a coinductive trait. We will likely extend this function in the future
324    /// and will need to clearly document it in the rustc-dev-guide before
325    /// stabilization.
326    pub(super) fn step_kind_for_source(&self, source: GoalSource) -> PathKind {
327        match source {
328            // We treat these goals as unknown for now. It is likely that most miscellaneous
329            // nested goals will be converted to an inductive variant in the future.
330            //
331            // Having unknown cycles is always the safer option, as changing that to either
332            // succeed or hard error is backwards compatible. If we incorrectly treat a cycle
333            // as inductive even though it should not be, it may be unsound during coherence and
334            // fixing it may cause inference breakage or introduce ambiguity.
335            GoalSource::Misc => PathKind::Unknown,
336            GoalSource::NormalizeGoal(path_kind) => path_kind,
337            GoalSource::ImplWhereBound => match self.current_goal_kind {
338                // We currently only consider a cycle coinductive if it steps
339                // into a where-clause of a coinductive trait.
340                CurrentGoalKind::CoinductiveTrait => PathKind::Coinductive,
341                // While normalizing via an impl does step into a where-clause of
342                // an impl, accessing the associated item immediately steps out of
343                // it again. This means cycles/recursive calls are not guarded
344                // by impls used for normalization.
345                //
346                // See tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.rs
347                // for how this can go wrong.
348                CurrentGoalKind::ProjectionComputeAssocTermCandidate => PathKind::Inductive,
349                // We probably want to make all traits coinductive in the future,
350                // so we treat cycles involving where-clauses of not-yet coinductive
351                // traits as ambiguous for now.
352                CurrentGoalKind::Misc => PathKind::Unknown,
353            },
354            // Relating types is always unproductive. If we were to map proof trees to
355            // corecursive functions as explained in #136824, relating types never
356            // introduces a constructor which could cause the recursion to be guarded.
357            GoalSource::TypeRelating => PathKind::Inductive,
358            // These goal sources are likely unproductive and can be changed to
359            // `PathKind::Inductive`. Keeping them as unknown until we're confident
360            // about this and have an example where it is necessary.
361            GoalSource::AliasBoundConstCondition | GoalSource::AliasWellFormed => PathKind::Unknown,
362        }
363    }
364
365    /// Creates a root evaluation context and search graph. This should only be
366    /// used from outside of any evaluation, and other methods should be preferred
367    /// over using this manually (such as [`SolverDelegateEvalExt::evaluate_root_goal`]).
368    pub(super) fn enter_root<R>(
369        delegate: &D,
370        root_depth: usize,
371        origin_span: I::Span,
372        f: impl FnOnce(&mut EvalCtxt<'_, D>) -> R,
373    ) -> R {
374        let mut search_graph = SearchGraph::new(root_depth);
375
376        let mut ecx = EvalCtxt {
377            delegate,
378            search_graph: &mut search_graph,
379            nested_goals: Default::default(),
380            inspect: inspect::EvaluationStepBuilder::new_noop(),
381
382            // Only relevant when canonicalizing the response,
383            // which we don't do within this evaluation context.
384            max_input_universe: ty::UniverseIndex::ROOT,
385            initial_opaque_types_storage_num_entries: Default::default(),
386            var_kinds: Default::default(),
387            var_values: CanonicalVarValues::dummy(),
388            current_goal_kind: CurrentGoalKind::Misc,
389            origin_span,
390            tainted: Ok(()),
391            opaque_accesses: AccessedOpaques::default(),
392        };
393        let result = f(&mut ecx);
394        if !ecx.nested_goals.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("root `EvalCtxt` should not have any goals added to it"));
    }
};assert!(
395            ecx.nested_goals.is_empty(),
396            "root `EvalCtxt` should not have any goals added to it"
397        );
398        if !!ecx.opaque_accesses.might_rerun() {
    ::core::panicking::panic("assertion failed: !ecx.opaque_accesses.might_rerun()")
};assert!(!ecx.opaque_accesses.might_rerun());
399        if !search_graph.is_empty() {
    ::core::panicking::panic("assertion failed: search_graph.is_empty()")
};assert!(search_graph.is_empty());
400        result
401    }
402
403    /// Creates a nested evaluation context that shares the same search graph as the
404    /// one passed in. This is suitable for evaluation, granted that the search graph
405    /// has had the nested goal recorded on its stack. This method only be used by
406    /// `search_graph::Delegate::compute_goal`.
407    ///
408    /// This function takes care of setting up the inference context, setting the anchor,
409    /// and registering opaques from the canonicalized input.
410    pub(super) fn enter_canonical<T>(
411        cx: I,
412        search_graph: &'a mut SearchGraph<D>,
413        canonical_input: CanonicalInput<I>,
414        proof_tree_builder: &mut inspect::ProofTreeBuilder<D>,
415        f: impl FnOnce(
416            &mut EvalCtxt<'_, D>,
417            Goal<I, I::Predicate>,
418        ) -> Result<T, NoSolutionOrRerunNonErased>,
419    ) -> (Result<T, NoSolution>, AccessedOpaques<I>) {
420        let (ref delegate, input, var_values) = D::build_with_canonical(cx, &canonical_input);
421        for (key, ty) in input.predefined_opaques_in_body.iter() {
422            let prev = delegate.register_hidden_type_in_storage(key, ty, I::Span::dummy());
423            // It may be possible that two entries in the opaque type storage end up
424            // with the same key after resolving contained inference variables.
425            //
426            // We could put them in the duplicate list but don't have to. The opaques we
427            // encounter here are already tracked in the caller, so there's no need to
428            // also store them here. We'd take them out when computing the query response
429            // and then discard them, as they're already present in the input.
430            //
431            // Ideally we'd drop duplicate opaque type definitions when computing
432            // the canonical input. This is more annoying to implement and may cause a
433            // perf regression, so we do it inside of the query for now.
434            if let Some(prev) = prev {
435                {
    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:435",
                        "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(435u32),
                        ::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`");
436            }
437        }
438
439        let initial_opaque_types_storage_num_entries = delegate.opaque_types_storage_num_entries();
440        if truecfg!(debug_assertions) && delegate.typing_mode_raw().is_erased_not_coherence() {
441            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());
442        }
443
444        let mut ecx = EvalCtxt {
445            delegate,
446            var_kinds: canonical_input.canonical.var_kinds,
447            var_values,
448            current_goal_kind: CurrentGoalKind::from_query_input(cx, input),
449            max_input_universe: canonical_input.canonical.max_universe,
450            initial_opaque_types_storage_num_entries,
451            search_graph,
452            nested_goals: Default::default(),
453            origin_span: I::Span::dummy(),
454            tainted: Ok(()),
455            inspect: proof_tree_builder.new_evaluation_step(var_values),
456            opaque_accesses: AccessedOpaques::default(),
457        };
458
459        let result = f(&mut ecx, input.goal);
460        ecx.inspect.probe_final_state(ecx.delegate, ecx.max_input_universe);
461        proof_tree_builder.finish_evaluation_step(ecx.inspect);
462
463        if canonical_input.typing_mode.0.is_erased_not_coherence() {
464            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());
465        }
466
467        // When creating a query response we clone the opaque type constraints
468        // instead of taking them. This would cause an ICE here, since we have
469        // assertions against dropping an `InferCtxt` without taking opaques.
470        // FIXME: Once we remove support for the old impl we can remove this.
471        // FIXME: Could we make `build_with_canonical` into `enter_with_canonical` and call this at the end?
472        delegate.reset_opaque_types();
473
474        let opaque_accesses = ecx.opaque_accesses;
475        (
476            match result {
477                Ok(i) => Ok(i),
478                Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Err(NoSolution),
479                Err(NoSolutionOrRerunNonErased::RerunNonErased(_)) => {
480                    // Check that the opaque_accesses state mirrors the result we got.
481                    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());
482                    Err(NoSolution)
483                }
484            },
485            opaque_accesses,
486        )
487    }
488
489    pub(super) fn ignore_candidate_head_usages(&mut self, usages: CandidateHeadUsages) {
490        self.search_graph.ignore_candidate_head_usages(usages);
491    }
492
493    /// Recursively evaluates `goal`, returning whether any inference vars have
494    /// been constrained and the certainty of the result.
495    fn evaluate_goal(
496        &mut self,
497        source: GoalSource,
498        goal: Goal<I, I::Predicate>,
499        stalled_on: Option<GoalStalledOn<I>>,
500    ) -> Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased> {
501        if let RerunStalled::WontMakeProgress(stalled_certainty) =
502            rerunning_stalled_goal_may_make_progress(self.delegate, stalled_on.as_ref())
503        {
504            return Ok(GoalEvaluation {
505                goal,
506                certainty: stalled_certainty,
507                has_changed: HasChanged::No,
508                stalled_on,
509            });
510        }
511
512        // No need to try the fast path if stalled_on is `None`, since we already try the fast path
513        // immediately when adding new goals. If we didn't check `stalled_on` here we'd be trying
514        // the fast path twice for some goals.
515        if stalled_on.is_some()
516            && let Some(res) = compute_goal_fast_path_cold(self.delegate, goal, self.origin_span)
517        {
518            return Ok(res);
519        }
520
521        self.evaluate_goal_no_fast_paths(source, goal)
522    }
523
524    // Outlining and `#[cold]` matter here because fast paths make it less likely to get here.
525    #[cold]
526    #[inline(never)]
527    fn evaluate_goal_no_fast_paths(
528        &mut self,
529        source: GoalSource,
530        goal: Goal<I, I::Predicate>,
531    ) -> Result<GoalEvaluation<I>, NoSolutionOrRerunNonErased> {
532        let (normalization_nested_goals, goal_evaluation) =
533            self.evaluate_goal_raw(source, goal, LowerAvailableDepth::Yes)?;
534        if !normalization_nested_goals.is_empty() {
    ::core::panicking::panic("assertion failed: normalization_nested_goals.is_empty()")
};assert!(normalization_nested_goals.is_empty());
535        Ok(goal_evaluation)
536    }
537
538    /// Recursively evaluates `goal`, returning the nested goals in case
539    /// the nested goal is a `NormalizesTo` goal.
540    ///
541    /// As all other goal kinds do not return any nested goals and
542    /// `NormalizesTo` is only used by `Projection`, all other callsites
543    /// should use [`EvalCtxt::evaluate_goal`] which discards that empty
544    /// storage.
545    pub(super) fn evaluate_goal_raw(
546        &mut self,
547        source: GoalSource,
548        goal: Goal<I, I::Predicate>,
549        increase_depth_for_nested: LowerAvailableDepth,
550    ) -> Result<(NestedNormalizationGoals<I>, GoalEvaluation<I>), NoSolutionOrRerunNonErased> {
551        // We only care about one entry per `OpaqueTypeKey` here,
552        // so we only canonicalize the lookup table and ignore
553        // duplicate entries.
554        let opaque_types = self.delegate.clone_opaque_types_lookup_table();
555        let (goal, opaque_types) = eager_resolve_vars(&**self.delegate, (goal, opaque_types));
556        let typing_mode = self.typing_mode();
557        let step_kind = self.step_kind_for_source(source);
558
559        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(559u32),
                        ::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!(
560            Level::DEBUG,
561            "evaluate_goal_raw in typing mode",
562            "{:?} opaques={:?}",
563            typing_mode,
564            opaque_types
565        )
566        .entered();
567
568        let (result, orig_values, canonical_goal, succeeded_in_erased) = 'retry_canonicalize: {
569            let skip_erased_attempt = if typing_mode.is_coherence() {
570                true
571            } else {
572                let mut skip = false;
573                if opaque_types.iter().any(|(_, ty)| ty.is_ty_var())
574                    && let PredicateKind::Clause(ClauseKind::Trait(..)) =
575                        goal.predicate.kind().skip_binder()
576                {
577                    skip = true;
578                }
579
580                if let PredicateKind::Clause(ClauseKind::Trait(tr)) =
581                    goal.predicate.kind().skip_binder()
582                    && tr.self_ty().has_coroutines()
583                    && self.cx().trait_is_auto(tr.trait_ref.def_id)
584                {
585                    // FIXME(#155443): this doesn't make a difference now, but with eager normalization
586                    // it likely will.
587                    // skip_erased_attempt = true;
588                }
589
590                skip
591            };
592
593            if skip_erased_attempt {
594                if typing_mode.is_erased_not_coherence() {
595                    match self.opaque_accesses.rerun_always(RerunReason::SkipErasedAttempt)? {}
596                } else {
597                    {
    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:597",
                        "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(597u32),
                        ::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");
598                }
599            } else {
600                {
    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:600",
                        "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(600u32),
                        ::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:?}");
601
602                let (orig_values, canonical_goal) = canonicalize_goal(
603                    self.delegate,
604                    goal,
605                    &[],
606                    TypingMode::ErasedNotCoherence(MayBeErased),
607                );
608
609                let (canonical_result, accessed_opaques) = self.search_graph.evaluate_goal(
610                    self.cx(),
611                    canonical_goal,
612                    step_kind,
613                    increase_depth_for_nested,
614                    &mut inspect::ProofTreeBuilder::new_noop(),
615                );
616
617                let should_rerun = should_rerun_after_erased_canonicalization(
618                    accessed_opaques,
619                    self.typing_mode(),
620                    &opaque_types,
621                );
622                match should_rerun {
623                    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:623",
                        "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(623u32),
                        ::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"),
624                    RerunDecision::No => {
625                        break 'retry_canonicalize (
626                            canonical_result,
627                            orig_values,
628                            canonical_goal,
629                            SucceededInErased::Yes { accessed_opaques },
630                        );
631                    }
632                    RerunDecision::EagerlyPropagateToParent => {
633                        self.opaque_accesses.update(accessed_opaques)?;
634                        break 'retry_canonicalize (
635                            canonical_result,
636                            orig_values,
637                            canonical_goal,
638                            // If we're propagating up, we should never retry the goal.
639                            // That means `No` is fine to return, it doesn't really matter.
640                            SucceededInErased::No,
641                        );
642                    }
643                }
644            }
645
646            let (orig_values, canonical_goal) =
647                canonicalize_goal(self.delegate, goal, &opaque_types, typing_mode);
648
649            let (canonical_result, accessed_opaques) = self.search_graph.evaluate_goal(
650                self.cx(),
651                canonical_goal,
652                step_kind,
653                increase_depth_for_nested,
654                &mut inspect::ProofTreeBuilder::new_noop(),
655            );
656            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!(
657                !accessed_opaques.might_rerun(),
658                "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:?}"
659            );
660
661            (canonical_result, orig_values, canonical_goal, SucceededInErased::No)
662        };
663
664        {
    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:664",
                        "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(664u32),
                        ::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);
665        let response = match result {
666            Ok(response) => {
667                {
    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:667",
                        "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(667u32),
                        ::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");
668                response
669            }
670            Err(NoSolution) => {
671                {
    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:671",
                        "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(671u32),
                        ::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");
672                return Err(NoSolution.into());
673            }
674        };
675
676        drop(tracing_span);
677
678        let has_changed =
679            if !has_only_region_constraints(response) { HasChanged::Yes } else { HasChanged::No };
680
681        let (normalization_nested_goals, certainty) = instantiate_and_apply_query_response(
682            self.delegate,
683            goal.param_env,
684            &orig_values,
685            response,
686            self.origin_span,
687        );
688
689        // FIXME: We previously had an assert here that checked that recomputing
690        // a goal after applying its constraints did not change its response.
691        //
692        // This assert was removed as it did not hold for goals constraining
693        // an inference variable to a recursive alias, e.g. in
694        // tests/ui/traits/next-solver/overflow/recursive-self-normalization.rs.
695        //
696        // Once we have decided on how to handle trait-system-refactor-initiative#75,
697        // we should re-add an assert here.
698
699        let stalled_on = match certainty {
700            Certainty::Yes => None,
701            Certainty::Maybe { .. } => match has_changed {
702                // FIXME: We could recompute a *new* set of stalled variables by walking
703                // through the orig values, resolving, and computing the root vars of anything
704                // that is not resolved. Only when *these* have changed is it meaningful
705                // to recompute this goal.
706                HasChanged::Yes => None,
707                HasChanged::No => Some(self.build_stalled_on(
708                    canonical_goal,
709                    certainty,
710                    orig_values,
711                    succeeded_in_erased,
712                )),
713            },
714        };
715
716        Ok((
717            normalization_nested_goals,
718            GoalEvaluation { goal, certainty, has_changed, stalled_on },
719        ))
720    }
721
722    fn build_stalled_on(
723        &self,
724        canonical_goal: CanonicalInput<I>,
725        certainty: Certainty,
726        mut stalled_vars: Vec<I::GenericArg>,
727        previously_succeeded_in_erased: SucceededInErased<I>,
728    ) -> GoalStalledOn<I> {
729        // Remove the canonicalized universal vars, since we only care about stalled existentials.
730        let mut sub_roots = Vec::new();
731        stalled_vars.retain(|arg| match arg.kind() {
732            // Lifetimes can never stall goals.
733            ty::GenericArgKind::Lifetime(_) => false,
734            ty::GenericArgKind::Type(ty) => match ty.kind() {
735                ty::Infer(ty::TyVar(vid)) => {
736                    sub_roots.push(self.delegate.sub_unification_table_root_var(vid));
737                    true
738                }
739                ty::Infer(_) => true,
740                ty::Param(_) | ty::Placeholder(_) => false,
741                _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected orig_value: {0:?}", ty)));
}unreachable!("unexpected orig_value: {ty:?}"),
742            },
743            ty::GenericArgKind::Const(ct) => match ct.kind() {
744                ty::ConstKind::Infer(_) => true,
745                ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(_) => false,
746                _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected orig_value: {0:?}", ct)));
}unreachable!("unexpected orig_value: {ct:?}"),
747            },
748        });
749
750        GoalStalledOn {
751            stalled_vars,
752            sub_roots,
753            stalled_certainty: certainty,
754            opaques: GoalStalledOnOpaques::Yes {
755                num_opaques_in_storage: canonical_goal
756                    .canonical
757                    .value
758                    .predefined_opaques_in_body
759                    .len(),
760                previously_succeeded_in_erased,
761            },
762        }
763    }
764
765    pub(super) fn compute_goal(
766        &mut self,
767        goal: Goal<I, I::Predicate>,
768    ) -> QueryResultOrRerunNonErased<I> {
769        let Goal { param_env, predicate } = goal;
770        let kind = predicate.kind();
771        self.enter_forall_with_assumptions(kind, param_env, |ecx, kind| {
772            Ok(match kind {
773                ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
774                    ecx.compute_trait_goal(Goal { param_env, predicate }).map(|(r, _via)| r)?
775                }
776                ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
777                    ecx.compute_host_effect_goal(Goal { param_env, predicate })?
778                }
779                ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) => {
780                    ecx.compute_projection_goal(Goal { param_env, predicate })?
781                }
782                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(predicate)) => {
783                    ecx.compute_type_outlives_goal(Goal { param_env, predicate })?
784                }
785                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(predicate)) => {
786                    ecx.compute_region_outlives_goal(Goal { param_env, predicate })?
787                }
788                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
789                    ecx.compute_const_arg_has_type_goal(Goal { param_env, predicate: (ct, ty) })?
790                }
791                ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(symbol)) => {
792                    ecx.compute_unstable_feature_goal(param_env, symbol)?
793                }
794                ty::PredicateKind::Subtype(predicate) => {
795                    ecx.compute_subtype_goal(Goal { param_env, predicate })?
796                }
797                ty::PredicateKind::Coerce(predicate) => {
798                    ecx.compute_coerce_goal(Goal { param_env, predicate })?
799                }
800                ty::PredicateKind::DynCompatible(trait_def_id) => {
801                    ecx.compute_dyn_compatible_goal(trait_def_id)?
802                }
803                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
804                    ecx.compute_well_formed_goal(Goal { param_env, predicate: term })?
805                }
806                ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => {
807                    ecx.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })?
808                }
809                ty::PredicateKind::ConstEquate(_, _) => {
810                    {
    ::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")
811                }
812                ty::PredicateKind::NormalizesTo(predicate) => {
813                    ecx.compute_normalizes_to_goal(Goal { param_env, predicate })?
814                }
815                ty::PredicateKind::Ambiguous => {
816                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)?
817                }
818            })
819        })
820    }
821
822    // Recursively evaluates all the goals added to this `EvalCtxt` to completion, returning
823    // the certainty of all the goals.
824    #[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(824u32),
                                    ::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:839",
                                    "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(839u32),
                                    ::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))]
825    pub(super) fn try_evaluate_added_goals(
826        &mut self,
827    ) -> Result<Certainty, NoSolutionOrRerunNonErased> {
828        for _ in 0..FIXPOINT_STEP_LIMIT {
829            match self.evaluate_added_goals_step().map_err_to_rerun()? {
830                Ok(None) => {}
831                Ok(Some(cert)) => return Ok(cert),
832                Err(NoSolution) => {
833                    self.tainted = Err(NoSolution);
834                    return Err(NoSolution.into());
835                }
836            }
837        }
838
839        debug!("try_evaluate_added_goals: encountered overflow");
840        Ok(Certainty::overflow(false))
841    }
842
843    /// Iterate over all added goals: returning `Ok(Some(_))` in case we can stop rerunning.
844    ///
845    /// Goals for the next step get directly added to the nested goals of the `EvalCtxt`.
846    fn evaluate_added_goals_step(
847        &mut self,
848    ) -> Result<Option<Certainty>, NoSolutionOrRerunNonErased> {
849        // If this loop did not result in any progress, what's our final certainty.
850        let mut unchanged_certainty = Some(Certainty::Yes);
851        // This mem::take seems super inefficient, given that we push to it again later.
852        // Despite that, replacing it has no effect on performance. We tried.
853        // (https://github.com/rust-lang/rust/pull/158126)
854        for (source, goal, stalled_on) in mem::take(&mut self.nested_goals) {
855            // We never handle `NormalizesTo` as a nested goal
856            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!(
857                goal.predicate.kind().skip_binder(),
858                PredicateKind::NormalizesTo(_)
859            ));
860
861            let GoalEvaluation { goal, certainty, has_changed, stalled_on } =
862                self.evaluate_goal(source, goal, stalled_on)?;
863            if has_changed == HasChanged::Yes {
864                unchanged_certainty = None;
865            }
866
867            match certainty {
868                Certainty::Yes => {}
869                Certainty::Maybe { .. } => {
870                    self.nested_goals.push((source, goal, stalled_on));
871                    unchanged_certainty = unchanged_certainty.map(|c| c.and(certainty));
872                }
873            }
874        }
875
876        Ok(unchanged_certainty)
877    }
878
879    /// Record impl args in the proof tree for later access by `InspectCandidate`.
880    pub(crate) fn record_impl_args(&mut self, impl_args: I::GenericArgs) {
881        self.inspect.record_impl_args(self.delegate, self.max_input_universe, impl_args)
882    }
883
884    pub(super) fn cx(&self) -> I {
885        self.delegate.cx()
886    }
887
888    #[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(888u32),
                                    ::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))]
889    pub(super) fn add_goal(
890        &mut self,
891        source: GoalSource,
892        mut goal: Goal<I, I::Predicate>,
893    ) -> Result<(), NoSolutionOrRerunNonErased> {
894        goal.predicate = self.normalize(
895            GoalSource::NormalizeGoal(self.step_kind_for_source(source)),
896            goal.param_env,
897            ty::Unnormalized::new_wip(goal.predicate),
898        )?;
899        self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
900
901        if let Some(GoalEvaluation { goal, certainty, has_changed: _, stalled_on }) =
902            compute_goal_fast_path(self.delegate, goal, self.origin_span)
903        {
904            match certainty {
905                // We're done here
906                Certainty::Yes => {}
907                Certainty::Maybe(_) => {
908                    self.nested_goals.push((source, goal, stalled_on));
909                }
910            }
911        } else {
912            self.nested_goals.push((source, goal, None));
913        }
914        Ok(())
915    }
916
917    #[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(917u32),
                                    ::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))]
918    pub(super) fn add_goals(
919        &mut self,
920        source: GoalSource,
921        goals: impl IntoIterator<Item = Goal<I, I::Predicate>>,
922    ) -> Result<(), NoSolutionOrRerunNonErased> {
923        for goal in goals {
924            self.add_goal(source, goal)?;
925        }
926        Ok(())
927    }
928
929    pub(super) fn next_region_var(&mut self) -> Region<I> {
930        let region = self.delegate.next_region_infer();
931        self.inspect.add_var_value(region);
932        region
933    }
934
935    pub(super) fn next_ty_infer(&mut self) -> I::Ty {
936        let ty = self.delegate.next_ty_infer();
937        self.inspect.add_var_value(ty);
938        ty
939    }
940
941    pub(super) fn next_const_infer(&mut self) -> I::Const {
942        let ct = self.delegate.next_const_infer();
943        self.inspect.add_var_value(ct);
944        ct
945    }
946
947    /// Returns a ty infer or a const infer depending on whether `kind` is a `Ty` or `Const`.
948    /// If `kind` is an integer inference variable this will still return a ty infer var.
949    pub(super) fn next_term_infer_of_alias_kind(
950        &mut self,
951        alias_term: ty::AliasTerm<I>,
952    ) -> I::Term {
953        match alias_term.kind {
954            ty::AliasTermKind::ProjectionTy { .. }
955            | ty::AliasTermKind::InherentTy { .. }
956            | ty::AliasTermKind::OpaqueTy { .. }
957            | ty::AliasTermKind::FreeTy { .. } => self.next_ty_infer().into(),
958            ty::AliasTermKind::FreeConst { .. }
959            | ty::AliasTermKind::InherentConst { .. }
960            | ty::AliasTermKind::AnonConst { .. }
961            | ty::AliasTermKind::ProjectionConst { .. } => self.next_const_infer().into(),
962        }
963    }
964
965    /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
966    ///
967    /// This is the case if the `term` does not occur in any other part of the predicate
968    /// and is able to name all other placeholder and inference variables.
969    x;#[instrument(level = "trace", skip(self), ret)]
970    pub(super) fn term_is_fully_unconstrained(&self, goal: Goal<I, ty::NormalizesTo<I>>) -> bool {
971        let universe_of_term = match goal.predicate.term.kind() {
972            ty::TermKind::Ty(ty) => {
973                if let ty::Infer(ty::TyVar(vid)) = ty.kind() {
974                    self.delegate.universe_of_ty(vid).unwrap()
975                } else {
976                    return false;
977                }
978            }
979            ty::TermKind::Const(ct) => {
980                if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
981                    self.delegate.universe_of_ct(vid).unwrap()
982                } else {
983                    return false;
984                }
985            }
986        };
987
988        struct ContainsTermOrNotNameable<'a, D: SolverDelegate<Interner = I>, I: Interner> {
989            term: I::Term,
990            universe_of_term: ty::UniverseIndex,
991            delegate: &'a D,
992            cache: HashSet<I::Ty>,
993        }
994
995        impl<D: SolverDelegate<Interner = I>, I: Interner> ContainsTermOrNotNameable<'_, D, I> {
996            fn check_nameable(&self, universe: ty::UniverseIndex) -> ControlFlow<()> {
997                if self.universe_of_term.can_name(universe) {
998                    ControlFlow::Continue(())
999                } else {
1000                    ControlFlow::Break(())
1001                }
1002            }
1003        }
1004
1005        impl<D: SolverDelegate<Interner = I>, I: Interner> TypeVisitor<I>
1006            for ContainsTermOrNotNameable<'_, D, I>
1007        {
1008            type Result = ControlFlow<()>;
1009            fn visit_ty(&mut self, t: I::Ty) -> Self::Result {
1010                if self.cache.contains(&t) {
1011                    return ControlFlow::Continue(());
1012                }
1013
1014                match t.kind() {
1015                    ty::Infer(ty::TyVar(vid)) => {
1016                        if let ty::TermKind::Ty(term) = self.term.kind()
1017                            && let ty::Infer(ty::TyVar(term_vid)) = term.kind()
1018                            && self.delegate.root_ty_var(vid) == self.delegate.root_ty_var(term_vid)
1019                        {
1020                            return ControlFlow::Break(());
1021                        }
1022
1023                        self.check_nameable(self.delegate.universe_of_ty(vid).unwrap())?;
1024                    }
1025                    ty::Placeholder(p) => self.check_nameable(p.universe())?,
1026                    _ => {
1027                        if t.has_non_region_infer() || t.has_placeholders() {
1028                            t.super_visit_with(self)?
1029                        }
1030                    }
1031                }
1032
1033                assert!(self.cache.insert(t));
1034                ControlFlow::Continue(())
1035            }
1036
1037            fn visit_const(&mut self, c: I::Const) -> Self::Result {
1038                match c.kind() {
1039                    ty::ConstKind::Infer(ty::InferConst::Var(vid)) => {
1040                        if let ty::TermKind::Const(term) = self.term.kind()
1041                            && let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
1042                            && self.delegate.root_const_var(vid)
1043                                == self.delegate.root_const_var(term_vid)
1044                        {
1045                            return ControlFlow::Break(());
1046                        }
1047
1048                        self.check_nameable(self.delegate.universe_of_ct(vid).unwrap())
1049                    }
1050                    ty::ConstKind::Placeholder(p) => self.check_nameable(p.universe()),
1051                    _ => {
1052                        if c.has_non_region_infer() || c.has_placeholders() {
1053                            c.super_visit_with(self)
1054                        } else {
1055                            ControlFlow::Continue(())
1056                        }
1057                    }
1058                }
1059            }
1060
1061            fn visit_predicate(&mut self, p: I::Predicate) -> Self::Result {
1062                if p.has_non_region_infer() || p.has_placeholders() {
1063                    p.super_visit_with(self)
1064                } else {
1065                    ControlFlow::Continue(())
1066                }
1067            }
1068
1069            fn visit_clauses(&mut self, c: I::Clauses) -> Self::Result {
1070                if c.has_non_region_infer() || c.has_placeholders() {
1071                    c.super_visit_with(self)
1072                } else {
1073                    ControlFlow::Continue(())
1074                }
1075            }
1076        }
1077
1078        let mut visitor = ContainsTermOrNotNameable {
1079            delegate: self.delegate,
1080            universe_of_term,
1081            term: goal.predicate.term,
1082            cache: Default::default(),
1083        };
1084        goal.predicate.alias.visit_with(&mut visitor).is_continue()
1085            && goal.param_env.visit_with(&mut visitor).is_continue()
1086    }
1087
1088    pub(super) fn sub_unify_ty_vids_raw(&self, a: ty::TyVid, b: ty::TyVid) {
1089        self.delegate.sub_unify_ty_vids_raw(a, b)
1090    }
1091
1092    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1093    pub(super) fn eq<T: Relate<I>>(
1094        &mut self,
1095        param_env: I::ParamEnv,
1096        lhs: T,
1097        rhs: T,
1098    ) -> Result<(), NoSolutionOrRerunNonErased> {
1099        self.relate(param_env, lhs, ty::Variance::Invariant, rhs)
1100    }
1101
1102    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1103    pub(super) fn sub<T: Relate<I>>(
1104        &mut self,
1105        param_env: I::ParamEnv,
1106        sub: T,
1107        sup: T,
1108    ) -> Result<(), NoSolutionOrRerunNonErased> {
1109        self.relate(param_env, sub, ty::Variance::Covariant, sup)
1110    }
1111
1112    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1113    pub(super) fn relate<T: Relate<I>>(
1114        &mut self,
1115        param_env: I::ParamEnv,
1116        lhs: T,
1117        variance: ty::Variance,
1118        rhs: T,
1119    ) -> Result<(), NoSolutionOrRerunNonErased> {
1120        let goals = self.delegate.relate(param_env, lhs, variance, rhs, self.origin_span)?;
1121        for &goal in goals.iter() {
1122            let source = match goal.predicate.kind().skip_binder() {
1123                ty::PredicateKind::Subtype { .. }
1124                | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
1125                    GoalSource::TypeRelating
1126                }
1127                // FIXME(-Znext-solver=coinductive): should these WF goals also be unproductive?
1128                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => GoalSource::Misc,
1129                p => unreachable!("unexpected nested goal in `relate`: {p:?}"),
1130            };
1131            self.add_goal(source, goal)?;
1132        }
1133        Ok(())
1134    }
1135
1136    /// Equates two values returning the nested goals without adding them
1137    /// to the nested goals of the `EvalCtxt`.
1138    ///
1139    /// If possible, try using `eq` instead which automatically handles nested
1140    /// goals correctly.
1141    x;#[instrument(level = "trace", skip(self, param_env), ret)]
1142    pub(super) fn eq_and_get_goals<T: Relate<I>>(
1143        &self,
1144        param_env: I::ParamEnv,
1145        lhs: T,
1146        rhs: T,
1147    ) -> Result<Vec<Goal<I, I::Predicate>>, NoSolution> {
1148        Ok(self.delegate.relate(param_env, lhs, ty::Variance::Invariant, rhs, self.origin_span)?)
1149    }
1150
1151    pub(super) fn instantiate_binder_with_infer<T: TypeFoldable<I> + Copy>(
1152        &self,
1153        value: ty::Binder<I, T>,
1154    ) -> T {
1155        self.delegate.instantiate_binder_with_infer(value)
1156    }
1157
1158    /// `enter_forall_with_assumptions`, but takes `&mut self` and passes it back through
1159    /// the callback since it can't be aliased during the call.
1160    ///
1161    /// The `param_env` is used to *compute* the assumptions of the binder, not *as* the
1162    /// assumptions associated with the binder.
1163    ///
1164    /// FIXME(inherent_associated_types): fix this?
1165    pub(super) fn enter_forall_with_assumptions<T: TypeFoldable<I>, U>(
1166        &mut self,
1167        value: ty::Binder<I, T>,
1168        param_env: I::ParamEnv,
1169        f: impl FnOnce(&mut Self, T) -> U,
1170    ) -> U {
1171        self.delegate.enter_forall_without_assumptions(value, |value| {
1172            let u = self.delegate.universe();
1173            let assumptions = if self.cx().assumptions_on_binders() {
1174                self.region_assumptions_for_placeholders_in_universe(value.clone(), u, param_env)
1175            } else {
1176                None
1177            };
1178            self.delegate.insert_placeholder_assumptions(u, assumptions);
1179            f(self, value)
1180        })
1181    }
1182
1183    pub(super) fn resolve_vars_if_possible<T>(&self, value: T) -> T
1184    where
1185        T: TypeFoldable<I>,
1186    {
1187        self.delegate.resolve_vars_if_possible(value)
1188    }
1189
1190    pub(super) fn shallow_resolve(&self, ty: I::Ty) -> I::Ty {
1191        self.delegate.shallow_resolve(ty)
1192    }
1193
1194    pub(super) fn eager_resolve_region(&self, r: Region<I>) -> Region<I> {
1195        if let ty::ReVar(vid) = r.kind() {
1196            self.delegate.opportunistic_resolve_lt_var(vid)
1197        } else {
1198            r
1199        }
1200    }
1201
1202    pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
1203        let args = self.delegate.fresh_args_for_item(def_id);
1204        for arg in args.iter() {
1205            self.inspect.add_var_value(arg);
1206        }
1207        args
1208    }
1209
1210    pub(super) fn register_solver_region_constraint(&self, c: RegionConstraint<I>) {
1211        self.delegate.register_solver_region_constraint(c);
1212    }
1213
1214    pub(super) fn register_ty_outlives(&self, ty: I::Ty, lt: Region<I>) {
1215        self.delegate.register_ty_outlives(ty, lt, self.origin_span);
1216    }
1217
1218    pub(super) fn register_region_outlives(
1219        &self,
1220        a: Region<I>,
1221        b: Region<I>,
1222        vis: VisibleForLeakCheck,
1223    ) {
1224        // `'a: 'b` ==> `'b <= 'a`
1225        self.delegate.sub_regions(b, a, vis, self.origin_span);
1226    }
1227
1228    /// Computes the list of goals required for `arg` to be well-formed
1229    pub(super) fn well_formed_goals(
1230        &self,
1231        param_env: I::ParamEnv,
1232        term: I::Term,
1233    ) -> Option<Vec<Goal<I, I::Predicate>>> {
1234        self.delegate.well_formed_goals(param_env, term)
1235    }
1236
1237    pub(super) fn trait_ref_is_knowable(
1238        &mut self,
1239        param_env: I::ParamEnv,
1240        trait_ref: ty::TraitRef<I>,
1241    ) -> Result<bool, NoSolutionOrRerunNonErased> {
1242        let delegate = self.delegate;
1243        let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
1244        coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
1245            .map(|is_knowable| is_knowable.is_ok())
1246    }
1247
1248    pub(super) fn fetch_eligible_assoc_item(
1249        &self,
1250        goal_trait_ref: ty::TraitRef<I>,
1251        trait_assoc_def_id: I::TraitAssocTermId,
1252        impl_def_id: I::ImplId,
1253    ) -> FetchEligibleAssocItemResponse<I> {
1254        self.delegate.fetch_eligible_assoc_item(goal_trait_ref, trait_assoc_def_id, impl_def_id)
1255    }
1256
1257    x;#[instrument(level = "debug", skip(self), ret)]
1258    pub(super) fn register_hidden_type_in_storage(
1259        &mut self,
1260        opaque_type_key: ty::OpaqueTypeKey<I>,
1261        hidden_ty: I::Ty,
1262    ) -> Option<I::Ty> {
1263        self.delegate.register_hidden_type_in_storage(opaque_type_key, hidden_ty, self.origin_span)
1264    }
1265
1266    pub(super) fn add_item_bounds_for_hidden_type(
1267        &mut self,
1268        opaque_def_id: I::OpaqueTyId,
1269        opaque_args: I::GenericArgs,
1270        param_env: I::ParamEnv,
1271        hidden_ty: I::Ty,
1272    ) -> Result<(), NoSolutionOrRerunNonErased> {
1273        let mut goals = Vec::new();
1274        self.delegate.add_item_bounds_for_hidden_type(
1275            opaque_def_id,
1276            opaque_args,
1277            param_env,
1278            hidden_ty,
1279            &mut goals,
1280        );
1281        self.add_goals(GoalSource::AliasWellFormed, goals)?;
1282        Ok(())
1283    }
1284
1285    // Try to evaluate a const, or return `None` if the const is too generic.
1286    // This doesn't mean the const isn't evaluatable, though, and should be treated
1287    // as an ambiguity rather than no-solution.
1288    pub(super) fn evaluate_const(
1289        &mut self,
1290        param_env: I::ParamEnv,
1291        alias_const: ty::AliasConst<I>,
1292    ) -> Result<Option<I::Const>, RerunNonErased> {
1293        if self.typing_mode().is_erased_not_coherence() {
1294            match self.opaque_accesses.rerun_always(RerunReason::EvaluateConst)? {}
1295        }
1296
1297        Ok(self.delegate.evaluate_const(param_env, alias_const))
1298    }
1299
1300    pub(super) fn evaluate_const_and_instantiate_projection_term(
1301        &mut self,
1302        param_env: I::ParamEnv,
1303        projection_term: ty::AliasTerm<I>,
1304        expected_term: I::Term,
1305        alias_const: ty::AliasConst<I>,
1306    ) -> QueryResultOrRerunNonErased<I> {
1307        match self.evaluate_const(param_env, alias_const)? {
1308            Some(evaluated) => {
1309                self.eq(param_env, expected_term, evaluated.into())?;
1310                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1311            }
1312            None if self.cx().features().generic_const_args() => {
1313                // HACK(khyperia): calling `resolve_vars_if_possible` here shouldn't be necessary,
1314                // `try_evaluate_const` calls `resolve_vars_if_possible` already. However, we want
1315                // to check `has_non_region_infer` against the type with vars resolved (i.e. check
1316                // if there are vars we failed to resolve), so we need to call it again here.
1317                // Perhaps we could split EvaluateConstErr::HasGenericsOrInfers into HasGenerics and
1318                // HasInfers or something, make evaluate_const return that, and make this branch be
1319                // based on that, rather than checking `has_non_region_infer`.
1320                if self.resolve_vars_if_possible(alias_const).has_non_region_infer() {
1321                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1322                } else {
1323                    // We do not instantiate to the `alias_const` passed in, but rather
1324                    // `goal.predicate.alias`. The `alias_const` passed in might correspond to the `impl`
1325                    // form of a constant (with generic arguments corresponding to the impl block),
1326                    // however, we want to structurally instantiate to the original, non-rebased,
1327                    // trait `Self` form of the constant (with generic arguments being the trait
1328                    // `Self` type).
1329                    self.eq(
1330                        param_env,
1331                        projection_term.to_term(self.cx(), ty::IsRigid::Yes),
1332                        expected_term,
1333                    )?;
1334                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1335                }
1336            }
1337            None => {
1338                // Legacy behavior: always treat as ambiguous
1339                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1340            }
1341        }
1342    }
1343
1344    pub(super) fn is_transmutable(
1345        &mut self,
1346        src: I::Ty,
1347        dst: I::Ty,
1348        assume: I::Const,
1349    ) -> Result<Certainty, NoSolution> {
1350        self.delegate.is_transmutable(dst, src, assume)
1351    }
1352
1353    pub(super) fn replace_bound_vars<T: TypeFoldable<I>>(
1354        &self,
1355        t: T,
1356        universes: &mut Vec<Option<ty::UniverseIndex>>,
1357    ) -> T {
1358        BoundVarReplacer::replace_bound_vars(&**self.delegate, universes, t).0
1359    }
1360
1361    pub(super) fn may_use_unstable_feature(
1362        &mut self,
1363        param_env: I::ParamEnv,
1364        symbol: I::Symbol,
1365    ) -> Result<bool, RerunNonErased> {
1366        if self.typing_mode().is_erased_not_coherence() {
1367            match self.opaque_accesses.rerun_always(RerunReason::MayUseUnstableFeature)? {}
1368        }
1369
1370        Ok(may_use_unstable_feature(&**self.delegate, param_env, symbol))
1371    }
1372
1373    pub(crate) fn opaques_with_sub_unified_hidden_type(
1374        &self,
1375        self_ty: I::Ty,
1376    ) -> Vec<ty::OpaqueAliasTy<I>> {
1377        if let ty::Infer(ty::TyVar(vid)) = self_ty.kind() {
1378            self.delegate.opaques_with_sub_unified_hidden_type(vid)
1379        } else {
1380            ::alloc::vec::Vec::new()vec![]
1381        }
1382    }
1383
1384    /// To return the constraints of a canonical query to the caller, we canonicalize:
1385    ///
1386    /// - `var_values`: a map from bound variables in the canonical goal to
1387    ///   the values inferred while solving the instantiated goal.
1388    /// - `external_constraints`: additional constraints which aren't expressible
1389    ///   using simple unification of inference variables.
1390    ///
1391    /// This takes the `shallow_certainty` which represents whether we're confident
1392    /// that the final result of the current goal only depends on the nested goals.
1393    ///
1394    /// In case this is `Certainty::Maybe`, there may still be additional nested goals
1395    /// or inference constraints required for this candidate to be hold. The candidate
1396    /// always requires all already added constraints and nested goals.
1397    x;#[instrument(level = "trace", skip(self), ret)]
1398    pub(in crate::solve) fn evaluate_added_goals_and_make_canonical_response(
1399        &mut self,
1400        shallow_certainty: Certainty,
1401    ) -> QueryResultOrRerunNonErased<I> {
1402        self.inspect.make_canonical_response(shallow_certainty);
1403
1404        let goals_certainty = self.try_evaluate_added_goals()?;
1405        assert_eq!(
1406            self.tainted,
1407            Ok(()),
1408            "EvalCtxt is tainted -- nested goals may have been dropped in a \
1409            previous call to `try_evaluate_added_goals!`"
1410        );
1411
1412        let goals_certainty = match self.delegate.cx().assumptions_on_binders() {
1413            true => {
1414                let certainty = self.eagerly_handle_placeholders()?;
1415                certainty.and(goals_certainty)
1416            }
1417            false => {
1418                // We only check for leaks from universes which were entered inside
1419                // of the query.
1420                self.delegate.leak_check(self.max_input_universe).map_err(|NoSolution| {
1421                    trace!("failed the leak check");
1422                    NoSolution
1423                })?;
1424
1425                goals_certainty
1426            }
1427        };
1428
1429        let (certainty, normalization_nested_goals) =
1430            match (self.current_goal_kind, shallow_certainty) {
1431                // When normalizing, we've replaced the expected term with an unconstrained
1432                // inference variable. This means that we dropped information which could
1433                // have been important. We handle this by instead returning the nested goals
1434                // to the caller, where they are then handled. We only do so if we do not
1435                // need to recompute the `NormalizesTo` goal afterwards to avoid repeatedly
1436                // uplifting its nested goals. This is the case if the `shallow_certainty` is
1437                // `Certainty::Yes`.
1438                (CurrentGoalKind::ProjectionComputeAssocTermCandidate, Certainty::Yes) => {
1439                    let goals = std::mem::take(&mut self.nested_goals);
1440                    // As we return all ambiguous nested goals, we can ignore the certainty
1441                    // returned by `self.try_evaluate_added_goals()`.
1442                    if goals.is_empty() {
1443                        assert!(matches!(goals_certainty, Certainty::Yes));
1444                    }
1445                    (
1446                        Certainty::Yes,
1447                        NestedNormalizationGoals(
1448                            goals.into_iter().map(|(s, g, _)| (s, g)).collect(),
1449                        ),
1450                    )
1451                }
1452                _ => {
1453                    let certainty = shallow_certainty.and(goals_certainty);
1454                    (certainty, NestedNormalizationGoals::empty())
1455                }
1456            };
1457
1458        if let Certainty::Maybe(
1459            maybe_info @ MaybeInfo {
1460                cause: MaybeCause::Overflow { keep_constraints: false, .. },
1461                opaque_types_jank: _,
1462                stalled_on_coroutines: _,
1463            },
1464        ) = certainty
1465        {
1466            // If we have overflow, it's probable that we're substituting a type
1467            // into itself infinitely and any partial substitutions in the query
1468            // response are probably not useful anyways, so just return an empty
1469            // query response.
1470            //
1471            // This may prevent us from potentially useful inference, e.g.
1472            // 2 candidates, one ambiguous and one overflow, which both
1473            // have the same inference constraints.
1474            //
1475            // Changing this to retain some constraints in the future
1476            // won't be a breaking change, so this is good enough for now.
1477            return Ok(self.make_ambiguous_response_no_constraints(maybe_info));
1478        }
1479
1480        let external_constraints =
1481            self.compute_external_query_constraints(certainty, normalization_nested_goals);
1482        let (var_values, mut external_constraints) =
1483            eager_resolve_vars(&**self.delegate, (self.var_values, external_constraints));
1484
1485        // Remove any trivial or duplicated region constraints once we've resolved regions
1486        let mut unique = HashSet::default();
1487        if let ExternalRegionConstraints::Old(r) = &mut external_constraints.region_constraints {
1488            r.retain(|(outlives, _)| !outlives.is_trivial() && unique.insert(*outlives));
1489        }
1490
1491        let canonical = canonicalize_response(
1492            self.delegate,
1493            self.max_input_universe,
1494            Response {
1495                var_values,
1496                certainty,
1497                external_constraints: self.cx().mk_external_constraints(external_constraints),
1498            },
1499        );
1500
1501        Ok(canonical)
1502    }
1503
1504    /// Constructs a totally unconstrained, ambiguous response to a goal.
1505    ///
1506    /// Take care when using this, since often it's useful to respond with
1507    /// ambiguity but return constrained variables to guide inference.
1508    pub(in crate::solve) fn make_ambiguous_response_no_constraints(
1509        &self,
1510        maybe: MaybeInfo,
1511    ) -> CanonicalResponse<I> {
1512        response_no_constraints_raw(
1513            self.cx(),
1514            self.max_input_universe,
1515            self.var_kinds,
1516            Certainty::Maybe(maybe),
1517        )
1518    }
1519
1520    /// Computes the region constraints and *new* opaque types registered when
1521    /// proving a goal.
1522    ///
1523    /// If an opaque was already constrained before proving this goal, then the
1524    /// external constraints do not need to record that opaque, since if it is
1525    /// further constrained by inference, that will be passed back in the var
1526    /// values.
1527    x;#[instrument(level = "trace", skip(self), ret)]
1528    fn compute_external_query_constraints(
1529        &self,
1530        certainty: Certainty,
1531        normalization_nested_goals: NestedNormalizationGoals<I>,
1532    ) -> ExternalConstraintsData<I> {
1533        // We only return region constraints once the certainty is `Yes`. This
1534        // is necessary as we may drop nested goals on ambiguity, which may result
1535        // in unconstrained inference variables in the region constraints. It also
1536        // prevents us from emitting duplicate region constraints, avoiding some
1537        // unnecessary work. This slightly weakens the leak check in case it uses
1538        // region constraints from an ambiguous nested goal. This is tested in both
1539        // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-5-ambig.rs` and
1540        // `tests/ui/higher-ranked/leak-check/leak-check-in-selection-6-ambig-unify.rs`.
1541        let region_constraints = if self.cx().assumptions_on_binders() {
1542            ExternalRegionConstraints::NextGen(if let Certainty::Yes = certainty {
1543                self.delegate.get_solver_region_constraint()
1544            } else {
1545                RegionConstraint::new_true()
1546            })
1547        } else {
1548            ExternalRegionConstraints::Old(if let Certainty::Yes = certainty {
1549                self.delegate.make_deduplicated_region_constraints()
1550            } else {
1551                vec![]
1552            })
1553        };
1554
1555        // We only return *newly defined* opaque types from canonical queries.
1556        //
1557        // Constraints for any existing opaque types are already tracked by changes
1558        // to the `var_values`.
1559        let opaque_types = self
1560            .delegate
1561            .clone_opaque_types_added_since(self.initial_opaque_types_storage_num_entries);
1562
1563        if self.typing_mode().is_erased_not_coherence() {
1564            assert!(opaque_types.is_empty());
1565        }
1566
1567        ExternalConstraintsData { region_constraints, opaque_types, normalization_nested_goals }
1568    }
1569
1570    pub(super) fn normalize<T: TypeFoldable<I>>(
1571        &mut self,
1572        source: GoalSource,
1573        param_env: I::ParamEnv,
1574        value: ty::Unnormalized<I, T>,
1575    ) -> Result<T, NoSolutionOrRerunNonErased> {
1576        let value = self.delegate.resolve_vars_if_possible(value.skip_normalization());
1577
1578        if !self.cx().renormalize_rigid_aliases() && !value.has_non_rigid_aliases() {
1579            return Ok(value);
1580        }
1581
1582        // To drop the mutable borrow of self early.
1583        let infcx = self.delegate.deref();
1584        let mut folder = NormalizationFolder::new(infcx, ::alloc::vec::Vec::new()vec![], |alias_term| {
1585            let infer_term = self.next_term_infer_of_alias_kind(alias_term);
1586            let pred = ty::ProjectionPredicate { projection_term: alias_term, term: infer_term };
1587            let goal = Goal::new(self.cx(), param_env, pred);
1588            self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
1589            let GoalEvaluation { goal, certainty, has_changed: _, stalled_on } =
1590                self.evaluate_goal(source, goal, None)?;
1591            let normalization_was_ambiguous = match certainty {
1592                Certainty::Yes => NormalizationWasAmbiguous::No,
1593                Certainty::Maybe(_) => {
1594                    self.nested_goals.push((source, goal, stalled_on));
1595                    NormalizationWasAmbiguous::Yes
1596                }
1597            };
1598
1599            Ok((self.resolve_vars_if_possible(infer_term), normalization_was_ambiguous))
1600        });
1601        value.try_fold_with(&mut folder)
1602    }
1603}
1604
1605#[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)]
1606enum RerunDecision {
1607    Yes,
1608    No,
1609    EagerlyPropagateToParent,
1610}
1611
1612x;#[tracing::instrument(ret)]
1613fn should_rerun_after_erased_canonicalization<I: Interner>(
1614    AccessedOpaques { reason: _, rerun }: AccessedOpaques<I>,
1615    original_typing_mode: TypingMode<I>,
1616    parent_opaque_types: &[(OpaqueTypeKey<I>, I::Ty)],
1617) -> RerunDecision {
1618    let parent_opaque_def_ids = parent_opaque_types.iter().map(|(key, _)| key.def_id.into());
1619    let opaque_in_storage = |opaques: I::LocalDefIds, def_ids: SmallCopyList<_>| {
1620        if def_ids.as_ref().is_empty() {
1621            RerunDecision::No
1622        } else if opaques
1623            .iter()
1624            .chain(parent_opaque_def_ids)
1625            .any(|opaque| def_ids.as_ref().contains(&opaque))
1626        {
1627            RerunDecision::Yes
1628        } else {
1629            RerunDecision::No
1630        }
1631    };
1632    let any_opaque_has_infer_as_hidden = || {
1633        if parent_opaque_types.iter().any(|(_, ty)| ty.is_ty_var()) {
1634            RerunDecision::Yes
1635        } else {
1636            RerunDecision::No
1637        }
1638    };
1639
1640    match (rerun, original_typing_mode) {
1641        // =============================
1642        (RerunCondition::Never, _) => RerunDecision::No,
1643        // =============================
1644        (_, TypingMode::ErasedNotCoherence(MayBeErased)) => RerunDecision::EagerlyPropagateToParent,
1645        // =============================
1646        // In coherence, we never switch to erased mode, so we will never register anything
1647        // in the rerun state, so we should've taken the first branch of this match
1648        (_, TypingMode::Coherence) => unreachable!(),
1649        // =============================
1650        (RerunCondition::Always, _) => RerunDecision::Yes,
1651        // =============================
1652        (RerunCondition::OpaqueInStorage(..), TypingMode::PostAnalysis | TypingMode::Codegen) => {
1653            RerunDecision::Yes
1654        }
1655        (
1656            RerunCondition::OpaqueInStorage(defids),
1657            TypingMode::PostBorrowck { defined_opaque_types: opaques }
1658            | TypingMode::Typeck { defining_opaque_types_and_generators: opaques }
1659            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: opaques },
1660        ) => opaque_in_storage(opaques, defids),
1661        // =============================
1662        (RerunCondition::AnyOpaqueHasInferAsHidden, TypingMode::Typeck { .. }) => {
1663            any_opaque_has_infer_as_hidden()
1664        }
1665        (
1666            RerunCondition::AnyOpaqueHasInferAsHidden,
1667            TypingMode::PostBorrowck { .. }
1668            | TypingMode::PostAnalysis
1669            | TypingMode::Codegen
1670            | TypingMode::PostTypeckUntilBorrowck { .. },
1671        ) => RerunDecision::No,
1672        // =============================
1673        (
1674            RerunCondition::OpaqueInStorageOrAnyOpaqueHasInferAsHidden(_),
1675            TypingMode::PostAnalysis | TypingMode::Codegen,
1676        ) => RerunDecision::Yes,
1677        (
1678            RerunCondition::OpaqueInStorageOrAnyOpaqueHasInferAsHidden(defids),
1679            TypingMode::Typeck { defining_opaque_types_and_generators: opaques },
1680        ) => {
1681            if let RerunDecision::Yes = any_opaque_has_infer_as_hidden() {
1682                RerunDecision::Yes
1683            } else if let RerunDecision::Yes = opaque_in_storage(opaques, defids) {
1684                RerunDecision::Yes
1685            } else {
1686                RerunDecision::No
1687            }
1688        }
1689        (
1690            RerunCondition::OpaqueInStorageOrAnyOpaqueHasInferAsHidden(defids),
1691            TypingMode::PostBorrowck { defined_opaque_types: opaques }
1692            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: opaques },
1693        ) => opaque_in_storage(opaques, defids),
1694    }
1695}
1696
1697/// Do not call this directly, use the `tcx` query instead.
1698pub fn evaluate_root_goal_for_proof_tree_raw_provider<
1699    D: SolverDelegate<Interner = I>,
1700    I: Interner,
1701>(
1702    cx: I,
1703    canonical_goal: CanonicalInput<I>,
1704) -> (QueryResult<I>, I::Probe) {
1705    let mut inspect = inspect::ProofTreeBuilder::new();
1706    let (canonical_result, accessed_opaques) = SearchGraph::<D>::evaluate_root_goal_for_proof_tree(
1707        cx,
1708        cx.recursion_limit(),
1709        canonical_goal,
1710        &mut inspect,
1711    );
1712    let final_revision = inspect.unwrap();
1713
1714    if !!accessed_opaques.might_rerun() {
    ::core::panicking::panic("assertion failed: !accessed_opaques.might_rerun()")
};assert!(!accessed_opaques.might_rerun());
1715    (canonical_result, cx.mk_probe(final_revision))
1716}
1717
1718/// Evaluate a goal to build a proof tree.
1719///
1720/// This is a copy of [EvalCtxt::evaluate_goal_raw] which avoids relying on the
1721/// [EvalCtxt] and uses a separate cache.
1722pub(super) fn evaluate_root_goal_for_proof_tree<D: SolverDelegate<Interner = I>, I: Interner>(
1723    delegate: &D,
1724    goal: Goal<I, I::Predicate>,
1725    origin_span: I::Span,
1726) -> (Result<NestedNormalizationGoals<I>, NoSolution>, inspect::GoalEvaluation<I>) {
1727    let opaque_types = delegate.clone_opaque_types_lookup_table();
1728    let (goal, opaque_types) = eager_resolve_vars(&**delegate, (goal, opaque_types));
1729    let typing_mode = delegate.typing_mode_raw().assert_not_erased();
1730
1731    let (orig_values, canonical_goal) =
1732        canonicalize_goal(delegate, goal, &opaque_types, typing_mode.into());
1733
1734    let (canonical_result, final_revision) =
1735        delegate.cx().evaluate_root_goal_for_proof_tree_raw(canonical_goal);
1736
1737    let proof_tree = inspect::GoalEvaluation {
1738        uncanonicalized_goal: goal,
1739        orig_values,
1740        final_revision,
1741        result: canonical_result,
1742    };
1743
1744    let response = match canonical_result {
1745        Err(e) => return (Err(e), proof_tree),
1746        Ok(response) => response,
1747    };
1748
1749    let (normalization_nested_goals, _certainty) = instantiate_and_apply_query_response(
1750        delegate,
1751        goal.param_env,
1752        &proof_tree.orig_values,
1753        response,
1754        origin_span,
1755    );
1756
1757    (Ok(normalization_nested_goals), proof_tree)
1758}