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, 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        Self::fast_reject_assumption(ecx, goal, assumption)?;
96
97        ecx.probe_trait_candidate(source).enter(|ecx| {
98            let cx = ecx.cx();
99            let ty::Dynamic(bounds, _) = goal.predicate.self_ty().kind() else {
100                {
    ::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`");
101            };
102
103            let trait_ref = assumption.kind().map_bound(|clause| match clause {
104                ty::ClauseKind::Trait(pred) => pred.trait_ref,
105                ty::ClauseKind::Projection(proj) => proj.projection_term.trait_ref(cx),
106
107                ty::ClauseKind::RegionOutlives(..)
108                | ty::ClauseKind::TypeOutlives(..)
109                | ty::ClauseKind::ConstArgHasType(..)
110                | ty::ClauseKind::WellFormed(..)
111                | ty::ClauseKind::ConstEvaluatable(..)
112                | ty::ClauseKind::HostEffect(..)
113                | ty::ClauseKind::UnstableFeature(..) => {
114                    {
    ::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")
115                }
116            });
117
118            // If we need to prove `dyn for<'x> Trait<'x> + '?temp: Trait<'static>` with
119            //
120            // ```rs
121            // trait Trait<'a>: 'a {}
122            // ```
123            //
124            // we have the goal's trait ref as `Trait<'static>` and a theoretical impl
125            // resembling:
126            //
127            // ```rs
128            // impl<'s, 'hr> Trait<'hr> for dyn for<'x> Trait<'x> + 's
129            // where
130            //     dyn for<'a> Trait<'a> + 's: 'hr
131            // {}
132            // ```
133            //
134            // where 'hr is our bound var. The where-clause elaborates to `'s: 'hr`;
135            // in this case we have 's := '?temp. Instantiating the binder gives us
136            // 'hr := '?infer, and our goal has 'hr := 'static, so we need to equate
137            // the instantiated trait ref to the goal in order to get '?infer := 'static,
138            // since what we want is the constraint `'?temp: 'static`.
139            //
140            // If we instead passed the binder to predicates_for_object_candidate and let
141            // it instantiate the binder itself, we would lose '?infer := 'static, since
142            // predicates_for_object_candidate has no way of equating the trait ref with
143            // the goal. We would simply have 'hr := '?infer, giving us the constraint
144            // `?temp: '?infer`, which is satisfiable for any lifetime, leading to
145            // unsoundness: trait-system-refactor-initiative#295.
146            let trait_ref = ecx.instantiate_binder_with_infer(trait_ref);
147            ecx.eq(goal.param_env, goal.predicate.trait_ref(cx), trait_ref)?;
148
149            match structural_traits::predicates_for_object_candidate(
150                ecx,
151                goal.param_env,
152                trait_ref,
153                bounds,
154            ) {
155                Ok(requirements) => {
156                    ecx.add_goals(GoalSource::ImplWhereBound, requirements)?;
157                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
158                }
159                Err(AmbiguousOrRerunNonErased::Ambiguous) => {
160                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
161                }
162                Err(AmbiguousOrRerunNonErased::RerunNonErased(rerun)) => Err(rerun.into()),
163            }
164        })
165    }
166
167    /// Assemble additional assumptions for an alias that are not included
168    /// in the item bounds of the alias. For now, this is limited to the
169    /// `explicit_implied_const_bounds` for an associated type.
170    fn consider_additional_alias_assumptions(
171        ecx: &mut EvalCtxt<'_, D>,
172        goal: Goal<I, Self>,
173        alias_ty: ty::AliasTy<I>,
174    ) -> Vec<Candidate<I>>;
175
176    fn probe_and_consider_param_env_candidate(
177        ecx: &mut EvalCtxt<'_, D>,
178        goal: Goal<I, Self>,
179        assumption: I::Clause,
180    ) -> Result<Result<Candidate<I>, CandidateHeadUsages>, RerunNonErased> {
181        match Self::fast_reject_assumption(ecx, goal, assumption) {
182            Ok(()) => {}
183            Err(NoSolution) => return Ok(Err(CandidateHeadUsages::default())),
184        }
185
186        // Dealing with `ParamEnv` candidates is a bit of a mess as we need to lazily
187        // check whether the candidate is global while considering normalization.
188        //
189        // We need to write into `source` inside of `match_assumption`, but need to access it
190        // in `probe` even if the candidate does not apply before we get there. We handle this
191        // by using a `Cell` here. We only ever write into it inside of `match_assumption`.
192        let source = Cell::new(CandidateSource::ParamEnv(ParamEnvSource::Global));
193        let (result, head_usages) = ecx
194            .probe(|result: &QueryResult<I>| inspect::ProbeKind::TraitCandidate {
195                source: source.get(),
196                result: *result,
197            })
198            .enter_single_candidate(|ecx| {
199                Self::match_assumption(
200                    ecx,
201                    goal,
202                    assumption,
203                    |ecx| -> Result<_, NoSolutionOrRerunNonErased> {
204                        ecx.try_evaluate_added_goals()?;
205                        let (src, certainty) =
206                            ecx.characterize_param_env_assumption(goal.param_env, assumption)?;
207                        source.set(src);
208                        ecx.evaluate_added_goals_and_make_canonical_response(certainty)
209                    },
210                )
211                .map_err(Into::into)
212            });
213
214        Ok(match result.map_err_to_rerun()? {
215            Ok(result) => Ok(Candidate { source: source.get(), result, head_usages }),
216            Err(NoSolution) => Err(head_usages),
217        })
218    }
219
220    /// Try equating an assumption predicate against a goal's predicate. If it
221    /// holds, then execute the `then` callback, which should do any additional
222    /// work, then produce a response (typically by executing
223    /// [`EvalCtxt::evaluate_added_goals_and_make_canonical_response`]).
224    fn probe_and_match_goal_against_assumption(
225        ecx: &mut EvalCtxt<'_, D>,
226        source: CandidateSource<I>,
227        goal: Goal<I, Self>,
228        assumption: I::Clause,
229        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
230    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
231        Self::fast_reject_assumption(ecx, goal, assumption)?;
232
233        ecx.probe_trait_candidate(source)
234            .enter(|ecx| Self::match_assumption(ecx, goal, assumption, then))
235    }
236
237    /// Try to reject the assumption based off of simple heuristics, such as [`ty::ClauseKind`]
238    /// and `DefId`.
239    fn fast_reject_assumption(
240        ecx: &mut EvalCtxt<'_, D>,
241        goal: Goal<I, Self>,
242        assumption: I::Clause,
243    ) -> Result<(), NoSolution>;
244
245    /// Relate the goal and assumption.
246    fn match_assumption(
247        ecx: &mut EvalCtxt<'_, D>,
248        goal: Goal<I, Self>,
249        assumption: I::Clause,
250        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
251    ) -> QueryResultOrRerunNonErased<I>;
252
253    /// Note: `goal_trait_ref` is derived from `goal`. Nonetheless, because
254    /// `consider_impl_candidate` is always called in a loop, we precompute `goal_trait_ref` once
255    /// and pass it in next to `goal` because the computation is expensive and loop-invariant.
256    fn consider_impl_candidate(
257        ecx: &mut EvalCtxt<'_, D>,
258        goal: Goal<I, Self>,
259        goal_trait_ref: ty::TraitRef<I>,
260        impl_def_id: I::ImplId,
261        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
262    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
263
264    /// If the predicate contained an error, we want to avoid emitting unnecessary trait
265    /// errors but still want to emit errors for other trait goals. We have some special
266    /// handling for this case.
267    ///
268    /// Trait goals always hold while projection goals never do. This is a bit arbitrary
269    /// but prevents incorrect normalization while hiding any trait errors.
270    fn consider_error_guaranteed_candidate(
271        ecx: &mut EvalCtxt<'_, D>,
272        goal: Goal<I, Self>,
273        guar: I::ErrorGuaranteed,
274    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
275
276    /// A type implements an `auto trait` if its components do as well.
277    ///
278    /// These components are given by built-in rules from
279    /// [`structural_traits::instantiate_constituent_tys_for_auto_trait`].
280    fn consider_auto_trait_candidate(
281        ecx: &mut EvalCtxt<'_, D>,
282        goal: Goal<I, Self>,
283    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
284
285    /// A trait alias holds if the RHS traits and `where` clauses hold.
286    fn consider_trait_alias_candidate(
287        ecx: &mut EvalCtxt<'_, D>,
288        goal: Goal<I, Self>,
289    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
290
291    /// A type is `Sized` if its tail component is `Sized` and a type is `MetaSized` if its tail
292    /// component is `MetaSized`.
293    ///
294    /// These components are given by built-in rules from
295    /// [`structural_traits::instantiate_constituent_tys_for_sizedness_trait`].
296    fn consider_builtin_sizedness_candidates(
297        ecx: &mut EvalCtxt<'_, D>,
298        goal: Goal<I, Self>,
299        sizedness: SizedTraitKind,
300    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
301
302    /// A type is `Copy` or `Clone` if its components are `Copy` or `Clone`.
303    ///
304    /// These components are given by built-in rules from
305    /// [`structural_traits::instantiate_constituent_tys_for_copy_clone_trait`].
306    fn consider_builtin_copy_clone_candidate(
307        ecx: &mut EvalCtxt<'_, D>,
308        goal: Goal<I, Self>,
309    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
310
311    /// A type is a `FnPtr` if it is of `FnPtr` type.
312    fn consider_builtin_fn_ptr_trait_candidate(
313        ecx: &mut EvalCtxt<'_, D>,
314        goal: Goal<I, Self>,
315    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
316
317    /// A callable type (a closure, fn def, or fn ptr) is known to implement the `Fn<A>`
318    /// family of traits where `A` is given by the signature of the type.
319    fn consider_builtin_fn_trait_candidates(
320        ecx: &mut EvalCtxt<'_, D>,
321        goal: Goal<I, Self>,
322        kind: ty::ClosureKind,
323    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
324
325    /// An async closure is known to implement the `AsyncFn<A>` family of traits
326    /// where `A` is given by the signature of the type.
327    fn consider_builtin_async_fn_trait_candidates(
328        ecx: &mut EvalCtxt<'_, D>,
329        goal: Goal<I, Self>,
330        kind: ty::ClosureKind,
331    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
332
333    /// Compute the built-in logic of the `AsyncFnKindHelper` helper trait, which
334    /// is used internally to delay computation for async closures until after
335    /// upvar analysis is performed in HIR typeck.
336    fn consider_builtin_async_fn_kind_helper_candidate(
337        ecx: &mut EvalCtxt<'_, D>,
338        goal: Goal<I, Self>,
339    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
340
341    /// `Tuple` is implemented if the `Self` type is a tuple.
342    fn consider_builtin_tuple_candidate(
343        ecx: &mut EvalCtxt<'_, D>,
344        goal: Goal<I, Self>,
345    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
346
347    /// `Pointee` is always implemented.
348    ///
349    /// See the projection implementation for the `Metadata` types for all of
350    /// the built-in types. For structs, the metadata type is given by the struct
351    /// tail.
352    fn consider_builtin_pointee_candidate(
353        ecx: &mut EvalCtxt<'_, D>,
354        goal: Goal<I, Self>,
355    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
356
357    /// A coroutine (that comes from an `async` desugaring) is known to implement
358    /// `Future<Output = O>`, where `O` is given by the coroutine's return type
359    /// that was computed during type-checking.
360    fn consider_builtin_future_candidate(
361        ecx: &mut EvalCtxt<'_, D>,
362        goal: Goal<I, Self>,
363    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
364
365    /// A coroutine (that comes from a `gen` desugaring) is known to implement
366    /// `Iterator<Item = O>`, where `O` is given by the generator's yield type
367    /// that was computed during type-checking.
368    fn consider_builtin_iterator_candidate(
369        ecx: &mut EvalCtxt<'_, D>,
370        goal: Goal<I, Self>,
371    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
372
373    /// A coroutine (that comes from a `gen` desugaring) is known to implement
374    /// `FusedIterator`
375    fn consider_builtin_fused_iterator_candidate(
376        ecx: &mut EvalCtxt<'_, D>,
377        goal: Goal<I, Self>,
378    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
379
380    fn consider_builtin_async_iterator_candidate(
381        ecx: &mut EvalCtxt<'_, D>,
382        goal: Goal<I, Self>,
383    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
384
385    /// A coroutine (that doesn't come from an `async` or `gen` desugaring) is known to
386    /// implement `Coroutine<R, Yield = Y, Return = O>`, given the resume, yield,
387    /// and return types of the coroutine computed during type-checking.
388    fn consider_builtin_coroutine_candidate(
389        ecx: &mut EvalCtxt<'_, D>,
390        goal: Goal<I, Self>,
391    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
392
393    fn consider_builtin_discriminant_kind_candidate(
394        ecx: &mut EvalCtxt<'_, D>,
395        goal: Goal<I, Self>,
396    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
397
398    fn consider_builtin_destruct_candidate(
399        ecx: &mut EvalCtxt<'_, D>,
400        goal: Goal<I, Self>,
401    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
402
403    fn consider_builtin_transmute_candidate(
404        ecx: &mut EvalCtxt<'_, D>,
405        goal: Goal<I, Self>,
406    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
407
408    fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
409        ecx: &mut EvalCtxt<'_, D>,
410        goal: Goal<I, Self>,
411    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
412
413    fn consider_builtin_try_as_dyn_candidate(
414        ecx: &mut EvalCtxt<'_, D>,
415        goal: Goal<I, Self>,
416    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
417
418    /// Consider (possibly several) candidates to upcast or unsize a type to another
419    /// type, excluding the coercion of a sized type into a `dyn Trait`.
420    ///
421    /// We return the `BuiltinImplSource` for each candidate as it is needed
422    /// for unsize coercion in hir typeck and because it is difficult to
423    /// otherwise recompute this for codegen. This is a bit of a mess but the
424    /// easiest way to maintain the existing behavior for now.
425    fn consider_structural_builtin_unsize_candidates(
426        ecx: &mut EvalCtxt<'_, D>,
427        goal: Goal<I, Self>,
428    ) -> Result<Vec<Candidate<I>>, RerunNonErased>;
429
430    fn consider_builtin_field_candidate(
431        ecx: &mut EvalCtxt<'_, D>,
432        goal: Goal<I, Self>,
433    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
434}
435
436/// Allows callers of `assemble_and_evaluate_candidates` to choose whether to limit
437/// candidate assembly to param-env and alias-bound candidates.
438///
439/// On top of being a micro-optimization, as it avoids doing unnecessary work when
440/// a param-env trait bound candidate shadows impls for normalization, this is also
441/// required to prevent query cycles due to RPITIT inference. See the issue at:
442/// <https://github.com/rust-lang/trait-system-refactor-initiative/issues/173>.
443pub(super) enum AssembleCandidatesFrom {
444    All,
445    /// Only assemble candidates from the environment and alias bounds, ignoring
446    /// user-written and built-in impls. We only expect `ParamEnv` and `AliasBound`
447    /// candidates to be assembled.
448    EnvAndBounds,
449}
450
451impl AssembleCandidatesFrom {
452    fn should_assemble_impl_candidates(&self) -> bool {
453        match self {
454            AssembleCandidatesFrom::All => true,
455            AssembleCandidatesFrom::EnvAndBounds => false,
456        }
457    }
458}
459
460/// This is currently used to track the [CandidateHeadUsages] of all failed `ParamEnv`
461/// candidates. This is then used to ignore their head usages in case there's another
462/// always applicable `ParamEnv` candidate. Look at how `param_env_head_usages` is
463/// used in the code for more details.
464///
465/// We could easily extend this to also ignore head usages of other ignored candidates.
466/// However, we currently don't have any tests where this matters and the complexity of
467/// doing so does not feel worth it for now.
468#[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)]
469pub(super) struct FailedCandidateInfo {
470    pub param_env_head_usages: CandidateHeadUsages,
471}
472
473impl<D, I> EvalCtxt<'_, D>
474where
475    D: SolverDelegate<Interner = I>,
476    I: Interner,
477{
478    // FIXME(#155443): This function should only ever return an error
479    // as we want to force a rerun when accessing opaques. We should change
480    // this file to revert all the newly added places which return `NoSolution`.
481    pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<D>>(
482        &mut self,
483        goal: Goal<I, G>,
484        assemble_from: AssembleCandidatesFrom,
485    ) -> Result<(Vec<Candidate<I>>, FailedCandidateInfo), RerunNonErased> {
486        let mut candidates = ::alloc::vec::Vec::new()vec![];
487        let mut failed_candidate_info =
488            FailedCandidateInfo { param_env_head_usages: CandidateHeadUsages::default() };
489        let Ok(normalized_self_ty) =
490            self.structurally_normalize_ty(goal.param_env, goal.predicate.self_ty())
491        else {
492            return Ok((candidates, failed_candidate_info));
493        };
494
495        let goal: Goal<I, G> = goal
496            .with(self.cx(), goal.predicate.with_replaced_self_ty(self.cx(), normalized_self_ty));
497
498        if normalized_self_ty.is_ty_var() {
499            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:499",
                        "rustc_next_trait_solver::solve::assembly",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(499u32),
                        ::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");
500            self.try_assemble_bounds_via_registered_opaques(goal, assemble_from, &mut candidates)?;
501            return Ok((candidates, failed_candidate_info));
502        }
503
504        // Vars that show up in the rest of the goal substs may have been constrained by
505        // normalizing the self type as well, since type variables are not uniquified.
506        let goal = self.deeply_resolve_ignoring_regions(goal);
507
508        if self.typing_mode().is_coherence()
509            && let Ok(candidate) = self.consider_coherence_unknowable_candidate(goal)
510        {
511            candidates.push(candidate);
512            return Ok((candidates, failed_candidate_info));
513        }
514
515        self.assemble_alias_bound_candidates(goal, &mut candidates)?;
516        self.assemble_param_env_candidates(goal, &mut candidates, &mut failed_candidate_info)?;
517
518        match assemble_from {
519            AssembleCandidatesFrom::All => {
520                self.assemble_builtin_impl_candidates(goal, &mut candidates)?;
521                // For performance we only assemble impls if there are no candidates
522                // which would shadow them. This is necessary to avoid hangs in rayon,
523                // see trait-system-refactor-initiative#109 for more details.
524                //
525                // We always assemble builtin impls as trivial builtin impls have a higher
526                // priority than where-clauses.
527                //
528                // We only do this if any such candidate applies without any constraints
529                // as we may want to weaken inference guidance in the future and don't want
530                // to worry about causing major performance regressions when doing so.
531                // See trait-system-refactor-initiative#226 for some ideas here.
532                let assemble_impls = match self.typing_mode() {
533                    TypingMode::Coherence => true,
534                    TypingMode::Typeck { .. }
535                    | TypingMode::PostTypeckUntilBorrowck { .. }
536                    | TypingMode::Reflection
537                    | TypingMode::PostBorrowck { .. }
538                    | TypingMode::PostAnalysis
539                    | TypingMode::Codegen
540                    | TypingMode::ErasedNotCoherence(MayBeErased) => !candidates.iter().any(|c| {
541                        #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(ParamEnvSource::NonGlobal) |
        CandidateSource::AliasBound(_) => true,
    _ => false,
}matches!(
542                            c.source,
543                            CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)
544                                | CandidateSource::AliasBound(_)
545                        ) && has_no_inference_or_external_constraints(c.result)
546                    }),
547                };
548                if assemble_impls {
549                    self.assemble_impl_candidates(goal, &mut candidates)?;
550                    self.assemble_object_bound_candidates(goal, &mut candidates);
551                }
552            }
553            AssembleCandidatesFrom::EnvAndBounds => {
554                // This is somewhat inconsistent and may make #57893 slightly easier to exploit.
555                // However, it matches the behavior of the old solver. See
556                // `tests/ui/traits/next-solver/normalization-shadowing/use_object_if_empty_env.rs`.
557                if #[allow(non_exhaustive_omitted_patterns)] match normalized_self_ty.kind() {
    ty::Dynamic(..) => true,
    _ => false,
}matches!(normalized_self_ty.kind(), ty::Dynamic(..))
558                    && !candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(_) => true,
    _ => false,
}matches!(c.source, CandidateSource::ParamEnv(_)))
559                {
560                    self.assemble_object_bound_candidates(goal, &mut candidates);
561                }
562            }
563        }
564
565        Ok((candidates, failed_candidate_info))
566    }
567
568    pub(super) fn forced_ambiguity(
569        &mut self,
570        maybe: MaybeInfo,
571    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
572        // This may fail if `try_evaluate_added_goals` overflows because it
573        // fails to reach a fixpoint but ends up getting an error after
574        // running for some additional step.
575        //
576        // FIXME(@lcnr): While I believe an error here to be possible, we
577        // currently don't have any test which actually triggers it. @lqd
578        // created a minimization for an ICE in typenum, but that one no
579        // longer fails here. cc trait-system-refactor-initiative#105.
580        let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
581        let certainty = Certainty::Maybe(maybe);
582        self.probe_trait_candidate(source)
583            .enter(|this| this.evaluate_added_goals_and_make_canonical_response(certainty))
584    }
585
586    {}
#[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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(586u32),
                                    ::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)]
587    fn assemble_impl_candidates<G: GoalKind<D>>(
588        &mut self,
589        goal: Goal<I, G>,
590        candidates: &mut Vec<Candidate<I>>,
591    ) -> Result<(), RerunNonErased> {
592        let cx = self.cx();
593        let goal_trait_ref = goal.predicate.trait_ref(cx);
594        cx.for_each_relevant_impl(goal_trait_ref, |impl_def_id| -> Result<_, _> {
595            match G::consider_impl_candidate(self, goal, goal_trait_ref, impl_def_id, |ecx| {
596                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
597            })
598            .map_err_to_rerun()?
599            {
600                Ok(candidate) => candidates.push(candidate),
601                Err(NoSolution) => {}
602            }
603
604            Ok(())
605        })
606    }
607
608    {}
#[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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(608u32),
                                    ::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)]
609    fn assemble_builtin_impl_candidates<G: GoalKind<D>>(
610        &mut self,
611        goal: Goal<I, G>,
612        candidates: &mut Vec<Candidate<I>>,
613    ) -> Result<(), RerunNonErased> {
614        let cx = self.cx();
615        let trait_def_id = goal.predicate.trait_def_id(cx);
616
617        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
618        // of trying to handle these manually, we just reject all builtin impls in reflection
619        // mode. We can probably lift this restriction for specific cases, but this is safer.
620        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
621        if self.typing_mode().is_reflection() {
622            return Ok(());
623        }
624
625        // N.B. When assembling built-in candidates for lang items that are also
626        // `auto` traits, then the auto trait candidate that is assembled in
627        // `consider_auto_trait_candidate` MUST be disqualified to remain sound.
628        //
629        // Instead of adding the logic here, it's a better idea to add it in
630        // `EvalCtxt::disqualify_auto_trait_candidate_due_to_possible_impl` in
631        // `solve::trait_goals` instead.
632        let result = if let ty::Error(guar) = goal.predicate.self_ty().kind() {
633            G::consider_error_guaranteed_candidate(self, goal, guar)
634        } else if cx.trait_is_auto(trait_def_id) {
635            G::consider_auto_trait_candidate(self, goal)
636        } else if cx.trait_is_alias(trait_def_id) {
637            G::consider_trait_alias_candidate(self, goal)
638        } else {
639            match cx.as_trait_lang_item(trait_def_id) {
640                Some(SolverTraitLangItem::Sized) => {
641                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::Sized)
642                }
643                Some(SolverTraitLangItem::MetaSized) => {
644                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::MetaSized)
645                }
646                Some(SolverTraitLangItem::PointeeSized) => {
647                    unreachable!("`PointeeSized` is removed during lowering");
648                }
649                Some(
650                    SolverTraitLangItem::Copy
651                    | SolverTraitLangItem::Clone
652                    | SolverTraitLangItem::TrivialClone,
653                ) => G::consider_builtin_copy_clone_candidate(self, goal),
654                Some(SolverTraitLangItem::Fn) => {
655                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
656                }
657                Some(SolverTraitLangItem::FnMut) => {
658                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnMut)
659                }
660                Some(SolverTraitLangItem::FnOnce) => {
661                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnOnce)
662                }
663                Some(SolverTraitLangItem::AsyncFn) => {
664                    G::consider_builtin_async_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
665                }
666                Some(SolverTraitLangItem::AsyncFnMut) => {
667                    G::consider_builtin_async_fn_trait_candidates(
668                        self,
669                        goal,
670                        ty::ClosureKind::FnMut,
671                    )
672                }
673                Some(SolverTraitLangItem::AsyncFnOnce) => {
674                    G::consider_builtin_async_fn_trait_candidates(
675                        self,
676                        goal,
677                        ty::ClosureKind::FnOnce,
678                    )
679                }
680                Some(SolverTraitLangItem::FnPtrTrait) => {
681                    G::consider_builtin_fn_ptr_trait_candidate(self, goal)
682                }
683                Some(SolverTraitLangItem::AsyncFnKindHelper) => {
684                    G::consider_builtin_async_fn_kind_helper_candidate(self, goal)
685                }
686                Some(SolverTraitLangItem::Tuple) => G::consider_builtin_tuple_candidate(self, goal),
687                Some(SolverTraitLangItem::PointeeTrait) => {
688                    G::consider_builtin_pointee_candidate(self, goal)
689                }
690                Some(SolverTraitLangItem::Future) => {
691                    G::consider_builtin_future_candidate(self, goal)
692                }
693                Some(SolverTraitLangItem::Iterator) => {
694                    G::consider_builtin_iterator_candidate(self, goal)
695                }
696                Some(SolverTraitLangItem::FusedIterator) => {
697                    G::consider_builtin_fused_iterator_candidate(self, goal)
698                }
699                Some(SolverTraitLangItem::AsyncIterator) => {
700                    G::consider_builtin_async_iterator_candidate(self, goal)
701                }
702                Some(SolverTraitLangItem::Coroutine) => {
703                    G::consider_builtin_coroutine_candidate(self, goal)
704                }
705                Some(SolverTraitLangItem::DiscriminantKind) => {
706                    G::consider_builtin_discriminant_kind_candidate(self, goal)
707                }
708                Some(SolverTraitLangItem::Destruct) => {
709                    G::consider_builtin_destruct_candidate(self, goal)
710                }
711                Some(SolverTraitLangItem::TransmuteTrait) => {
712                    G::consider_builtin_transmute_candidate(self, goal)
713                }
714                Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
715                    G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self, goal)
716                }
717                Some(SolverTraitLangItem::TryAsDyn) => {
718                    G::consider_builtin_try_as_dyn_candidate(self, goal)
719                }
720                Some(SolverTraitLangItem::Field) => G::consider_builtin_field_candidate(self, goal),
721                _ => Err(NoSolution.into()),
722            }
723        };
724
725        candidates.extend(result);
726
727        // There may be multiple unsize candidates for a trait with several supertraits:
728        // `trait Foo: Bar<A> + Bar<B>` and `dyn Foo: Unsize<dyn Bar<_>>`
729        if cx.is_trait_lang_item(trait_def_id, SolverTraitLangItem::Unsize) {
730            candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal)?);
731        }
732
733        Ok(())
734    }
735
736    {}
#[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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(736u32),
                                    ::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;
        }
        {
            for assumption in goal.param_env.caller_bounds() {
                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)
                    }
                }
            }
            Ok(())
        }
    }
}#[instrument(level = "trace", skip_all)]
737    fn assemble_param_env_candidates<G: GoalKind<D>>(
738        &mut self,
739        goal: Goal<I, G>,
740        candidates: &mut Vec<Candidate<I>>,
741        failed_candidate_info: &mut FailedCandidateInfo,
742    ) -> Result<(), RerunNonErased> {
743        for assumption in goal.param_env.caller_bounds() {
744            match G::probe_and_consider_param_env_candidate(self, goal, assumption)? {
745                Ok(candidate) => candidates.push(candidate),
746                Err(head_usages) => {
747                    failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
748                }
749            }
750        }
751
752        Ok(())
753    }
754
755    {}
#[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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(755u32),
                                    ::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::panic("internal error: entered unreachable code")
                }
            }
        }
    }
}#[instrument(level = "trace", skip_all)]
756    fn assemble_alias_bound_candidates<G: GoalKind<D>>(
757        &mut self,
758        goal: Goal<I, G>,
759        candidates: &mut Vec<Candidate<I>>,
760    ) -> Result<(), RerunNonErased> {
761        let res = self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
762            ecx.assemble_alias_bound_candidates_recur(
763                goal.predicate.self_ty(),
764                goal,
765                candidates,
766                AliasBoundKind::SelfBounds,
767            )?;
768            Ok(())
769        });
770
771        // always returns Ok
772        match res {
773            Ok(_) => Ok(()),
774            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
775            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
776                unreachable!()
777            }
778        }
779    }
780
781    /// For some deeply nested `<T>::A::B::C::D` rigid associated type,
782    /// we should explore the item bounds for all levels, since the
783    /// `associated_type_bounds` feature means that a parent associated
784    /// type may carry bounds for a nested associated type.
785    ///
786    /// If we have a projection, check that its self type is a rigid projection.
787    /// If so, continue searching by recursively calling after normalization.
788    // FIXME: This may recurse infinitely, but I can't seem to trigger it without
789    // hitting another overflow error something. Add a depth parameter needed later.
790    fn assemble_alias_bound_candidates_recur<G: GoalKind<D>>(
791        &mut self,
792        self_ty: I::Ty,
793        goal: Goal<I, G>,
794        candidates: &mut Vec<Candidate<I>>,
795        consider_self_bounds: AliasBoundKind,
796    ) -> Result<(), RerunNonErased> {
797        let (alias_ty, def_id) = match self_ty.kind() {
798            ty::Bool
799            | ty::Char
800            | ty::Int(_)
801            | ty::Uint(_)
802            | ty::Float(_)
803            | ty::Adt(_, _)
804            | ty::Foreign(_)
805            | ty::Str
806            | ty::Array(_, _)
807            | ty::Pat(_, _)
808            | ty::Slice(_)
809            | ty::RawPtr(_, _)
810            | ty::Ref(_, _, _)
811            | ty::FnDef(_, _)
812            | ty::FnPtr(..)
813            | ty::UnsafeBinder(_)
814            | ty::Dynamic(..)
815            | ty::Closure(..)
816            | ty::CoroutineClosure(..)
817            | ty::Coroutine(..)
818            | ty::CoroutineWitness(..)
819            | ty::Never
820            | ty::Tuple(_)
821            | ty::Param(_)
822            | ty::Placeholder(..)
823            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
824            | ty::Error(_) => return Ok(()),
825            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => {
826                {
    ::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
            goal));
}panic!("unexpected self type for `{goal:?}`")
827            }
828
829            ty::Infer(ty::TyVar(_)) => {
830                // If we hit infer when normalizing the self type of an alias,
831                // then bail with ambiguity. We should never encounter this on
832                // the *first* iteration of this recursive function.
833                if let Ok(result) =
834                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
835                {
836                    candidates.push(Candidate {
837                        source: CandidateSource::AliasBound(consider_self_bounds),
838                        result,
839                        head_usages: CandidateHeadUsages::default(),
840                    });
841                }
842                return Ok(());
843            }
844
845            ty::Alias(
846                ty::IsRigid::Yes,
847                alias_ty @ AliasTy { kind: ty::Projection { def_id }, .. },
848            ) => (alias_ty, def_id.into()),
849
850            ty::Alias(ty::IsRigid::Yes, alias_ty @ AliasTy { kind: ty::Opaque { def_id }, .. }) => {
851                (alias_ty, def_id.into())
852            }
853
854            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:?}"),
855
856            ty::Alias(
857                ty::IsRigid::Yes,
858                AliasTy { kind: ty::Inherent { .. } | ty::Free { .. }, .. },
859            ) => {
860                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"));
861                return Ok(());
862            }
863        };
864
865        match consider_self_bounds {
866            AliasBoundKind::SelfBounds => {
867                for assumption in self
868                    .cx()
869                    .item_self_bounds(def_id)
870                    .iter_instantiated(self.cx(), alias_ty.args)
871                    .map(Unnormalized::skip_norm_wip)
872                {
873                    candidates.extend(G::probe_and_consider_implied_clause(
874                        self,
875                        CandidateSource::AliasBound(consider_self_bounds),
876                        goal,
877                        assumption,
878                        [],
879                    ));
880                }
881            }
882            AliasBoundKind::NonSelfBounds => {
883                for assumption in self
884                    .cx()
885                    .item_non_self_bounds(def_id)
886                    .iter_instantiated(self.cx(), alias_ty.args)
887                    .map(Unnormalized::skip_norm_wip)
888                {
889                    candidates.extend(G::probe_and_consider_implied_clause(
890                        self,
891                        CandidateSource::AliasBound(consider_self_bounds),
892                        goal,
893                        assumption,
894                        [],
895                    ));
896                }
897            }
898        }
899
900        candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty));
901
902        let Some(projection_ty) = alias_ty.try_to_projection() else {
903            return Ok(());
904        };
905
906        // Recurse on the self type of the projection.
907        match self.structurally_normalize_ty(goal.param_env, projection_ty.projection_self_ty()) {
908            Ok(next_self_ty) => self.assemble_alias_bound_candidates_recur(
909                next_self_ty,
910                goal,
911                candidates,
912                AliasBoundKind::NonSelfBounds,
913            ),
914            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Ok(()),
915            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
916        }
917    }
918
919    {}
#[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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(919u32),
                                    ::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)]
920    fn assemble_object_bound_candidates<G: GoalKind<D>>(
921        &mut self,
922        goal: Goal<I, G>,
923        candidates: &mut Vec<Candidate<I>>,
924    ) {
925        let cx = self.cx();
926        if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
927            // `dyn MetaSized` is valid, but should get its `MetaSized` impl from
928            // being `dyn` (SizedCandidate), not from the object candidate.
929            return;
930        }
931
932        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
933        // of trying to handle these manually, we just reject all builtin impls in reflection
934        // mode. We can probably lift this restriction for specific cases, but this is safer.
935        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
936        if self.typing_mode().is_reflection() {
937            return;
938        }
939
940        let self_ty = goal.predicate.self_ty();
941        let bounds = match self_ty.kind() {
942            ty::Bool
943            | ty::Char
944            | ty::Int(_)
945            | ty::Uint(_)
946            | ty::Float(_)
947            | ty::Adt(_, _)
948            | ty::Foreign(_)
949            | ty::Str
950            | ty::Array(_, _)
951            | ty::Pat(_, _)
952            | ty::Slice(_)
953            | ty::RawPtr(_, _)
954            | ty::Ref(_, _, _)
955            | ty::FnDef(_, _)
956            | ty::FnPtr(..)
957            | ty::UnsafeBinder(_)
958            | ty::Alias(..)
959            | ty::Closure(..)
960            | ty::CoroutineClosure(..)
961            | ty::Coroutine(..)
962            | ty::CoroutineWitness(..)
963            | ty::Never
964            | ty::Tuple(_)
965            | ty::Param(_)
966            | ty::Placeholder(..)
967            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
968            | ty::Error(_) => return,
969            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
970            | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"),
971            ty::Dynamic(bounds, ..) => bounds,
972        };
973
974        // Do not consider built-in object impls for dyn-incompatible types.
975        if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
976            return;
977        }
978
979        // Consider all of the auto-trait and projection bounds, which don't
980        // need to be recorded as a `BuiltinImplSource::Object` since they don't
981        // really have a vtable base...
982        for bound in bounds.iter() {
983            match bound.skip_binder() {
984                ty::ExistentialPredicate::Trait(_) => {
985                    // Skip principal
986                }
987                ty::ExistentialPredicate::Projection(_)
988                | ty::ExistentialPredicate::AutoTrait(_) => {
989                    candidates.extend(G::probe_and_consider_object_bound_candidate(
990                        self,
991                        CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
992                        goal,
993                        bound.with_self_ty(cx, self_ty),
994                    ));
995                }
996            }
997        }
998
999        // FIXME: We only need to do *any* of this if we're considering a trait goal,
1000        // since we don't need to look at any supertrait or anything if we are doing
1001        // a projection goal.
1002        if let Some(principal) = bounds.principal() {
1003            let principal_trait_ref = principal.with_self_ty(cx, self_ty);
1004            for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
1005                candidates.extend(G::probe_and_consider_object_bound_candidate(
1006                    self,
1007                    CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
1008                    goal,
1009                    assumption.upcast(cx),
1010                ));
1011            }
1012        }
1013    }
1014
1015    /// In coherence we have to not only care about all impls we know about, but
1016    /// also consider impls which may get added in a downstream or sibling crate
1017    /// or which an upstream impl may add in a minor release.
1018    ///
1019    /// To do so we return a single ambiguous candidate in case such an unknown
1020    /// impl could apply to the current goal.
1021    {}
#[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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1021u32),
                                    ::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)]
1022    fn consider_coherence_unknowable_candidate<G: GoalKind<D>>(
1023        &mut self,
1024        goal: Goal<I, G>,
1025    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1026        self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx| {
1027            let cx = ecx.cx();
1028            let trait_ref = goal.predicate.trait_ref(cx);
1029            if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
1030                Err(NoSolution.into())
1031            } else {
1032                // While the trait bound itself may be unknowable, we may be able to
1033                // prove that a super trait is not implemented. For this, we recursively
1034                // prove the super trait bounds of the current goal.
1035                //
1036                // We skip the goal itself as that one would cycle.
1037                let predicate: I::Predicate = trait_ref.upcast(cx);
1038                ecx.add_goals(
1039                    GoalSource::Misc,
1040                    elaborate::elaborate(cx, [predicate])
1041                        .skip(1)
1042                        .map(|predicate| goal.with(cx, predicate)),
1043                )?;
1044                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1045            }
1046        })
1047    }
1048}
1049
1050pub(super) enum AllowInferenceConstraints {
1051    Yes,
1052    No,
1053}
1054
1055impl<D, I> EvalCtxt<'_, D>
1056where
1057    D: SolverDelegate<Interner = I>,
1058    I: Interner,
1059{
1060    /// Check whether we can ignore impl candidates due to specialization.
1061    ///
1062    /// This is only necessary for `feature(specialization)` and seems quite ugly.
1063    pub(super) fn filter_specialized_impls(
1064        &mut self,
1065        allow_inference_constraints: AllowInferenceConstraints,
1066        candidates: &mut Vec<Candidate<I>>,
1067    ) {
1068        if self.typing_mode().is_coherence() {
1069            return;
1070        }
1071
1072        let mut i = 0;
1073        'outer: while i < candidates.len() {
1074            let CandidateSource::Impl(victim_def_id) = candidates[i].source else {
1075                i += 1;
1076                continue;
1077            };
1078
1079            for (j, c) in candidates.iter().enumerate() {
1080                if i == j {
1081                    continue;
1082                }
1083
1084                let CandidateSource::Impl(other_def_id) = c.source else {
1085                    continue;
1086                };
1087
1088                // See if we can toss out `victim` based on specialization.
1089                //
1090                // While this requires us to know *for sure* that the `lhs` impl applies
1091                // we still use modulo regions here. This is fine as specialization currently
1092                // assumes that specializing impls have to be always applicable, meaning that
1093                // the only allowed region constraints may be constraints also present on the default impl.
1094                if #[allow(non_exhaustive_omitted_patterns)] match allow_inference_constraints {
    AllowInferenceConstraints::Yes => true,
    _ => false,
}matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
1095                    || has_only_region_constraints(c.result)
1096                {
1097                    if self.cx().impl_specializes(other_def_id, victim_def_id) {
1098                        candidates.remove(i);
1099                        continue 'outer;
1100                    }
1101                }
1102            }
1103
1104            i += 1;
1105        }
1106    }
1107
1108    /// If the self type is the hidden type of an opaque, try to assemble
1109    /// candidates for it by consider its item bounds and by using blanket
1110    /// impls. This is used to incompletely guide type inference when handling
1111    /// non-defining uses in the defining scope.
1112    ///
1113    /// We otherwise just fail fail with ambiguity. Even if we're using an
1114    /// opaque type item bound or a blank impls, we still force its certainty
1115    /// to be `Maybe` so that we properly prove this goal later.
1116    ///
1117    /// See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/182>
1118    /// for why this is necessary.
1119    {}
#[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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1119u32),
                                    ::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::PostTypeckUntilBorrowck { .. } |
                        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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1149",
                                        "rustc_next_trait_solver::solve::assembly",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1149u32),
                                        ::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))]
1120    fn try_assemble_bounds_via_registered_opaques<G: GoalKind<D>>(
1121        &mut self,
1122        goal: Goal<I, G>,
1123        assemble_from: AssembleCandidatesFrom,
1124        candidates: &mut Vec<Candidate<I>>,
1125    ) -> Result<(), RerunNonErased> {
1126        let self_ty = goal.predicate.self_ty();
1127        // We only use this hack during HIR typeck.
1128        let opaque_types = match self.typing_mode() {
1129            TypingMode::Typeck { .. } => self.opaques_with_sub_unified_hidden_type(self_ty),
1130            TypingMode::Coherence
1131            | TypingMode::PostTypeckUntilBorrowck { .. }
1132            | TypingMode::PostBorrowck { .. }
1133            | TypingMode::PostAnalysis
1134            | TypingMode::Reflection
1135            | TypingMode::Codegen => vec![],
1136            TypingMode::ErasedNotCoherence(MayBeErased) => {
1137                self.opaque_accesses
1138                    .rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
1139                Vec::new()
1140            }
1141        };
1142
1143        if opaque_types.is_empty() {
1144            candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
1145            return Ok(());
1146        }
1147
1148        for &opaque_ty in &opaque_types {
1149            debug!("self ty is sub unified with {opaque_ty:?}");
1150
1151            struct ReplaceOpaque<I: Interner> {
1152                cx: I,
1153                opaque_ty: ty::OpaqueAliasTy<I>,
1154                self_ty: I::Ty,
1155            }
1156            impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
1157                fn cx(&self) -> I {
1158                    self.cx
1159                }
1160                fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1161                    if let ty::Alias(is_rigid, alias_ty) = ty.kind()
1162                        && let Some(opaque_ty) = alias_ty.try_to_opaque()
1163                    {
1164                        if opaque_ty == self.opaque_ty {
1165                            debug_assert_eq!(is_rigid, ty::IsRigid::No);
1166                            return self.self_ty;
1167                        }
1168                    }
1169                    ty.super_fold_with(self)
1170                }
1171            }
1172
1173            // We look at all item-bounds of the opaque, replacing the
1174            // opaque with the current self type before considering
1175            // them as a candidate. Imagine we've got `?x: Trait<?y>`
1176            // and `?x` has been sub-unified with the hidden type of
1177            // `impl Trait<u32>`, We take the item bound `opaque: Trait<u32>`
1178            // and replace all occurrences of `opaque` with `?x`. This results
1179            // in a `?x: Trait<u32>` alias-bound candidate.
1180            for item_bound in self
1181                .cx()
1182                .item_self_bounds(opaque_ty.kind.into())
1183                .iter_instantiated(self.cx(), opaque_ty.args)
1184                .map(Unnormalized::skip_norm_wip)
1185            {
1186                let assumption =
1187                    item_bound.fold_with(&mut ReplaceOpaque { cx: self.cx(), opaque_ty, self_ty });
1188                candidates.extend(G::probe_and_match_goal_against_assumption(
1189                    self,
1190                    CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
1191                    goal,
1192                    assumption,
1193                    |ecx| {
1194                        // We want to reprove this goal once we've inferred the
1195                        // hidden type, so we force the certainty to `Maybe`.
1196                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1197                    },
1198                ));
1199            }
1200        }
1201
1202        // If the self type is sub unified with any opaque type, we also look at blanket
1203        // impls for it.
1204        //
1205        // See tests/ui/impl-trait/non-defining-uses/use-blanket-impl.rs for an example.
1206        if assemble_from.should_assemble_impl_candidates() {
1207            let cx = self.cx();
1208            let goal_trait_ref = goal.predicate.trait_ref(cx);
1209
1210            cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx), |impl_def_id| {
1211                match G::consider_impl_candidate(self, goal, goal_trait_ref, impl_def_id, |ecx| {
1212                    if ecx.shallow_resolve(self_ty).is_ty_var() {
1213                        // We force the certainty of impl candidates to be `Maybe`.
1214                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1215                    } else {
1216                        // We don't want to use impls if they constrain the opaque.
1217                        //
1218                        // FIXME(trait-system-refactor-initiative#229): This isn't
1219                        // perfect yet as it still allows us to incorrectly constrain
1220                        // other inference variables.
1221                        Err(NoSolution.into())
1222                    }
1223                })
1224                .map_err_to_rerun()?
1225                {
1226                    Ok(candidate) => candidates.push(candidate),
1227                    Err(NoSolution) => {}
1228                }
1229
1230                Ok(())
1231            })?;
1232        }
1233
1234        if candidates.is_empty() {
1235            let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1236            let certainty = Certainty::Maybe(MaybeInfo {
1237                cause: MaybeCause::Ambiguity,
1238                opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
1239                stalled_on_coroutines: StalledOnCoroutines::No,
1240            });
1241            candidates
1242                .extend(self.probe_trait_candidate(source).enter(|this| {
1243                    this.evaluate_added_goals_and_make_canonical_response(certainty)
1244                }));
1245        }
1246
1247        Ok(())
1248    }
1249
1250    /// Assemble and merge candidates for goals which are related to an underlying trait
1251    /// goal. Right now, this is normalizes-to and host effect goals.
1252    ///
1253    /// We sadly can't simply take all possible candidates for normalization goals
1254    /// and check whether they result in the same constraints. We want to make sure
1255    /// that trying to normalize an alias doesn't result in constraints which aren't
1256    /// otherwise required.
1257    ///
1258    /// Most notably, when proving a trait goal by via a where-bound, we should not
1259    /// normalize via impls which have stricter region constraints than the where-bound:
1260    ///
1261    /// ```rust
1262    /// trait Trait<'a> {
1263    ///     type Assoc;
1264    /// }
1265    ///
1266    /// impl<'a, T: 'a> Trait<'a> for T {
1267    ///     type Assoc = u32;
1268    /// }
1269    ///
1270    /// fn with_bound<'a, T: Trait<'a>>(_value: T::Assoc) {}
1271    /// ```
1272    ///
1273    /// The where-bound of `with_bound` doesn't specify the associated type, so we would
1274    /// only be able to normalize `<T as Trait<'a>>::Assoc` by using the impl. This impl
1275    /// adds a `T: 'a` bound however, which would result in a region error. Given that the
1276    /// user explicitly wrote that `T: Trait<'a>` holds, this is undesirable and we instead
1277    /// treat the alias as rigid.
1278    ///
1279    /// See trait-system-refactor-initiative#124 for more details.
1280    {}
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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1280u32),
                                ::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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1314",
                                                        "rustc_next_trait_solver::solve::assembly",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1314u32),
                                                        ::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/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1280",
                        "rustc_next_trait_solver::solve::assembly",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1280u32),
                        ::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)]
1281    pub(super) fn assemble_and_merge_candidates<G: GoalKind<D>>(
1282        &mut self,
1283        proven_via: Option<TraitGoalProvenVia>,
1284        goal: Goal<I, G>,
1285        inject_forced_ambiguity_candidate: impl FnOnce(
1286            &mut EvalCtxt<'_, D>,
1287        ) -> Option<
1288            Result<CanonicalResponse<I>, NoSolutionOrRerunNonErased>,
1289        >,
1290        inject_normalize_to_rigid_candidate: impl FnOnce(
1291            &mut EvalCtxt<'_, D>,
1292        ) -> Result<
1293            CanonicalResponse<I>,
1294            NoSolutionOrRerunNonErased,
1295        >,
1296    ) -> QueryResultOrRerunNonErased<I> {
1297        let Some(proven_via) = proven_via else {
1298            // We don't care about overflow. If proving the trait goal overflowed, then
1299            // it's enough to report an overflow error for that, we don't also have to
1300            // overflow during normalization.
1301            //
1302            // We use `forced_ambiguity` here over `make_ambiguous_response_no_constraints`
1303            // because the former will also record a built-in candidate in the inspector.
1304            return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand| cand.result);
1305        };
1306
1307        match proven_via {
1308            TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => {
1309                // Even when a trait bound has been proven using a where-bound, we
1310                // still need to consider alias-bounds for normalization, see
1311                // `tests/ui/next-solver/alias-bound-shadowed-by-env.rs`.
1312                let (mut candidates, _) = self
1313                    .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds)?;
1314                debug!(?candidates);
1315
1316                // If the trait goal has been proven by using the environment, we want to treat
1317                // aliases as rigid if there are no applicable projection bounds in the environment.
1318                if candidates.is_empty() {
1319                    return inject_normalize_to_rigid_candidate(self);
1320                }
1321
1322                // If we're normalizing an GAT, we bail if using a where-bound would constrain
1323                // its generic arguments.
1324                if let Some(result) = inject_forced_ambiguity_candidate(self) {
1325                    return result;
1326                }
1327
1328                // We still need to prefer where-bounds over alias-bounds however.
1329                // See `tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs`.
1330                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1331                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1332                }
1333
1334                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1335                    Ok(response)
1336                } else {
1337                    self.flounder(&candidates).map_err(Into::into)
1338                }
1339            }
1340            TraitGoalProvenVia::Misc => {
1341                let (mut candidates, _) =
1342                    self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1343
1344                // Prefer "orphaned" param-env normalization predicates, which are used
1345                // (for example, and ideally only) when proving item bounds for an impl.
1346                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1347                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1348                }
1349
1350                // We drop specialized impls to allow normalization via a final impl here. In case
1351                // the specializing impl has different inference constraints from the specialized
1352                // impl, proving the trait goal is already ambiguous, so we never get here. This
1353                // means we can just ignore inference constraints and don't have to special-case
1354                // constraining the normalized-to `term`.
1355                self.filter_specialized_impls(AllowInferenceConstraints::Yes, &mut candidates);
1356                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1357                    Ok(response)
1358                } else {
1359                    self.flounder(&candidates).map_err(Into::into)
1360                }
1361            }
1362        }
1363    }
1364
1365    /// Compute whether a param-env assumption is global or non-global after normalizing it.
1366    ///
1367    /// This is necessary because, for example, given:
1368    ///
1369    /// ```ignore,rust
1370    /// where
1371    ///     T: Trait<Assoc = u32>,
1372    ///     i32: From<T::Assoc>,
1373    /// ```
1374    ///
1375    /// The `i32: From<T::Assoc>` bound is non-global before normalization, but is global after.
1376    /// Since the old trait solver normalized param-envs eagerly, we want to emulate this
1377    /// behavior lazily.
1378    fn characterize_param_env_assumption(
1379        &mut self,
1380        param_env: I::ParamEnv,
1381        assumption: I::Clause,
1382    ) -> Result<(CandidateSource<I>, Certainty), NoSolution> {
1383        // FIXME: This should be fixed, but it also requires changing the behavior
1384        // in the old solver which is currently relied on.
1385        if assumption.has_bound_vars() {
1386            return Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), Certainty::Yes));
1387        }
1388
1389        match assumption.visit_with(&mut FindParamInClause {
1390            ecx: self,
1391            param_env,
1392            universes: ::alloc::vec::Vec::new()vec![],
1393            recursion_depth: 0,
1394        }) {
1395            ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1396            ControlFlow::Break(Ok(certainty)) => {
1397                Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), certainty))
1398            }
1399            ControlFlow::Continue(()) => {
1400                Ok((CandidateSource::ParamEnv(ParamEnvSource::Global), Certainty::Yes))
1401            }
1402        }
1403    }
1404}
1405
1406struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1407    ecx: &'a mut EvalCtxt<'b, D>,
1408    param_env: I::ParamEnv,
1409    universes: Vec<Option<ty::UniverseIndex>>,
1410    recursion_depth: usize,
1411}
1412
1413impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1414where
1415    D: SolverDelegate<Interner = I>,
1416    I: Interner,
1417{
1418    // - `Continue(())`: no generic parameter was found, the type is global
1419    // - `Break(Ok(Certainty::Yes))`: a generic parameter was found, the type is non-global
1420    // - `Break(Ok(Certainty::Maybe(_)))`: the recursion limit reached, assume that the type is non-global
1421    // - `Break(Err(NoSolution))`: normalization failed
1422    type Result = ControlFlow<Result<Certainty, NoSolution>>;
1423
1424    fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1425        self.universes.push(None);
1426        t.super_visit_with(self)?;
1427        self.universes.pop();
1428        ControlFlow::Continue(())
1429    }
1430
1431    fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1432        let ty = self.ecx.replace_bound_vars(ty, &mut self.universes);
1433        let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1434            return ControlFlow::Break(Err(NoSolution));
1435        };
1436
1437        match ty.kind() {
1438            ty::Placeholder(p) => {
1439                if p.universe() == ty::UniverseIndex::ROOT {
1440                    ControlFlow::Break(Ok(Certainty::Yes))
1441                } else {
1442                    ControlFlow::Continue(())
1443                }
1444            }
1445            ty::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1446            _ if ty.has_type_flags(
1447                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1448            ) =>
1449            {
1450                self.recursion_depth += 1;
1451                if self.recursion_depth > self.ecx.cx().recursion_limit() {
1452                    return ControlFlow::Break(Ok(Certainty::Maybe(MaybeInfo {
1453                        cause: MaybeCause::Overflow {
1454                            suggest_increasing_limit: true,
1455                            keep_constraints: false,
1456                        },
1457                        opaque_types_jank: OpaqueTypesJank::AllGood,
1458                        stalled_on_coroutines: StalledOnCoroutines::No,
1459                    })));
1460                }
1461                let result = ty.super_visit_with(self);
1462                self.recursion_depth -= 1;
1463                result
1464            }
1465            _ => ControlFlow::Continue(()),
1466        }
1467    }
1468
1469    fn visit_const(&mut self, ct: I::Const) -> Self::Result {
1470        let ct = self.ecx.replace_bound_vars(ct, &mut self.universes);
1471        let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1472            return ControlFlow::Break(Err(NoSolution));
1473        };
1474
1475        match ct.kind() {
1476            ty::ConstKind::Placeholder(p) => {
1477                if p.universe() == ty::UniverseIndex::ROOT {
1478                    ControlFlow::Break(Ok(Certainty::Yes))
1479                } else {
1480                    ControlFlow::Continue(())
1481                }
1482            }
1483            ty::ConstKind::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1484            _ if ct.has_type_flags(
1485                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1486            ) =>
1487            {
1488                // FIXME(mgca): we should also check the recursion limit here
1489                ct.super_visit_with(self)
1490            }
1491            _ => ControlFlow::Continue(()),
1492        }
1493    }
1494
1495    fn visit_region(&mut self, r: Region<I>) -> Self::Result {
1496        match self.ecx.eager_resolve_region(r).kind() {
1497            ty::ReStatic | ty::ReError(_) | ty::ReBound(..) => ControlFlow::Continue(()),
1498            ty::RePlaceholder(p) => {
1499                if p.universe() == ty::UniverseIndex::ROOT {
1500                    ControlFlow::Break(Ok(Certainty::Yes))
1501                } else {
1502                    ControlFlow::Continue(())
1503                }
1504            }
1505            ty::ReVar(_) => ControlFlow::Break(Ok(Certainty::Yes)),
1506            ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
1507                {
    ::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")
1508            }
1509        }
1510    }
1511}