Skip to main content

rustc_next_trait_solver/solve/assembly/
mod.rs

1//! Code shared by trait and projection goals for candidate assembly.
2
3pub(super) mod structural_traits;
4
5use std::cell::Cell;
6use std::ops::ControlFlow;
7
8use derive_where::derive_where;
9use rustc_type_ir::inherent::*;
10use rustc_type_ir::lang_items::SolverTraitLangItem;
11use rustc_type_ir::search_graph::CandidateHeadUsages;
12use rustc_type_ir::solve::{
13    AliasBoundKind, MaybeInfo, NoSolutionOrRerunNonErased, QueryResultOrRerunNonErased,
14    RerunNonErased, RerunReason, RerunResultExt, SizedTraitKind, StalledOnCoroutines,
15};
16use rustc_type_ir::{
17    self as ty, AliasTy, Const, Interner, MayBeErased, Region, TypeFlags, TypeFoldable, TypeFolder,
18    TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
19    TypingMode, Unnormalized, Upcast, elaborate,
20};
21use tracing::{debug, instrument};
22
23use super::trait_goals::TraitGoalProvenVia;
24use super::{has_only_region_constraints, inspect};
25use crate::delegate::SolverDelegate;
26use crate::solve::assembly::structural_traits::AmbiguousOrRerunNonErased;
27use crate::solve::inspect::ProbeKind;
28use crate::solve::{
29    BuiltinImplSource, CandidateSource, CanonicalResponse, Certainty, EvalCtxt, Goal, GoalSource,
30    MaybeCause, NoSolution, OpaqueTypesJank, ParamEnvSource, QueryResult,
31    has_no_inference_or_external_constraints,
32};
33
34/// A candidate is a possible way to prove a goal.
35///
36/// It consists of both the `source`, which describes how that goal would be proven,
37/// and the `result` when using the given `source`.
38#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for Candidate<I> where I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            Candidate {
                source: ref __field_source,
                result: ref __field_result,
                head_usages: ref __field_head_usages } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "Candidate");
                ::core::fmt::DebugStruct::field(&mut __builder, "source",
                    __field_source);
                ::core::fmt::DebugStruct::field(&mut __builder, "result",
                    __field_result);
                ::core::fmt::DebugStruct::field(&mut __builder, "head_usages",
                    __field_head_usages);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Debug; I: Interner)]
39pub(super) struct Candidate<I: Interner> {
40    pub(super) source: CandidateSource<I>,
41    pub(super) result: CanonicalResponse<I>,
42    pub(super) head_usages: CandidateHeadUsages,
43}
44
45/// Methods used to assemble candidates for either trait or projection goals.
46pub(super) trait GoalKind<D, I = <D as SolverDelegate>::Interner>:
47    TypeFoldable<I> + Copy + Eq + std::fmt::Display
48where
49    D: SolverDelegate<Interner = I>,
50    I: Interner,
51{
52    fn self_ty(self) -> I::Ty;
53
54    fn trait_ref(self, cx: I) -> ty::TraitRef<I>;
55
56    fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self;
57
58    fn trait_def_id(self, cx: I) -> I::TraitId;
59
60    /// Consider a clause, which consists of a "assumption" and some "requirements",
61    /// to satisfy a goal. If the requirements hold, then attempt to satisfy our
62    /// goal by equating it with the assumption.
63    fn probe_and_consider_implied_clause(
64        ecx: &mut EvalCtxt<'_, D>,
65        parent_source: CandidateSource<I>,
66        goal: Goal<I, Self>,
67        assumption: I::Clause,
68        requirements: impl IntoIterator<Item = (GoalSource, Goal<I, I::Predicate>)>,
69    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
70        Self::probe_and_match_goal_against_assumption(ecx, parent_source, goal, assumption, |ecx| {
71            for (nested_source, goal) in requirements {
72                ecx.add_goal(nested_source, goal)?;
73            }
74            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
75        })
76    }
77
78    /// Consider a clause specifically for a `dyn Trait` self type. This requires
79    /// additionally checking all of the supertraits and object bounds to hold,
80    /// since they're not implied by the well-formedness of the object type.
81    /// `NormalizesTo` overrides this to not check the supertraits for backwards
82    /// compatibility with the old solver. cc trait-system-refactor-initiative#245.
83    fn probe_and_consider_object_bound_candidate(
84        ecx: &mut EvalCtxt<'_, D>,
85        source: CandidateSource<I>,
86        goal: Goal<I, Self>,
87        assumption: I::Clause,
88    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
89        // We inline much of `probe_and_match_goal_against_assumption` and
90        // `TraitPredicate::match_assumption` here, as we never encounter
91        // `Sized` or `MetaSized` goals here, and we need to equate `goal`
92        // and `assumption`'s trait refs directly inside this function in
93        // order to prevent unsoundness (see below).
94
95        let goal_lang_item = ecx.cx().as_trait_lang_item(goal.predicate.trait_def_id(ecx.cx()));
96        Self::fast_reject_assumption(ecx, goal, goal_lang_item, assumption)?;
97
98        ecx.probe_trait_candidate(source).enter(|ecx| {
99            let cx = ecx.cx();
100            let ty::Dynamic(bounds, _) = goal.predicate.self_ty().kind() else {
101                {
    ::core::panicking::panic_fmt(format_args!("expected object type in `probe_and_consider_object_bound_candidate`"));
};panic!("expected object type in `probe_and_consider_object_bound_candidate`");
102            };
103
104            let trait_ref = assumption.kind().map_bound(|clause| match clause {
105                ty::ClauseKind::Trait(pred) => pred.trait_ref,
106                ty::ClauseKind::Projection(proj) => proj.projection_term.trait_ref(cx),
107
108                ty::ClauseKind::RegionOutlives(..)
109                | ty::ClauseKind::TypeOutlives(..)
110                | ty::ClauseKind::ConstArgHasType(..)
111                | ty::ClauseKind::WellFormed(..)
112                | ty::ClauseKind::ConstEvaluatable(..)
113                | ty::ClauseKind::HostEffect(..)
114                | ty::ClauseKind::UnstableFeature(..) => {
115                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected trait or projection predicate as an assumption")));
}unreachable!("expected trait or projection predicate as an assumption")
116                }
117            });
118
119            // If we need to prove `dyn for<'x> Trait<'x> + '?temp: Trait<'static>` with
120            //
121            // ```rs
122            // trait Trait<'a>: 'a {}
123            // ```
124            //
125            // we have the goal's trait ref as `Trait<'static>` and a theoretical impl
126            // resembling:
127            //
128            // ```rs
129            // impl<'s, 'hr> Trait<'hr> for dyn for<'x> Trait<'x> + 's
130            // where
131            //     dyn for<'a> Trait<'a> + 's: 'hr
132            // {}
133            // ```
134            //
135            // where 'hr is our bound var. The where-clause elaborates to `'s: 'hr`;
136            // in this case we have 's := '?temp. Instantiating the binder gives us
137            // 'hr := '?infer, and our goal has 'hr := 'static, so we need to equate
138            // the instantiated trait ref to the goal in order to get '?infer := 'static,
139            // since what we want is the constraint `'?temp: 'static`.
140            //
141            // If we instead passed the binder to predicates_for_object_candidate and let
142            // it instantiate the binder itself, we would lose '?infer := 'static, since
143            // predicates_for_object_candidate has no way of equating the trait ref with
144            // the goal. We would simply have 'hr := '?infer, giving us the constraint
145            // `?temp: '?infer`, which is satisfiable for any lifetime, leading to
146            // unsoundness: trait-system-refactor-initiative#295.
147            let trait_ref = ecx.instantiate_binder_with_infer(trait_ref);
148            ecx.eq(goal.param_env, goal.predicate.trait_ref(cx), trait_ref)?;
149
150            match structural_traits::predicates_for_object_candidate(
151                ecx,
152                goal.param_env,
153                trait_ref,
154                bounds,
155            ) {
156                Ok(requirements) => {
157                    ecx.add_goals(GoalSource::ImplWhereBound, requirements)?;
158                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
159                }
160                Err(AmbiguousOrRerunNonErased::Ambiguous) => {
161                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
162                }
163                Err(AmbiguousOrRerunNonErased::RerunNonErased(rerun)) => Err(rerun.into()),
164            }
165        })
166    }
167
168    /// Assemble additional assumptions for an alias that are not included
169    /// in the item bounds of the alias. For now, this is limited to the
170    /// `explicit_implied_const_bounds` for an associated type.
171    fn consider_additional_alias_assumptions(
172        ecx: &mut EvalCtxt<'_, D>,
173        goal: Goal<I, Self>,
174        alias_ty: ty::AliasTy<I>,
175    ) -> Vec<Candidate<I>>;
176
177    fn probe_and_consider_param_env_candidate(
178        ecx: &mut EvalCtxt<'_, D>,
179        goal: Goal<I, Self>,
180        assumption: I::Clause,
181    ) -> Result<Result<Candidate<I>, CandidateHeadUsages>, RerunNonErased> {
182        // Dealing with `ParamEnv` candidates is a bit of a mess as we need to lazily
183        // check whether the candidate is global while considering normalization.
184        //
185        // We need to write into `source` inside of `match_assumption`, but need to access it
186        // in `probe` even if the candidate does not apply before we get there. We handle this
187        // by using a `Cell` here. We only ever write into it inside of `match_assumption`.
188        let source = Cell::new(CandidateSource::ParamEnv(ParamEnvSource::Global));
189        let (result, head_usages) = ecx
190            .probe(|result: &QueryResult<I>| inspect::ProbeKind::TraitCandidate {
191                source: source.get(),
192                result: *result,
193            })
194            .enter_single_candidate(|ecx| {
195                Self::match_assumption(
196                    ecx,
197                    goal,
198                    assumption,
199                    |ecx| -> Result<_, NoSolutionOrRerunNonErased> {
200                        ecx.try_evaluate_added_goals()?;
201                        let (src, certainty) =
202                            ecx.characterize_param_env_assumption(goal.param_env, assumption)?;
203                        source.set(src);
204                        ecx.evaluate_added_goals_and_make_canonical_response(certainty)
205                    },
206                )
207            });
208
209        Ok(match result.map_err_to_rerun()? {
210            Ok(result) => Ok(Candidate { source: source.get(), result, head_usages }),
211            Err(NoSolution) => Err(head_usages),
212        })
213    }
214
215    /// Try equating an assumption predicate against a goal's predicate. If it
216    /// holds, then execute the `then` callback, which should do any additional
217    /// work, then produce a response (typically by executing
218    /// [`EvalCtxt::evaluate_added_goals_and_make_canonical_response`]).
219    fn probe_and_match_goal_against_assumption(
220        ecx: &mut EvalCtxt<'_, D>,
221        source: CandidateSource<I>,
222        goal: Goal<I, Self>,
223        assumption: I::Clause,
224        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
225    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
226        let goal_lang_item = ecx.cx().as_trait_lang_item(goal.predicate.trait_def_id(ecx.cx()));
227        Self::fast_reject_assumption(ecx, goal, goal_lang_item, assumption)?;
228
229        ecx.probe_trait_candidate(source)
230            .enter(|ecx| Self::match_assumption(ecx, goal, assumption, then))
231    }
232
233    /// Try to reject the assumption based off of simple heuristics, such as [`ty::ClauseKind`]
234    /// and `DefId`.
235    fn fast_reject_assumption(
236        ecx: &mut EvalCtxt<'_, D>,
237        goal: Goal<I, Self>,
238        goal_lang_item: Option<SolverTraitLangItem>,
239        assumption: I::Clause,
240    ) -> Result<(), NoSolution>;
241
242    /// Relate the goal and assumption.
243    fn match_assumption(
244        ecx: &mut EvalCtxt<'_, D>,
245        goal: Goal<I, Self>,
246        assumption: I::Clause,
247        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
248    ) -> QueryResultOrRerunNonErased<I>;
249
250    /// Note: `goal_trait_ref` is derived from `goal`. Nonetheless, because
251    /// `consider_impl_candidate` is always called in a loop, we precompute `goal_trait_ref` once
252    /// and pass it in next to `goal` because the computation is expensive and loop-invariant.
253    fn consider_impl_candidate(
254        ecx: &mut EvalCtxt<'_, D>,
255        goal: Goal<I, Self>,
256        goal_trait_ref: ty::TraitRef<I>,
257        impl_def_id: I::ImplId,
258        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
259    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
260
261    /// If the predicate contained an error, we want to avoid emitting unnecessary trait
262    /// errors but still want to emit errors for other trait goals. We have some special
263    /// handling for this case.
264    ///
265    /// Trait goals always hold while projection goals never do. This is a bit arbitrary
266    /// but prevents incorrect normalization while hiding any trait errors.
267    fn consider_error_guaranteed_candidate(
268        ecx: &mut EvalCtxt<'_, D>,
269        goal: Goal<I, Self>,
270        guar: I::ErrorGuaranteed,
271    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
272
273    /// A type implements an `auto trait` if its components do as well.
274    ///
275    /// These components are given by built-in rules from
276    /// [`structural_traits::instantiate_constituent_tys_for_auto_trait`].
277    fn consider_auto_trait_candidate(
278        ecx: &mut EvalCtxt<'_, D>,
279        goal: Goal<I, Self>,
280    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
281
282    /// A trait alias holds if the RHS traits and `where` clauses hold.
283    fn consider_trait_alias_candidate(
284        ecx: &mut EvalCtxt<'_, D>,
285        goal: Goal<I, Self>,
286    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
287
288    /// A type is `Sized` if its tail component is `Sized` and a type is `MetaSized` if its tail
289    /// component is `MetaSized`.
290    ///
291    /// These components are given by built-in rules from
292    /// [`structural_traits::instantiate_constituent_tys_for_sizedness_trait`].
293    fn consider_builtin_sizedness_candidates(
294        ecx: &mut EvalCtxt<'_, D>,
295        goal: Goal<I, Self>,
296        sizedness: SizedTraitKind,
297    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
298
299    /// A type is `Copy` or `Clone` if its components are `Copy` or `Clone`.
300    ///
301    /// These components are given by built-in rules from
302    /// [`structural_traits::instantiate_constituent_tys_for_copy_clone_trait`].
303    fn consider_builtin_copy_clone_candidate(
304        ecx: &mut EvalCtxt<'_, D>,
305        goal: Goal<I, Self>,
306    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
307
308    /// A type is a `FnPtr` if it is of `FnPtr` type.
309    fn consider_builtin_fn_ptr_trait_candidate(
310        ecx: &mut EvalCtxt<'_, D>,
311        goal: Goal<I, Self>,
312    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
313
314    /// A callable type (a closure, fn def, or fn ptr) is known to implement the `Fn<A>`
315    /// family of traits where `A` is given by the signature of the type.
316    fn consider_builtin_fn_trait_candidates(
317        ecx: &mut EvalCtxt<'_, D>,
318        goal: Goal<I, Self>,
319        kind: ty::ClosureKind,
320    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
321
322    /// An async closure is known to implement the `AsyncFn<A>` family of traits
323    /// where `A` is given by the signature of the type.
324    fn consider_builtin_async_fn_trait_candidates(
325        ecx: &mut EvalCtxt<'_, D>,
326        goal: Goal<I, Self>,
327        kind: ty::ClosureKind,
328    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
329
330    /// Compute the built-in logic of the `AsyncFnKindHelper` helper trait, which
331    /// is used internally to delay computation for async closures until after
332    /// upvar analysis is performed in HIR typeck.
333    fn consider_builtin_async_fn_kind_helper_candidate(
334        ecx: &mut EvalCtxt<'_, D>,
335        goal: Goal<I, Self>,
336    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
337
338    /// `Tuple` is implemented if the `Self` type is a tuple.
339    fn consider_builtin_tuple_candidate(
340        ecx: &mut EvalCtxt<'_, D>,
341        goal: Goal<I, Self>,
342    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
343
344    /// `Pointee` is always implemented.
345    ///
346    /// See the projection implementation for the `Metadata` types for all of
347    /// the built-in types. For structs, the metadata type is given by the struct
348    /// tail.
349    fn consider_builtin_pointee_candidate(
350        ecx: &mut EvalCtxt<'_, D>,
351        goal: Goal<I, Self>,
352    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
353
354    /// A coroutine (that comes from an `async` desugaring) is known to implement
355    /// `Future<Output = O>`, where `O` is given by the coroutine's return type
356    /// that was computed during type-checking.
357    fn consider_builtin_future_candidate(
358        ecx: &mut EvalCtxt<'_, D>,
359        goal: Goal<I, Self>,
360    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
361
362    /// A coroutine (that comes from a `gen` desugaring) is known to implement
363    /// `Iterator<Item = O>`, where `O` is given by the generator's yield type
364    /// that was computed during type-checking.
365    fn consider_builtin_iterator_candidate(
366        ecx: &mut EvalCtxt<'_, D>,
367        goal: Goal<I, Self>,
368    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
369
370    /// A coroutine (that comes from a `gen` desugaring) is known to implement
371    /// `FusedIterator`
372    fn consider_builtin_fused_iterator_candidate(
373        ecx: &mut EvalCtxt<'_, D>,
374        goal: Goal<I, Self>,
375    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
376
377    fn consider_builtin_async_iterator_candidate(
378        ecx: &mut EvalCtxt<'_, D>,
379        goal: Goal<I, Self>,
380    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
381
382    /// A coroutine (that doesn't come from an `async` or `gen` desugaring) is known to
383    /// implement `Coroutine<R, Yield = Y, Return = O>`, given the resume, yield,
384    /// and return types of the coroutine computed during type-checking.
385    fn consider_builtin_coroutine_candidate(
386        ecx: &mut EvalCtxt<'_, D>,
387        goal: Goal<I, Self>,
388    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
389
390    fn consider_builtin_discriminant_kind_candidate(
391        ecx: &mut EvalCtxt<'_, D>,
392        goal: Goal<I, Self>,
393    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
394
395    fn consider_builtin_destruct_candidate(
396        ecx: &mut EvalCtxt<'_, D>,
397        goal: Goal<I, Self>,
398    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
399
400    fn consider_builtin_transmute_candidate(
401        ecx: &mut EvalCtxt<'_, D>,
402        goal: Goal<I, Self>,
403    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
404
405    fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
406        ecx: &mut EvalCtxt<'_, D>,
407        goal: Goal<I, Self>,
408    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
409
410    fn consider_builtin_try_as_dyn_candidate(
411        ecx: &mut EvalCtxt<'_, D>,
412        goal: Goal<I, Self>,
413    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
414
415    /// Consider (possibly several) candidates to upcast or unsize a type to another
416    /// type, excluding the coercion of a sized type into a `dyn Trait`.
417    ///
418    /// We return the `BuiltinImplSource` for each candidate as it is needed
419    /// for unsize coercion in hir typeck and because it is difficult to
420    /// otherwise recompute this for codegen. This is a bit of a mess but the
421    /// easiest way to maintain the existing behavior for now.
422    fn consider_structural_builtin_unsize_candidates(
423        ecx: &mut EvalCtxt<'_, D>,
424        goal: Goal<I, Self>,
425    ) -> Result<Vec<Candidate<I>>, RerunNonErased>;
426
427    fn consider_builtin_field_candidate(
428        ecx: &mut EvalCtxt<'_, D>,
429        goal: Goal<I, Self>,
430    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
431}
432
433/// Allows callers of `assemble_and_evaluate_candidates` to choose whether to limit
434/// candidate assembly to param-env and alias-bound candidates.
435///
436/// On top of being a micro-optimization, as it avoids doing unnecessary work when
437/// a param-env trait bound candidate shadows impls for normalization, this is also
438/// required to prevent query cycles due to RPITIT inference. See the issue at:
439/// <https://github.com/rust-lang/trait-system-refactor-initiative/issues/173>.
440pub(super) enum AssembleCandidatesFrom {
441    All,
442    /// Only assemble candidates from the environment and alias bounds, ignoring
443    /// user-written and built-in impls. We only expect `ParamEnv` and `AliasBound`
444    /// candidates to be assembled.
445    EnvAndBounds,
446}
447
448impl AssembleCandidatesFrom {
449    fn should_assemble_impl_candidates(&self) -> bool {
450        match self {
451            AssembleCandidatesFrom::All => true,
452            AssembleCandidatesFrom::EnvAndBounds => false,
453        }
454    }
455}
456
457/// This is currently used to track the [CandidateHeadUsages] of all failed `ParamEnv`
458/// candidates. This is then used to ignore their head usages in case there's another
459/// always applicable `ParamEnv` candidate. Look at how `param_env_head_usages` is
460/// used in the code for more details.
461///
462/// We could easily extend this to also ignore head usages of other ignored candidates.
463/// However, we currently don't have any tests where this matters and the complexity of
464/// doing so does not feel worth it for now.
465#[derive(#[automatically_derived]impl ::core::fmt::Debug for FailedCandidateInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "FailedCandidateInfo", "param_env_head_usages",
            &&self.param_env_head_usages)
    }
}Debug)]
466pub(super) struct FailedCandidateInfo {
467    pub param_env_head_usages: CandidateHeadUsages,
468}
469
470impl<D, I> EvalCtxt<'_, D>
471where
472    D: SolverDelegate<Interner = I>,
473    I: Interner,
474{
475    // FIXME(#155443): This function should only ever return an error
476    // as we want to force a rerun when accessing opaques. We should change
477    // this file to revert all the newly added places which return `NoSolution`.
478    pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<D>>(
479        &mut self,
480        goal: Goal<I, G>,
481        assemble_from: AssembleCandidatesFrom,
482    ) -> Result<(Vec<Candidate<I>>, FailedCandidateInfo), RerunNonErased> {
483        let mut candidates = ::alloc::vec::Vec::new()vec![];
484        let mut failed_candidate_info =
485            FailedCandidateInfo { param_env_head_usages: CandidateHeadUsages::default() };
486        let Ok(normalized_self_ty) =
487            self.structurally_normalize_ty(goal.param_env, goal.predicate.self_ty())
488        else {
489            return Ok((candidates, failed_candidate_info));
490        };
491
492        let goal: Goal<I, G> = goal
493            .with(self.cx(), goal.predicate.with_replaced_self_ty(self.cx(), normalized_self_ty));
494
495        if normalized_self_ty.is_ty_var() {
496            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:496",
                        "rustc_next_trait_solver::solve::assembly",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(496u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("self type has been normalized to infer")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("self type has been normalized to infer");
497            self.try_assemble_bounds_via_registered_opaques(goal, assemble_from, &mut candidates)?;
498            return Ok((candidates, failed_candidate_info));
499        }
500
501        // Vars that show up in the rest of the goal substs may have been constrained by
502        // normalizing the self type as well, since type variables are not uniquified.
503        let goal = self.deeply_resolve_ignoring_regions(goal);
504
505        if self.typing_mode().is_coherence()
506            && let Ok(candidate) = self.consider_coherence_unknowable_candidate(goal)
507        {
508            candidates.push(candidate);
509            return Ok((candidates, failed_candidate_info));
510        }
511
512        self.assemble_alias_bound_candidates(goal, &mut candidates)?;
513        self.assemble_param_env_candidates(goal, &mut candidates, &mut failed_candidate_info)?;
514
515        match assemble_from {
516            AssembleCandidatesFrom::All => {
517                self.assemble_builtin_impl_candidates(goal, &mut candidates)?;
518                // For performance we only assemble impls if there are no candidates
519                // which would shadow them. This is necessary to avoid hangs in rayon,
520                // see trait-system-refactor-initiative#109 for more details.
521                //
522                // We always assemble builtin impls as trivial builtin impls have a higher
523                // priority than where-clauses.
524                //
525                // We only do this if any such candidate applies without any constraints
526                // as we may want to weaken inference guidance in the future and don't want
527                // to worry about causing major performance regressions when doing so.
528                // See trait-system-refactor-initiative#226 for some ideas here.
529                let assemble_impls = match self.typing_mode() {
530                    TypingMode::Coherence => true,
531                    TypingMode::Typeck { .. }
532                    | TypingMode::PostTypeckThroughBorrowck { .. }
533                    | TypingMode::Reflection
534                    | TypingMode::PostBorrowck { .. }
535                    | TypingMode::PostAnalysis
536                    | TypingMode::Codegen
537                    | TypingMode::ErasedNotCoherence(MayBeErased) => !candidates.iter().any(|c| {
538                        #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(ParamEnvSource::NonGlobal) |
        CandidateSource::AliasBound(_) => true,
    _ => false,
}matches!(
539                            c.source,
540                            CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)
541                                | CandidateSource::AliasBound(_)
542                        ) && has_no_inference_or_external_constraints(c.result)
543                    }),
544                };
545                if assemble_impls {
546                    self.assemble_impl_candidates(goal, &mut candidates)?;
547                    self.assemble_object_bound_candidates(goal, &mut candidates);
548                }
549            }
550            AssembleCandidatesFrom::EnvAndBounds => {
551                // This is somewhat inconsistent and may make #57893 slightly easier to exploit.
552                // However, it matches the behavior of the old solver. See
553                // `tests/ui/traits/next-solver/normalization-shadowing/use_object_if_empty_env.rs`.
554                if #[allow(non_exhaustive_omitted_patterns)] match normalized_self_ty.kind() {
    ty::Dynamic(..) => true,
    _ => false,
}matches!(normalized_self_ty.kind(), ty::Dynamic(..))
555                    && !candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(_) => true,
    _ => false,
}matches!(c.source, CandidateSource::ParamEnv(_)))
556                {
557                    self.assemble_object_bound_candidates(goal, &mut candidates);
558                }
559            }
560        }
561
562        Ok((candidates, failed_candidate_info))
563    }
564
565    pub(super) fn forced_ambiguity(
566        &mut self,
567        maybe: MaybeInfo,
568    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
569        // This may fail if `try_evaluate_added_goals` overflows because it
570        // fails to reach a fixpoint but ends up getting an error after
571        // running for some additional step.
572        //
573        // FIXME(@lcnr): While I believe an error here to be possible, we
574        // currently don't have any test which actually triggers it. @lqd
575        // created a minimization for an ICE in typenum, but that one no
576        // longer fails here. cc trait-system-refactor-initiative#105.
577        let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
578        let certainty = Certainty::Maybe(maybe);
579        self.probe_trait_candidate(source)
580            .enter(|this| this.evaluate_added_goals_and_make_canonical_response(certainty))
581    }
582
583    {}
#[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("assemble_impl_candidates",
                                    "rustc_next_trait_solver::solve::assembly",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(583u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let cx = self.cx();
            let goal_trait_ref = goal.predicate.trait_ref(cx);
            cx.for_each_relevant_impl(goal_trait_ref,
                |impl_def_id| -> Result<_, _>
                    {
                        match G::consider_impl_candidate(self, goal, goal_trait_ref,
                                        impl_def_id,
                                        |ecx|
                                            {
                                                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                                            }).map_err_to_rerun()? {
                            Ok(candidate) => candidates.push(candidate),
                            Err(NoSolution) => {}
                        }
                        Ok(())
                    })
        }
    }
}#[instrument(level = "trace", skip_all)]
584    fn assemble_impl_candidates<G: GoalKind<D>>(
585        &mut self,
586        goal: Goal<I, G>,
587        candidates: &mut Vec<Candidate<I>>,
588    ) -> Result<(), RerunNonErased> {
589        let cx = self.cx();
590        let goal_trait_ref = goal.predicate.trait_ref(cx);
591        cx.for_each_relevant_impl(goal_trait_ref, |impl_def_id| -> Result<_, _> {
592            match G::consider_impl_candidate(self, goal, goal_trait_ref, impl_def_id, |ecx| {
593                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
594            })
595            .map_err_to_rerun()?
596            {
597                Ok(candidate) => candidates.push(candidate),
598                Err(NoSolution) => {}
599            }
600
601            Ok(())
602        })
603    }
604
605    {}
#[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("assemble_builtin_impl_candidates",
                                    "rustc_next_trait_solver::solve::assembly",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(605u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let cx = self.cx();
            let trait_def_id = goal.predicate.trait_def_id(cx);
            if self.typing_mode().is_reflection() { return Ok(()); }
            let result =
                if let ty::Error(guar) = goal.predicate.self_ty().kind() {
                    G::consider_error_guaranteed_candidate(self, goal, guar)
                } else if cx.trait_is_auto(trait_def_id) {
                    G::consider_auto_trait_candidate(self, goal)
                } else if cx.trait_is_alias(trait_def_id) {
                    G::consider_trait_alias_candidate(self, goal)
                } else {
                    match cx.as_trait_lang_item(trait_def_id) {
                        Some(SolverTraitLangItem::Sized) => {
                            G::consider_builtin_sizedness_candidates(self, goal,
                                SizedTraitKind::Sized)
                        }
                        Some(SolverTraitLangItem::MetaSized) => {
                            G::consider_builtin_sizedness_candidates(self, goal,
                                SizedTraitKind::MetaSized)
                        }
                        Some(SolverTraitLangItem::PointeeSized) => {
                            {
                                ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                        format_args!("`PointeeSized` is removed during lowering")));
                            };
                        }
                        Some(SolverTraitLangItem::Copy | SolverTraitLangItem::Clone
                            | SolverTraitLangItem::TrivialClone) =>
                            G::consider_builtin_copy_clone_candidate(self, goal),
                        Some(SolverTraitLangItem::Fn) => {
                            G::consider_builtin_fn_trait_candidates(self, goal,
                                ty::ClosureKind::Fn)
                        }
                        Some(SolverTraitLangItem::FnMut) => {
                            G::consider_builtin_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnMut)
                        }
                        Some(SolverTraitLangItem::FnOnce) => {
                            G::consider_builtin_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnOnce)
                        }
                        Some(SolverTraitLangItem::AsyncFn) => {
                            G::consider_builtin_async_fn_trait_candidates(self, goal,
                                ty::ClosureKind::Fn)
                        }
                        Some(SolverTraitLangItem::AsyncFnMut) => {
                            G::consider_builtin_async_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnMut)
                        }
                        Some(SolverTraitLangItem::AsyncFnOnce) => {
                            G::consider_builtin_async_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnOnce)
                        }
                        Some(SolverTraitLangItem::FnPtrTrait) => {
                            G::consider_builtin_fn_ptr_trait_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::AsyncFnKindHelper) => {
                            G::consider_builtin_async_fn_kind_helper_candidate(self,
                                goal)
                        }
                        Some(SolverTraitLangItem::Tuple) =>
                            G::consider_builtin_tuple_candidate(self, goal),
                        Some(SolverTraitLangItem::PointeeTrait) => {
                            G::consider_builtin_pointee_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Future) => {
                            G::consider_builtin_future_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Iterator) => {
                            G::consider_builtin_iterator_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::FusedIterator) => {
                            G::consider_builtin_fused_iterator_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::AsyncIterator) => {
                            G::consider_builtin_async_iterator_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Coroutine) => {
                            G::consider_builtin_coroutine_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::DiscriminantKind) => {
                            G::consider_builtin_discriminant_kind_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Destruct) => {
                            G::consider_builtin_destruct_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::TransmuteTrait) => {
                            G::consider_builtin_transmute_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
                            G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self,
                                goal)
                        }
                        Some(SolverTraitLangItem::TryAsDyn) => {
                            G::consider_builtin_try_as_dyn_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Field) =>
                            G::consider_builtin_field_candidate(self, goal),
                        _ => Err(NoSolution.into()),
                    }
                };
            candidates.extend(result);
            if cx.is_trait_lang_item(trait_def_id,
                    SolverTraitLangItem::Unsize) {
                candidates.extend(G::consider_structural_builtin_unsize_candidates(self,
                            goal)?);
            }
            Ok(())
        }
    }
}#[instrument(level = "trace", skip_all)]
606    fn assemble_builtin_impl_candidates<G: GoalKind<D>>(
607        &mut self,
608        goal: Goal<I, G>,
609        candidates: &mut Vec<Candidate<I>>,
610    ) -> Result<(), RerunNonErased> {
611        let cx = self.cx();
612        let trait_def_id = goal.predicate.trait_def_id(cx);
613
614        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
615        // of trying to handle these manually, we just reject all builtin impls in reflection
616        // mode. We can probably lift this restriction for specific cases, but this is safer.
617        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
618        if self.typing_mode().is_reflection() {
619            return Ok(());
620        }
621
622        // N.B. When assembling built-in candidates for lang items that are also
623        // `auto` traits, then the auto trait candidate that is assembled in
624        // `consider_auto_trait_candidate` MUST be disqualified to remain sound.
625        //
626        // Instead of adding the logic here, it's a better idea to add it in
627        // `EvalCtxt::disqualify_auto_trait_candidate_due_to_possible_impl` in
628        // `solve::trait_goals` instead.
629        let result = if let ty::Error(guar) = goal.predicate.self_ty().kind() {
630            G::consider_error_guaranteed_candidate(self, goal, guar)
631        } else if cx.trait_is_auto(trait_def_id) {
632            G::consider_auto_trait_candidate(self, goal)
633        } else if cx.trait_is_alias(trait_def_id) {
634            G::consider_trait_alias_candidate(self, goal)
635        } else {
636            match cx.as_trait_lang_item(trait_def_id) {
637                Some(SolverTraitLangItem::Sized) => {
638                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::Sized)
639                }
640                Some(SolverTraitLangItem::MetaSized) => {
641                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::MetaSized)
642                }
643                Some(SolverTraitLangItem::PointeeSized) => {
644                    unreachable!("`PointeeSized` is removed during lowering");
645                }
646                Some(
647                    SolverTraitLangItem::Copy
648                    | SolverTraitLangItem::Clone
649                    | SolverTraitLangItem::TrivialClone,
650                ) => G::consider_builtin_copy_clone_candidate(self, goal),
651                Some(SolverTraitLangItem::Fn) => {
652                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
653                }
654                Some(SolverTraitLangItem::FnMut) => {
655                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnMut)
656                }
657                Some(SolverTraitLangItem::FnOnce) => {
658                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnOnce)
659                }
660                Some(SolverTraitLangItem::AsyncFn) => {
661                    G::consider_builtin_async_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
662                }
663                Some(SolverTraitLangItem::AsyncFnMut) => {
664                    G::consider_builtin_async_fn_trait_candidates(
665                        self,
666                        goal,
667                        ty::ClosureKind::FnMut,
668                    )
669                }
670                Some(SolverTraitLangItem::AsyncFnOnce) => {
671                    G::consider_builtin_async_fn_trait_candidates(
672                        self,
673                        goal,
674                        ty::ClosureKind::FnOnce,
675                    )
676                }
677                Some(SolverTraitLangItem::FnPtrTrait) => {
678                    G::consider_builtin_fn_ptr_trait_candidate(self, goal)
679                }
680                Some(SolverTraitLangItem::AsyncFnKindHelper) => {
681                    G::consider_builtin_async_fn_kind_helper_candidate(self, goal)
682                }
683                Some(SolverTraitLangItem::Tuple) => G::consider_builtin_tuple_candidate(self, goal),
684                Some(SolverTraitLangItem::PointeeTrait) => {
685                    G::consider_builtin_pointee_candidate(self, goal)
686                }
687                Some(SolverTraitLangItem::Future) => {
688                    G::consider_builtin_future_candidate(self, goal)
689                }
690                Some(SolverTraitLangItem::Iterator) => {
691                    G::consider_builtin_iterator_candidate(self, goal)
692                }
693                Some(SolverTraitLangItem::FusedIterator) => {
694                    G::consider_builtin_fused_iterator_candidate(self, goal)
695                }
696                Some(SolverTraitLangItem::AsyncIterator) => {
697                    G::consider_builtin_async_iterator_candidate(self, goal)
698                }
699                Some(SolverTraitLangItem::Coroutine) => {
700                    G::consider_builtin_coroutine_candidate(self, goal)
701                }
702                Some(SolverTraitLangItem::DiscriminantKind) => {
703                    G::consider_builtin_discriminant_kind_candidate(self, goal)
704                }
705                Some(SolverTraitLangItem::Destruct) => {
706                    G::consider_builtin_destruct_candidate(self, goal)
707                }
708                Some(SolverTraitLangItem::TransmuteTrait) => {
709                    G::consider_builtin_transmute_candidate(self, goal)
710                }
711                Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
712                    G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self, goal)
713                }
714                Some(SolverTraitLangItem::TryAsDyn) => {
715                    G::consider_builtin_try_as_dyn_candidate(self, goal)
716                }
717                Some(SolverTraitLangItem::Field) => G::consider_builtin_field_candidate(self, goal),
718                _ => Err(NoSolution.into()),
719            }
720        };
721
722        candidates.extend(result);
723
724        // There may be multiple unsize candidates for a trait with several supertraits:
725        // `trait Foo: Bar<A> + Bar<B>` and `dyn Foo: Unsize<dyn Bar<_>>`
726        if cx.is_trait_lang_item(trait_def_id, SolverTraitLangItem::Unsize) {
727            candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal)?);
728        }
729
730        Ok(())
731    }
732
733    {}
#[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("assemble_param_env_candidates",
                                    "rustc_next_trait_solver::solve::assembly",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(733u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let goal_lang_item =
                self.cx().as_trait_lang_item(goal.predicate.trait_def_id(self.cx()));
            for assumption in goal.param_env.caller_bounds() {
                match G::fast_reject_assumption(self, goal, goal_lang_item,
                        assumption) {
                    Ok(()) => {
                        match G::probe_and_consider_param_env_candidate(self, goal,
                                    assumption)? {
                            Ok(candidate) => candidates.push(candidate),
                            Err(head_usages) => {
                                failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
                            }
                        }
                    }
                    Err(NoSolution) => {}
                }
            }
            Ok(())
        }
    }
}#[instrument(level = "trace", skip_all)]
734    fn assemble_param_env_candidates<G: GoalKind<D>>(
735        &mut self,
736        goal: Goal<I, G>,
737        candidates: &mut Vec<Candidate<I>>,
738        failed_candidate_info: &mut FailedCandidateInfo,
739    ) -> Result<(), RerunNonErased> {
740        let goal_lang_item = self.cx().as_trait_lang_item(goal.predicate.trait_def_id(self.cx()));
741
742        for assumption in goal.param_env.caller_bounds() {
743            match G::fast_reject_assumption(self, goal, goal_lang_item, assumption) {
744                Ok(()) => {
745                    match G::probe_and_consider_param_env_candidate(self, goal, assumption)? {
746                        Ok(candidate) => candidates.push(candidate),
747                        Err(head_usages) => {
748                            failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
749                        }
750                    }
751                }
752                Err(NoSolution) => {}
753            }
754        }
755
756        Ok(())
757    }
758
759    {}
#[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("assemble_alias_bound_candidates",
                                    "rustc_next_trait_solver::solve::assembly",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(759u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let res =
                self.probe(|_|
                            ProbeKind::NormalizedSelfTyAssembly).enter(|ecx|
                        {
                            ecx.assemble_alias_bound_candidates_recur(goal.predicate.self_ty(),
                                    goal, candidates, AliasBoundKind::SelfBounds)?;
                            Ok(())
                        });
            match res {
                Ok(_) => Ok(()),
                Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
                Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
                    ::core::panicking::unreachable_default_msg()
                }
            }
        }
    }
}#[instrument(level = "trace", skip_all)]
760    fn assemble_alias_bound_candidates<G: GoalKind<D>>(
761        &mut self,
762        goal: Goal<I, G>,
763        candidates: &mut Vec<Candidate<I>>,
764    ) -> Result<(), RerunNonErased> {
765        let res = self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
766            ecx.assemble_alias_bound_candidates_recur(
767                goal.predicate.self_ty(),
768                goal,
769                candidates,
770                AliasBoundKind::SelfBounds,
771            )?;
772            Ok(())
773        });
774
775        // always returns Ok
776        match res {
777            Ok(_) => Ok(()),
778            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
779            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
780                unreachable!()
781            }
782        }
783    }
784
785    /// For some deeply nested `<T>::A::B::C::D` rigid associated type,
786    /// we should explore the item bounds for all levels, since the
787    /// `associated_type_bounds` feature means that a parent associated
788    /// type may carry bounds for a nested associated type.
789    ///
790    /// If we have a projection, check that its self type is a rigid projection.
791    /// If so, continue searching by recursively calling after normalization.
792    // FIXME: This may recurse infinitely, but I can't seem to trigger it without
793    // hitting another overflow error something. Add a depth parameter needed later.
794    fn assemble_alias_bound_candidates_recur<G: GoalKind<D>>(
795        &mut self,
796        self_ty: I::Ty,
797        goal: Goal<I, G>,
798        candidates: &mut Vec<Candidate<I>>,
799        consider_self_bounds: AliasBoundKind,
800    ) -> Result<(), RerunNonErased> {
801        let (alias_ty, def_id) = match self_ty.kind() {
802            ty::Bool
803            | ty::Char
804            | ty::Int(_)
805            | ty::Uint(_)
806            | ty::Float(_)
807            | ty::Adt(_, _)
808            | ty::Foreign(_)
809            | ty::Str
810            | ty::Array(_, _)
811            | ty::Pat(_, _)
812            | ty::Slice(_)
813            | ty::RawPtr(_, _)
814            | ty::Ref(_, _, _)
815            | ty::FnDef(_, _)
816            | ty::FnPtr(..)
817            | ty::UnsafeBinder(_)
818            | ty::Dynamic(..)
819            | ty::Closure(..)
820            | ty::CoroutineClosure(..)
821            | ty::Coroutine(..)
822            | ty::CoroutineWitness(..)
823            | ty::Never
824            | ty::Tuple(_)
825            | ty::Param(_)
826            | ty::Placeholder(..)
827            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
828            | ty::Error(_) => return Ok(()),
829            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => {
830                {
    ::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
            goal));
}panic!("unexpected self type for `{goal:?}`")
831            }
832
833            ty::Infer(ty::TyVar(_)) => {
834                // If we hit infer when normalizing the self type of an alias,
835                // then bail with ambiguity. We should never encounter this on
836                // the *first* iteration of this recursive function.
837                if let Ok(result) =
838                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
839                {
840                    candidates.push(Candidate {
841                        source: CandidateSource::AliasBound(consider_self_bounds),
842                        result,
843                        head_usages: CandidateHeadUsages::default(),
844                    });
845                }
846                return Ok(());
847            }
848
849            ty::Alias(
850                ty::IsRigid::Yes,
851                alias_ty @ AliasTy { kind: ty::Projection { def_id }, .. },
852            ) => (alias_ty, def_id.into()),
853
854            ty::Alias(ty::IsRigid::Yes, alias_ty @ AliasTy { kind: ty::Opaque { def_id }, .. }) => {
855                (alias_ty, def_id.into())
856            }
857
858            ty::Alias(ty::IsRigid::No, _) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("non-rigid self type: {0:?}", self_ty)));
}unreachable!("non-rigid self type: {self_ty:?}"),
859
860            ty::Alias(
861                ty::IsRigid::Yes,
862                AliasTy { kind: ty::Inherent { .. } | ty::Free { .. }, .. },
863            ) => {
864                self.cx().delay_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not normalize {0:?}, it is not WF",
                self_ty))
    })format!("could not normalize {self_ty:?}, it is not WF"));
865                return Ok(());
866            }
867        };
868
869        match consider_self_bounds {
870            AliasBoundKind::SelfBounds => {
871                for assumption in self
872                    .cx()
873                    .item_self_bounds(def_id)
874                    .iter_instantiated(self.cx(), alias_ty.args)
875                    .map(Unnormalized::skip_norm_wip)
876                {
877                    candidates.extend(G::probe_and_consider_implied_clause(
878                        self,
879                        CandidateSource::AliasBound(consider_self_bounds),
880                        goal,
881                        assumption,
882                        [],
883                    ));
884                }
885            }
886            AliasBoundKind::NonSelfBounds => {
887                for assumption in self
888                    .cx()
889                    .item_non_self_bounds(def_id)
890                    .iter_instantiated(self.cx(), alias_ty.args)
891                    .map(Unnormalized::skip_norm_wip)
892                {
893                    candidates.extend(G::probe_and_consider_implied_clause(
894                        self,
895                        CandidateSource::AliasBound(consider_self_bounds),
896                        goal,
897                        assumption,
898                        [],
899                    ));
900                }
901            }
902        }
903
904        candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty));
905
906        let Some(projection_ty) = alias_ty.try_to_projection() else {
907            return Ok(());
908        };
909
910        // Recurse on the self type of the projection.
911        match self.structurally_normalize_ty(goal.param_env, projection_ty.projection_self_ty()) {
912            Ok(next_self_ty) => self.assemble_alias_bound_candidates_recur(
913                next_self_ty,
914                goal,
915                candidates,
916                AliasBoundKind::NonSelfBounds,
917            ),
918            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Ok(()),
919            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
920        }
921    }
922
923    {}
#[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("assemble_object_bound_candidates",
                                    "rustc_next_trait_solver::solve::assembly",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(923u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let cx = self.cx();
            if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
                return;
            }
            if self.typing_mode().is_reflection() { return; }
            let self_ty = goal.predicate.self_ty();
            let bounds =
                match self_ty.kind() {
                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) |
                        ty::Float(_) | ty::Adt(_, _) | ty::Foreign(_) | ty::Str |
                        ty::Array(_, _) | ty::Pat(_, _) | ty::Slice(_) |
                        ty::RawPtr(_, _) | ty::Ref(_, _, _) | ty::FnDef(_, _) |
                        ty::FnPtr(..) | ty::UnsafeBinder(_) | ty::Alias(..) |
                        ty::Closure(..) | ty::CoroutineClosure(..) |
                        ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Never |
                        ty::Tuple(_) | ty::Param(_) | ty::Placeholder(..) |
                        ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Error(_) =>
                        return,
                    ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_)
                        | ty::FreshFloatTy(_)) | ty::Bound(..) => {
                        ::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
                                goal));
                    }
                    ty::Dynamic(bounds, ..) => bounds,
                };
            if bounds.principal_def_id().is_some_and(|def_id|
                        !cx.trait_is_dyn_compatible(def_id)) {
                return;
            }
            for bound in bounds.iter() {
                match bound.skip_binder() {
                    ty::ExistentialPredicate::Trait(_) => {}
                    ty::ExistentialPredicate::Projection(_) |
                        ty::ExistentialPredicate::AutoTrait(_) => {
                        candidates.extend(G::probe_and_consider_object_bound_candidate(self,
                                CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal,
                                bound.with_self_ty(cx, self_ty)));
                    }
                }
            }
            if let Some(principal) = bounds.principal() {
                let principal_trait_ref = principal.with_self_ty(cx, self_ty);
                for (idx, assumption) in
                    elaborate::supertraits(cx, principal_trait_ref).enumerate()
                    {
                    candidates.extend(G::probe_and_consider_object_bound_candidate(self,
                            CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
                            goal, assumption.upcast(cx)));
                }
            }
        }
    }
}#[instrument(level = "trace", skip_all)]
924    fn assemble_object_bound_candidates<G: GoalKind<D>>(
925        &mut self,
926        goal: Goal<I, G>,
927        candidates: &mut Vec<Candidate<I>>,
928    ) {
929        let cx = self.cx();
930        if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
931            // `dyn MetaSized` is valid, but should get its `MetaSized` impl from
932            // being `dyn` (SizedCandidate), not from the object candidate.
933            return;
934        }
935
936        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
937        // of trying to handle these manually, we just reject all builtin impls in reflection
938        // mode. We can probably lift this restriction for specific cases, but this is safer.
939        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
940        if self.typing_mode().is_reflection() {
941            return;
942        }
943
944        let self_ty = goal.predicate.self_ty();
945        let bounds = match self_ty.kind() {
946            ty::Bool
947            | ty::Char
948            | ty::Int(_)
949            | ty::Uint(_)
950            | ty::Float(_)
951            | ty::Adt(_, _)
952            | ty::Foreign(_)
953            | ty::Str
954            | ty::Array(_, _)
955            | ty::Pat(_, _)
956            | ty::Slice(_)
957            | ty::RawPtr(_, _)
958            | ty::Ref(_, _, _)
959            | ty::FnDef(_, _)
960            | ty::FnPtr(..)
961            | ty::UnsafeBinder(_)
962            | ty::Alias(..)
963            | ty::Closure(..)
964            | ty::CoroutineClosure(..)
965            | ty::Coroutine(..)
966            | ty::CoroutineWitness(..)
967            | ty::Never
968            | ty::Tuple(_)
969            | ty::Param(_)
970            | ty::Placeholder(..)
971            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
972            | ty::Error(_) => return,
973            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
974            | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"),
975            ty::Dynamic(bounds, ..) => bounds,
976        };
977
978        // Do not consider built-in object impls for dyn-incompatible types.
979        if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
980            return;
981        }
982
983        // Consider all of the auto-trait and projection bounds, which don't
984        // need to be recorded as a `BuiltinImplSource::Object` since they don't
985        // really have a vtable base...
986        for bound in bounds.iter() {
987            match bound.skip_binder() {
988                ty::ExistentialPredicate::Trait(_) => {
989                    // Skip principal
990                }
991                ty::ExistentialPredicate::Projection(_)
992                | ty::ExistentialPredicate::AutoTrait(_) => {
993                    candidates.extend(G::probe_and_consider_object_bound_candidate(
994                        self,
995                        CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
996                        goal,
997                        bound.with_self_ty(cx, self_ty),
998                    ));
999                }
1000            }
1001        }
1002
1003        // FIXME: We only need to do *any* of this if we're considering a trait goal,
1004        // since we don't need to look at any supertrait or anything if we are doing
1005        // a projection goal.
1006        if let Some(principal) = bounds.principal() {
1007            let principal_trait_ref = principal.with_self_ty(cx, self_ty);
1008            for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
1009                candidates.extend(G::probe_and_consider_object_bound_candidate(
1010                    self,
1011                    CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
1012                    goal,
1013                    assumption.upcast(cx),
1014                ));
1015            }
1016        }
1017    }
1018
1019    /// In coherence we have to not only care about all impls we know about, but
1020    /// also consider impls which may get added in a downstream or sibling crate
1021    /// or which an upstream impl may add in a minor release.
1022    ///
1023    /// To do so we return a single ambiguous candidate in case such an unknown
1024    /// impl could apply to the current goal.
1025    {}
#[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("consider_coherence_unknowable_candidate",
                                    "rustc_next_trait_solver::solve::assembly",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1025u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Candidate<I>, NoSolutionOrRerunNonErased> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx|
                    {
                        let cx = ecx.cx();
                        let trait_ref = goal.predicate.trait_ref(cx);
                        if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
                            Err(NoSolution.into())
                        } else {
                            let predicate: I::Predicate = trait_ref.upcast(cx);
                            ecx.add_goals(GoalSource::Misc,
                                    elaborate::elaborate(cx,
                                                [predicate]).skip(1).map(|predicate|
                                            goal.with(cx, predicate)))?;
                            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                        }
                    })
        }
    }
}#[instrument(level = "trace", skip_all)]
1026    fn consider_coherence_unknowable_candidate<G: GoalKind<D>>(
1027        &mut self,
1028        goal: Goal<I, G>,
1029    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1030        self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx| {
1031            let cx = ecx.cx();
1032            let trait_ref = goal.predicate.trait_ref(cx);
1033            if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
1034                Err(NoSolution.into())
1035            } else {
1036                // While the trait bound itself may be unknowable, we may be able to
1037                // prove that a super trait is not implemented. For this, we recursively
1038                // prove the super trait bounds of the current goal.
1039                //
1040                // We skip the goal itself as that one would cycle.
1041                let predicate: I::Predicate = trait_ref.upcast(cx);
1042                ecx.add_goals(
1043                    GoalSource::Misc,
1044                    elaborate::elaborate(cx, [predicate])
1045                        .skip(1)
1046                        .map(|predicate| goal.with(cx, predicate)),
1047                )?;
1048                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1049            }
1050        })
1051    }
1052}
1053
1054pub(super) enum AllowInferenceConstraints {
1055    Yes,
1056    No,
1057}
1058
1059impl<D, I> EvalCtxt<'_, D>
1060where
1061    D: SolverDelegate<Interner = I>,
1062    I: Interner,
1063{
1064    /// Check whether we can ignore impl candidates due to specialization.
1065    ///
1066    /// This is only necessary for `feature(specialization)` and seems quite ugly.
1067    pub(super) fn filter_specialized_impls(
1068        &mut self,
1069        allow_inference_constraints: AllowInferenceConstraints,
1070        candidates: &mut Vec<Candidate<I>>,
1071    ) {
1072        if self.typing_mode().is_coherence() {
1073            return;
1074        }
1075
1076        let mut i = 0;
1077        'outer: while i < candidates.len() {
1078            let CandidateSource::Impl(victim_def_id) = candidates[i].source else {
1079                i += 1;
1080                continue;
1081            };
1082
1083            for (j, c) in candidates.iter().enumerate() {
1084                if i == j {
1085                    continue;
1086                }
1087
1088                let CandidateSource::Impl(other_def_id) = c.source else {
1089                    continue;
1090                };
1091
1092                // See if we can toss out `victim` based on specialization.
1093                //
1094                // While this requires us to know *for sure* that the `lhs` impl applies
1095                // we still use modulo regions here. This is fine as specialization currently
1096                // assumes that specializing impls have to be always applicable, meaning that
1097                // the only allowed region constraints may be constraints also present on the default impl.
1098                //
1099                // If both impls have the same response, dropping victim doesn't change the
1100                // result. We need to do so here as we don't merge distinct impl candidates.
1101                if #[allow(non_exhaustive_omitted_patterns)] match allow_inference_constraints {
    AllowInferenceConstraints::Yes => true,
    _ => false,
}matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
1102                    || has_only_region_constraints(c.result)
1103                    || c.result == candidates[i].result
1104                {
1105                    if self.cx().impl_specializes(other_def_id, victim_def_id) {
1106                        candidates.remove(i);
1107                        continue 'outer;
1108                    }
1109                }
1110            }
1111
1112            i += 1;
1113        }
1114    }
1115
1116    /// If the self type is the hidden type of an opaque, try to assemble
1117    /// candidates for it by consider its item bounds and by using blanket
1118    /// impls. This is used to incompletely guide type inference when handling
1119    /// non-defining uses in the defining scope.
1120    ///
1121    /// We otherwise just fail fail with ambiguity. Even if we're using an
1122    /// opaque type item bound or a blank impls, we still force its certainty
1123    /// to be `Maybe` so that we properly prove this goal later.
1124    ///
1125    /// See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/182>
1126    /// for why this is necessary.
1127    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::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_assemble_bounds_via_registered_opaques",
                                    "rustc_next_trait_solver::solve::assembly",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1127u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("candidates")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("candidates");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let self_ty = goal.predicate.self_ty();
            let opaque_types =
                match self.typing_mode() {
                    TypingMode::Typeck { .. } =>
                        self.opaques_with_sub_unified_hidden_type(self_ty),
                    TypingMode::Coherence |
                        TypingMode::PostTypeckThroughBorrowck { .. } |
                        TypingMode::PostBorrowck { .. } | TypingMode::PostAnalysis |
                        TypingMode::Reflection | TypingMode::Codegen =>
                        ::alloc::vec::Vec::new(),
                    TypingMode::ErasedNotCoherence(MayBeErased) => {
                        self.opaque_accesses.rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
                        Vec::new()
                    }
                };
            if opaque_types.is_empty() {
                candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
                return Ok(());
            }
            for &opaque_ty in &opaque_types {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1157",
                                        "rustc_next_trait_solver::solve::assembly",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1157u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("self ty is sub unified with {0:?}",
                                                                    opaque_ty) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                struct ReplaceOpaque<I: Interner> {
                    cx: I,
                    opaque_ty: ty::OpaqueAliasTy<I>,
                    self_ty: I::Ty,
                }
                impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
                    fn cx(&self) -> I { self.cx }
                    fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
                        if let ty::Alias(is_rigid, alias_ty) = ty.kind() &&
                                let Some(opaque_ty) = alias_ty.try_to_opaque() {
                            if opaque_ty == self.opaque_ty {
                                if true {
                                    {
                                        match (&is_rigid, &ty::IsRigid::No) {
                                            (left_val, right_val) => {
                                                if !(*left_val == *right_val) {
                                                    let kind = ::core::panicking::AssertKind::Eq;
                                                    ::core::panicking::assert_failed(kind, &*left_val,
                                                        &*right_val, ::core::option::Option::None);
                                                }
                                            }
                                        }
                                    };
                                };
                                return self.self_ty;
                            }
                        }
                        ty.super_fold_with(self)
                    }
                }
                for item_bound in
                    self.cx().item_self_bounds(opaque_ty.kind.into()).iter_instantiated(self.cx(),
                            opaque_ty.args).map(Unnormalized::skip_norm_wip) {
                    let assumption =
                        item_bound.fold_with(&mut ReplaceOpaque {
                                    cx: self.cx(),
                                    opaque_ty,
                                    self_ty,
                                });
                    candidates.extend(G::probe_and_match_goal_against_assumption(self,
                            CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
                            goal, assumption,
                            |ecx|
                                {
                                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                                }));
                }
            }
            if assemble_from.should_assemble_impl_candidates() {
                let cx = self.cx();
                let goal_trait_ref = goal.predicate.trait_ref(cx);
                cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx),
                        |impl_def_id|
                            {
                                match G::consider_impl_candidate(self, goal, goal_trait_ref,
                                                impl_def_id,
                                                |ecx|
                                                    {
                                                        if ecx.shallow_resolve(self_ty).is_ty_var() {
                                                            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                                                        } else { Err(NoSolution.into()) }
                                                    }).map_err_to_rerun()? {
                                    Ok(candidate) => candidates.push(candidate),
                                    Err(NoSolution) => {}
                                }
                                Ok(())
                            })?;
            }
            if candidates.is_empty() {
                let source =
                    CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
                let certainty =
                    Certainty::Maybe(MaybeInfo {
                            cause: MaybeCause::Ambiguity,
                            opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
                            stalled_on_coroutines: StalledOnCoroutines::No,
                        });
                candidates.extend(self.probe_trait_candidate(source).enter(|this|
                            {
                                this.evaluate_added_goals_and_make_canonical_response(certainty)
                            }));
            }
            Ok(())
        }
    }
}#[tracing::instrument(skip(self, assemble_from))]
1128    fn try_assemble_bounds_via_registered_opaques<G: GoalKind<D>>(
1129        &mut self,
1130        goal: Goal<I, G>,
1131        assemble_from: AssembleCandidatesFrom,
1132        candidates: &mut Vec<Candidate<I>>,
1133    ) -> Result<(), RerunNonErased> {
1134        let self_ty = goal.predicate.self_ty();
1135        // We only use this hack during HIR typeck.
1136        let opaque_types = match self.typing_mode() {
1137            TypingMode::Typeck { .. } => self.opaques_with_sub_unified_hidden_type(self_ty),
1138            TypingMode::Coherence
1139            | TypingMode::PostTypeckThroughBorrowck { .. }
1140            | TypingMode::PostBorrowck { .. }
1141            | TypingMode::PostAnalysis
1142            | TypingMode::Reflection
1143            | TypingMode::Codegen => vec![],
1144            TypingMode::ErasedNotCoherence(MayBeErased) => {
1145                self.opaque_accesses
1146                    .rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
1147                Vec::new()
1148            }
1149        };
1150
1151        if opaque_types.is_empty() {
1152            candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
1153            return Ok(());
1154        }
1155
1156        for &opaque_ty in &opaque_types {
1157            debug!("self ty is sub unified with {opaque_ty:?}");
1158
1159            struct ReplaceOpaque<I: Interner> {
1160                cx: I,
1161                opaque_ty: ty::OpaqueAliasTy<I>,
1162                self_ty: I::Ty,
1163            }
1164            impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
1165                fn cx(&self) -> I {
1166                    self.cx
1167                }
1168                fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1169                    if let ty::Alias(is_rigid, alias_ty) = ty.kind()
1170                        && let Some(opaque_ty) = alias_ty.try_to_opaque()
1171                    {
1172                        if opaque_ty == self.opaque_ty {
1173                            debug_assert_eq!(is_rigid, ty::IsRigid::No);
1174                            return self.self_ty;
1175                        }
1176                    }
1177                    ty.super_fold_with(self)
1178                }
1179            }
1180
1181            // We look at all item-bounds of the opaque, replacing the
1182            // opaque with the current self type before considering
1183            // them as a candidate. Imagine we've got `?x: Trait<?y>`
1184            // and `?x` has been sub-unified with the hidden type of
1185            // `impl Trait<u32>`, We take the item bound `opaque: Trait<u32>`
1186            // and replace all occurrences of `opaque` with `?x`. This results
1187            // in a `?x: Trait<u32>` alias-bound candidate.
1188            for item_bound in self
1189                .cx()
1190                .item_self_bounds(opaque_ty.kind.into())
1191                .iter_instantiated(self.cx(), opaque_ty.args)
1192                .map(Unnormalized::skip_norm_wip)
1193            {
1194                let assumption =
1195                    item_bound.fold_with(&mut ReplaceOpaque { cx: self.cx(), opaque_ty, self_ty });
1196                candidates.extend(G::probe_and_match_goal_against_assumption(
1197                    self,
1198                    CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
1199                    goal,
1200                    assumption,
1201                    |ecx| {
1202                        // We want to reprove this goal once we've inferred the
1203                        // hidden type, so we force the certainty to `Maybe`.
1204                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1205                    },
1206                ));
1207            }
1208        }
1209
1210        // If the self type is sub unified with any opaque type, we also look at blanket
1211        // impls for it.
1212        //
1213        // See tests/ui/impl-trait/non-defining-uses/use-blanket-impl.rs for an example.
1214        if assemble_from.should_assemble_impl_candidates() {
1215            let cx = self.cx();
1216            let goal_trait_ref = goal.predicate.trait_ref(cx);
1217
1218            cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx), |impl_def_id| {
1219                match G::consider_impl_candidate(self, goal, goal_trait_ref, impl_def_id, |ecx| {
1220                    if ecx.shallow_resolve(self_ty).is_ty_var() {
1221                        // We force the certainty of impl candidates to be `Maybe`.
1222                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1223                    } else {
1224                        // We don't want to use impls if they constrain the opaque.
1225                        //
1226                        // FIXME(trait-system-refactor-initiative#229): This isn't
1227                        // perfect yet as it still allows us to incorrectly constrain
1228                        // other inference variables.
1229                        Err(NoSolution.into())
1230                    }
1231                })
1232                .map_err_to_rerun()?
1233                {
1234                    Ok(candidate) => candidates.push(candidate),
1235                    Err(NoSolution) => {}
1236                }
1237
1238                Ok(())
1239            })?;
1240        }
1241
1242        if candidates.is_empty() {
1243            let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1244            let certainty = Certainty::Maybe(MaybeInfo {
1245                cause: MaybeCause::Ambiguity,
1246                opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
1247                stalled_on_coroutines: StalledOnCoroutines::No,
1248            });
1249            candidates
1250                .extend(self.probe_trait_candidate(source).enter(|this| {
1251                    this.evaluate_added_goals_and_make_canonical_response(certainty)
1252                }));
1253        }
1254
1255        Ok(())
1256    }
1257
1258    /// Assemble and merge candidates for goals which are related to an underlying trait
1259    /// goal. Right now, this is normalizes-to and host effect goals.
1260    ///
1261    /// We sadly can't simply take all possible candidates for normalization goals
1262    /// and check whether they result in the same constraints. We want to make sure
1263    /// that trying to normalize an alias doesn't result in constraints which aren't
1264    /// otherwise required.
1265    ///
1266    /// Most notably, when proving a trait goal by via a where-bound, we should not
1267    /// normalize via impls which have stricter region constraints than the where-bound:
1268    ///
1269    /// ```rust
1270    /// trait Trait<'a> {
1271    ///     type Assoc;
1272    /// }
1273    ///
1274    /// impl<'a, T: 'a> Trait<'a> for T {
1275    ///     type Assoc = u32;
1276    /// }
1277    ///
1278    /// fn with_bound<'a, T: Trait<'a>>(_value: T::Assoc) {}
1279    /// ```
1280    ///
1281    /// The where-bound of `with_bound` doesn't specify the associated type, so we would
1282    /// only be able to normalize `<T as Trait<'a>>::Assoc` by using the impl. This impl
1283    /// adds a `T: 'a` bound however, which would result in a region error. Given that the
1284    /// user explicitly wrote that `T: Trait<'a>` holds, this is undesirable and we instead
1285    /// treat the alias as rigid.
1286    ///
1287    /// See trait-system-refactor-initiative#124 for more details.
1288    {}
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("assemble_and_merge_candidates",
                                "rustc_next_trait_solver::solve::assembly",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1288u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("proven_via")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("proven_via");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("goal")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("goal");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::Empty
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::Empty
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                QueryResultOrRerunNonErased<I> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let Some(proven_via) =
                            proven_via else {
                                return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand|
                                            cand.result);
                            };
                        match proven_via {
                            TraitGoalProvenVia::ParamEnv |
                                TraitGoalProvenVia::AliasBound => {
                                let (mut candidates, _) =
                                    self.assemble_and_evaluate_candidates(goal,
                                            AssembleCandidatesFrom::EnvAndBounds)?;
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1322",
                                                        "rustc_next_trait_solver::solve::assembly",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1322u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                                        ::tracing_core::field::FieldSet::new(&[{
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("candidates")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("candidates");
                                                                            NAME.as_str()
                                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                                                            as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                if candidates.is_empty() {
                                    return inject_normalize_to_rigid_candidate(self);
                                }
                                if let Some(result) =
                                        inject_forced_ambiguity_candidate(self) {
                                    return result;
                                }
                                if candidates.iter().any(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            }) {
                                    candidates.retain(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            });
                                }
                                if let Some((response, _)) =
                                        self.try_merge_candidates(&candidates) {
                                    Ok(response)
                                } else { self.flounder(&candidates).map_err(Into::into) }
                            }
                            TraitGoalProvenVia::Misc => {
                                let (mut candidates, _) =
                                    self.assemble_and_evaluate_candidates(goal,
                                            AssembleCandidatesFrom::All)?;
                                if candidates.iter().any(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            }) {
                                    candidates.retain(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            });
                                }
                                self.filter_specialized_impls(AllowInferenceConstraints::Yes,
                                    &mut candidates);
                                if let Some((response, _)) =
                                        self.try_merge_candidates(&candidates) {
                                    Ok(response)
                                } else { self.flounder(&candidates).map_err(Into::into) }
                            }
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1288",
                        "rustc_next_trait_solver::solve::assembly",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/76456a688bc0ed897fa23a677d4ddb5b3fdb575a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1288u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip_all, fields(proven_via, goal), ret)]
1289    pub(super) fn assemble_and_merge_candidates<G: GoalKind<D>>(
1290        &mut self,
1291        proven_via: Option<TraitGoalProvenVia>,
1292        goal: Goal<I, G>,
1293        inject_forced_ambiguity_candidate: impl FnOnce(
1294            &mut EvalCtxt<'_, D>,
1295        ) -> Option<
1296            Result<CanonicalResponse<I>, NoSolutionOrRerunNonErased>,
1297        >,
1298        inject_normalize_to_rigid_candidate: impl FnOnce(
1299            &mut EvalCtxt<'_, D>,
1300        ) -> Result<
1301            CanonicalResponse<I>,
1302            NoSolutionOrRerunNonErased,
1303        >,
1304    ) -> QueryResultOrRerunNonErased<I> {
1305        let Some(proven_via) = proven_via else {
1306            // We don't care about overflow. If proving the trait goal overflowed, then
1307            // it's enough to report an overflow error for that, we don't also have to
1308            // overflow during normalization.
1309            //
1310            // We use `forced_ambiguity` here over `make_ambiguous_response_no_constraints`
1311            // because the former will also record a built-in candidate in the inspector.
1312            return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand| cand.result);
1313        };
1314
1315        match proven_via {
1316            TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => {
1317                // Even when a trait bound has been proven using a where-bound, we
1318                // still need to consider alias-bounds for normalization, see
1319                // `tests/ui/next-solver/alias-bound-shadowed-by-env.rs`.
1320                let (mut candidates, _) = self
1321                    .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds)?;
1322                debug!(?candidates);
1323
1324                // If the trait goal has been proven by using the environment, we want to treat
1325                // aliases as rigid if there are no applicable projection bounds in the environment.
1326                if candidates.is_empty() {
1327                    return inject_normalize_to_rigid_candidate(self);
1328                }
1329
1330                // If we're normalizing an GAT, we bail if using a where-bound would constrain
1331                // its generic arguments.
1332                if let Some(result) = inject_forced_ambiguity_candidate(self) {
1333                    return result;
1334                }
1335
1336                // We still need to prefer where-bounds over alias-bounds however.
1337                // See `tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs`.
1338                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1339                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1340                }
1341
1342                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1343                    Ok(response)
1344                } else {
1345                    self.flounder(&candidates).map_err(Into::into)
1346                }
1347            }
1348            TraitGoalProvenVia::Misc => {
1349                let (mut candidates, _) =
1350                    self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1351
1352                // Prefer "orphaned" param-env normalization predicates, which are used
1353                // (for example, and ideally only) when proving item bounds for an impl.
1354                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1355                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1356                }
1357
1358                // We drop specialized impls to allow normalization via a final impl here. In case
1359                // the specializing impl has different inference constraints from the specialized
1360                // impl, proving the trait goal is already ambiguous, so we never get here. This
1361                // means we can just ignore inference constraints and don't have to special-case
1362                // constraining the normalized-to `term`.
1363                self.filter_specialized_impls(AllowInferenceConstraints::Yes, &mut candidates);
1364                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1365                    Ok(response)
1366                } else {
1367                    self.flounder(&candidates).map_err(Into::into)
1368                }
1369            }
1370        }
1371    }
1372
1373    /// Compute whether a param-env assumption is global or non-global after normalizing it.
1374    ///
1375    /// This is necessary because, for example, given:
1376    ///
1377    /// ```ignore,rust
1378    /// where
1379    ///     T: Trait<Assoc = u32>,
1380    ///     i32: From<T::Assoc>,
1381    /// ```
1382    ///
1383    /// The `i32: From<T::Assoc>` bound is non-global before normalization, but is global after.
1384    /// Since the old trait solver normalized param-envs eagerly, we want to emulate this
1385    /// behavior lazily.
1386    fn characterize_param_env_assumption(
1387        &mut self,
1388        param_env: I::ParamEnv,
1389        assumption: I::Clause,
1390    ) -> Result<(CandidateSource<I>, Certainty), NoSolution> {
1391        // FIXME: This should be fixed, but it also requires changing the behavior
1392        // in the old solver which is currently relied on.
1393        if assumption.has_bound_vars() {
1394            return Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), Certainty::Yes));
1395        }
1396
1397        match assumption.visit_with(&mut FindParamInClause {
1398            ecx: self,
1399            param_env,
1400            universes: ::alloc::vec::Vec::new()vec![],
1401            recursion_depth: 0,
1402        }) {
1403            ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1404            ControlFlow::Break(Ok(certainty)) => {
1405                Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), certainty))
1406            }
1407            ControlFlow::Continue(()) => {
1408                Ok((CandidateSource::ParamEnv(ParamEnvSource::Global), Certainty::Yes))
1409            }
1410        }
1411    }
1412}
1413
1414struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1415    ecx: &'a mut EvalCtxt<'b, D>,
1416    param_env: I::ParamEnv,
1417    universes: Vec<Option<ty::UniverseIndex>>,
1418    recursion_depth: usize,
1419}
1420
1421impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1422where
1423    D: SolverDelegate<Interner = I>,
1424    I: Interner,
1425{
1426    // - `Continue(())`: no generic parameter was found, the type is global
1427    // - `Break(Ok(Certainty::Yes))`: a generic parameter was found, the type is non-global
1428    // - `Break(Ok(Certainty::Maybe(_)))`: the recursion limit reached, assume that the type is non-global
1429    // - `Break(Err(NoSolution))`: normalization failed
1430    type Result = ControlFlow<Result<Certainty, NoSolution>>;
1431
1432    fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1433        self.universes.push(None);
1434        t.super_visit_with(self)?;
1435        self.universes.pop();
1436        ControlFlow::Continue(())
1437    }
1438
1439    fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1440        let ty = self.ecx.replace_bound_vars(ty, &mut self.universes);
1441        let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1442            return ControlFlow::Break(Err(NoSolution));
1443        };
1444
1445        match ty.kind() {
1446            ty::Placeholder(p) => {
1447                if p.universe() == ty::UniverseIndex::ROOT {
1448                    ControlFlow::Break(Ok(Certainty::Yes))
1449                } else {
1450                    ControlFlow::Continue(())
1451                }
1452            }
1453            ty::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1454            _ if ty.has_type_flags(
1455                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1456            ) =>
1457            {
1458                self.recursion_depth += 1;
1459                if self.recursion_depth > self.ecx.cx().recursion_limit() {
1460                    return ControlFlow::Break(Ok(Certainty::Maybe(MaybeInfo {
1461                        cause: MaybeCause::Overflow {
1462                            suggest_increasing_limit: true,
1463                            keep_constraints: false,
1464                        },
1465                        opaque_types_jank: OpaqueTypesJank::AllGood,
1466                        stalled_on_coroutines: StalledOnCoroutines::No,
1467                    })));
1468                }
1469                let result = ty.super_visit_with(self);
1470                self.recursion_depth -= 1;
1471                result
1472            }
1473            _ => ControlFlow::Continue(()),
1474        }
1475    }
1476
1477    fn visit_const(&mut self, ct: Const<I>) -> Self::Result {
1478        let ct = self.ecx.replace_bound_vars(ct, &mut self.universes);
1479        let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1480            return ControlFlow::Break(Err(NoSolution));
1481        };
1482
1483        match ct.kind() {
1484            ty::ConstKind::Placeholder(p) => {
1485                if p.universe() == ty::UniverseIndex::ROOT {
1486                    ControlFlow::Break(Ok(Certainty::Yes))
1487                } else {
1488                    ControlFlow::Continue(())
1489                }
1490            }
1491            ty::ConstKind::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1492            _ if ct.has_type_flags(
1493                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1494            ) =>
1495            {
1496                // FIXME(mgca): we should also check the recursion limit here
1497                ct.super_visit_with(self)
1498            }
1499            _ => ControlFlow::Continue(()),
1500        }
1501    }
1502
1503    fn visit_region(&mut self, r: Region<I>) -> Self::Result {
1504        match self.ecx.eager_resolve_region(r).kind() {
1505            ty::ReStatic | ty::ReError(_) | ty::ReBound(..) => ControlFlow::Continue(()),
1506            ty::RePlaceholder(p) => {
1507                if p.universe() == ty::UniverseIndex::ROOT {
1508                    ControlFlow::Break(Ok(Certainty::Yes))
1509                } else {
1510                    ControlFlow::Continue(())
1511                }
1512            }
1513            ty::ReVar(_) => ControlFlow::Break(Ok(Certainty::Yes)),
1514            ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
1515                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected region in param-env clause")));
}unreachable!("unexpected region in param-env clause")
1516            }
1517        }
1518    }
1519}