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, 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, 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::search_graph::SearchGraph;
35use crate::solve::ty::may_use_unstable_feature;
36use crate::solve::{
37    CanonicalInput, CanonicalResponse, Certainty, ExternalConstraintsData, FIXPOINT_STEP_LIMIT,
38    Goal, GoalEvaluation, GoalSource, GoalStalledOn, HasChanged, MaybeCause,
39    NestedNormalizationGoals, NoSolution, QueryInput, QueryResult, Response, SucceededInErased,
40    VisibleForLeakCheck, inspect,
41};
42
43mod probe;
44mod solver_region_constraints;
45
46/// The kind of goal we're currently proving.
47///
48/// This has effects on cycle handling handling and on how we compute
49/// query responses, see the variant descriptions for more info.
50#[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)]
51enum CurrentGoalKind {
52    Misc,
53    /// We're proving an trait goal for a coinductive trait, either an auto trait or `Sized`.
54    ///
55    /// These are currently the only goals whose impl where-clauses are considered to be
56    /// productive steps.
57    CoinductiveTrait,
58    // FIXME: Consider renaming `PredicateKind::NormalizesTo` to match with this
59    /// Unlike other goals, `NormalizesTo` goals aren't independent goals but just implementation
60    /// details for handling projections of associated terms. When we encounter a `Projection` goal
61    /// whose `projection_term` is an associated term, we create a `NormalizesTo` goal whose
62    /// expected term is fully unconstrained and evaluate it.
63    ///
64    /// This would weaken inference however, as the nested goals of normalizes-to never get the
65    /// inference constraints from the actual expected term. We just gather candidates from the
66    /// normalizes-to goal and return any ambiguous nested goals of it to the caller (`Projection
67    /// goal`). The caller handle and evaluate them as if they were its own nested goals.
68    ///
69    /// Because of this, evaluating a normalizes-to goal is computing candidates for projection of
70    /// an associated term and it never leaks out of the solver.
71    ProjectionComputeAssocTermCandidate,
72}
73
74impl CurrentGoalKind {
75    fn from_query_input<I: Interner>(cx: I, input: QueryInput<I, I::Predicate>) -> CurrentGoalKind {
76        match input.goal.predicate.kind().skip_binder() {
77            ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
78                if cx.trait_is_coinductive(pred.trait_ref.def_id) {
79                    CurrentGoalKind::CoinductiveTrait
80                } else {
81                    CurrentGoalKind::Misc
82                }
83            }
84            ty::PredicateKind::NormalizesTo(_) => {
85                CurrentGoalKind::ProjectionComputeAssocTermCandidate
86            }
87            _ => CurrentGoalKind::Misc,
88        }
89    }
90}
91
92#[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)]
93enum RerunDecision {
94    Yes,
95    No,
96    EagerlyPropagateToParent,
97}
98pub struct EvalCtxt<'a, D, I = <D as SolverDelegate>::Interner>
99where
100    D: SolverDelegate<Interner = I>,
101    I: Interner,
102{
103    /// The inference context that backs (mostly) inference and placeholder terms
104    /// instantiated while solving goals.
105    ///
106    /// NOTE: The `InferCtxt` that backs the `EvalCtxt` is intentionally private,
107    /// because the `InferCtxt` is much more general than `EvalCtxt`. Methods such
108    /// as  `take_registered_region_obligations` can mess up query responses,
109    /// using `At::normalize` is totally wrong, calling `evaluate_root_goal` can
110    /// cause coinductive unsoundness, etc.
111    ///
112    /// Methods that are generally of use for trait solving are *intentionally*
113    /// re-declared through the `EvalCtxt` below, often with cleaner signatures
114    /// since we don't care about things like `ObligationCause`s and `Span`s here.
115    /// If some `InferCtxt` method is missing, please first think defensively about
116    /// the method's compatibility with this solver, or if an existing one does
117    /// the job already.
118    delegate: &'a D,
119
120    /// The variable info for the `var_values`, only used to make an ambiguous response
121    /// with no constraints.
122    var_kinds: I::CanonicalVarKinds,
123
124    /// What kind of goal we're currently computing, see the enum definition
125    /// for more info.
126    current_goal_kind: CurrentGoalKind,
127    pub(super) var_values: CanonicalVarValues<I>,
128
129    /// The highest universe index nameable by the caller.
130    ///
131    /// When we enter a new binder inside of the query we create new universes
132    /// which the caller cannot name. We have to be careful with variables from
133    /// these new universes when creating the query response.
134    ///
135    /// Both because these new universes can prevent us from reaching a fixpoint
136    /// if we have a coinductive cycle and because that's the only way we can return
137    /// new placeholders to the caller.
138    pub(super) max_input_universe: ty::UniverseIndex,
139    /// The opaque types from the canonical input. We only need to return opaque types
140    /// which have been added to the storage while evaluating this goal.
141    pub(super) initial_opaque_types_storage_num_entries:
142        <D::Infcx as InferCtxtLike>::OpaqueTypeStorageEntries,
143
144    pub(super) search_graph: &'a mut SearchGraph<D>,
145
146    nested_goals: Vec<(GoalSource, Goal<I, I::Predicate>, Option<GoalStalledOn<I>>)>,
147
148    pub(super) origin_span: I::Span,
149
150    // Has this `EvalCtxt` errored out with `NoSolution` in `try_evaluate_added_goals`?
151    //
152    // If so, then it can no longer be used to make a canonical query response,
153    // since subsequent calls to `try_evaluate_added_goals` have possibly dropped
154    // ambiguous goals. Instead, a probe needs to be introduced somewhere in the
155    // evaluation code.
156    tainted: Result<(), NoSolution>,
157
158    /// Tracks accesses of opaque types while in [`TypingMode::ErasedNotCoherence`].
159    pub(super) opaque_accesses: AccessedOpaques<I>,
160
161    pub(super) inspect: inspect::EvaluationStepBuilder<D>,
162}
163
164#[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)]
165#[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))]
166pub enum GenerateProofTree {
167    Yes,
168    No,
169}
170
171pub trait SolverDelegateEvalExt: SolverDelegate {
172    /// Evaluates a goal from **outside** of the trait solver.
173    ///
174    /// Using this while inside of the solver is wrong as it uses a new
175    /// search graph which would break cycle detection.
176    fn evaluate_root_goal(
177        &self,
178        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
179        span: <Self::Interner as Interner>::Span,
180        stalled_on: Option<GoalStalledOn<Self::Interner>>,
181    ) -> Result<GoalEvaluation<Self::Interner>, NoSolution>;
182
183    /// Checks whether evaluating `goal` may hold while treating not-yet-defined
184    /// opaque types as being kind of rigid.
185    ///
186    /// See the comment on [OpaqueTypesJank] for more details.
187    fn root_goal_may_hold_opaque_types_jank(
188        &self,
189        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
190    ) -> bool;
191
192    /// Check whether evaluating `goal` with a depth of `root_depth` may
193    /// succeed. This only returns `false` if the goal is guaranteed to
194    /// not hold. In case evaluation overflows and fails with ambiguity this
195    /// returns `true`.
196    ///
197    /// This is only intended to be used as a performance optimization
198    /// in coherence checking.
199    fn root_goal_may_hold_with_depth(
200        &self,
201        root_depth: usize,
202        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
203    ) -> bool;
204
205    // FIXME: This is only exposed because we need to use it in `analyse.rs`
206    // which is not yet uplifted. Once that's done, we should remove this.
207    fn evaluate_root_goal_for_proof_tree(
208        &self,
209        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
210        span: <Self::Interner as Interner>::Span,
211    ) -> (
212        Result<NestedNormalizationGoals<Self::Interner>, NoSolution>,
213        inspect::GoalEvaluation<Self::Interner>,
214    );
215}
216
217impl<D, I> SolverDelegateEvalExt for D
218where
219    D: SolverDelegate<Interner = I>,
220    I: Interner,
221{
222    x;#[instrument(level = "debug", skip(self), ret)]
223    fn evaluate_root_goal(
224        &self,
225        goal: Goal<I, I::Predicate>,
226        span: I::Span,
227        stalled_on: Option<GoalStalledOn<I>>,
228    ) -> Result<GoalEvaluation<I>, NoSolution> {
229        let result = EvalCtxt::enter_root(self, self.cx().recursion_limit(), span, |ecx| {
230            ecx.evaluate_goal(GoalSource::Misc, goal, stalled_on)
231        });
232
233        match result {
234            Ok(i) => Ok(i),
235            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Err(NoSolution),
236            Err(NoSolutionOrRerunNonErased::RerunNonErased(_)) => {
237                unreachable!("this never happens at the root, we're never in erased mode here");
238            }
239        }
240    }
241
242    x;#[instrument(level = "debug", skip(self), ret)]
243    fn root_goal_may_hold_opaque_types_jank(
244        &self,
245        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
246    ) -> bool {
247        self.probe(|| {
248            EvalCtxt::enter_root(self, self.cx().recursion_limit(), I::Span::dummy(), |ecx| {
249                ecx.evaluate_goal(GoalSource::Misc, goal, None)
250            })
251            .is_ok_and(|r| match r.certainty {
252                Certainty::Yes => true,
253                Certainty::Maybe(MaybeInfo {
254                    cause: _,
255                    opaque_types_jank,
256                    stalled_on_coroutines: _,
257                }) => match opaque_types_jank {
258                    OpaqueTypesJank::AllGood => true,
259                    OpaqueTypesJank::ErrorIfRigidSelfTy => false,
260                },
261            })
262        })
263    }
264
265    fn root_goal_may_hold_with_depth(
266        &self,
267        root_depth: usize,
268        goal: Goal<Self::Interner, <Self::Interner as Interner>::Predicate>,
269    ) -> bool {
270        self.probe(|| {
271            EvalCtxt::enter_root(self, root_depth, I::Span::dummy(), |ecx| {
272                ecx.evaluate_goal(GoalSource::Misc, goal, None)
273            })
274        })
275        .is_ok()
276    }
277
278    #[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(278u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&["goal", "span"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    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);
            self.nested_goals.push((source, goal, None));
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(self))]
1054    pub(super) fn add_goal(
1055        &mut self,
1056        source: GoalSource,
1057        mut goal: Goal<I, I::Predicate>,
1058    ) -> Result<(), NoSolutionOrRerunNonErased> {
1059        goal.predicate = self.normalize(
1060            GoalSource::NormalizeGoal(self.step_kind_for_source(source)),
1061            goal.param_env,
1062            ty::Unnormalized::new_wip(goal.predicate),
1063        )?;
1064        self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal);
1065        self.nested_goals.push((source, goal, None));
1066        Ok(())
1067    }
1068
1069    #[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(1069u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::eval_ctxt"),
                                    ::tracing_core::field::FieldSet::new(&["source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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