Skip to main content

rustc_next_trait_solver/solve/
trait_goals.rs

1//! Dealing with trait goals, i.e. `T: Trait<'a, U>`.
2
3use rustc_type_ir::data_structures::IndexSet;
4use rustc_type_ir::fast_reject::DeepRejectCtxt;
5use rustc_type_ir::inherent::*;
6use rustc_type_ir::lang_items::SolverTraitLangItem;
7use rustc_type_ir::solve::{
8    AliasBoundKind, CandidatePreferenceMode, CanonicalResponse, ExternalConstraintsData,
9    IsIdentity, MaybeInfo, NoSolutionOrRerunNonErased, OpaqueTypesJank,
10    QueryResultOrRerunNonErased, RerunNonErased, RerunReason, RerunResultExt, SizedTraitKind,
11};
12use rustc_type_ir::{
13    self as ty, CallerBoundsIterator, ExistentialPredicate, FieldInfo, IncludeSizedImplicitBounds,
14    Interner, MayBeErased, Movability, Region, TraitClause, TraitRef, TypeVisitableExt as _,
15    TypingMode, Unnormalized, Upcast as _, elaborate,
16};
17use tracing::{debug, instrument, trace, warn};
18
19use crate::delegate::SolverDelegate;
20use crate::solve::assembly::structural_traits::{self, AsyncCallableRelevantTypes};
21use crate::solve::assembly::{
22    self, AllowInferenceConstraints, AssembleCandidatesFrom, Candidate, FailedCandidateInfo,
23};
24use crate::solve::inspect::ProbeKind;
25use crate::solve::{
26    BuiltinImplSource, CandidateSource, Certainty, EvalCtxt, Goal, GoalSource, MaybeCause,
27    NoSolution, ParamEnvSource, StalledOnCoroutines, flatten_answer_tree,
28    has_only_region_constraints,
29};
30
31impl<D, I> assembly::GoalKind<D> for TraitClause<I>
32where
33    D: SolverDelegate<Interner = I>,
34    I: Interner,
35{
36    fn self_ty(self) -> I::Ty {
37        self.self_ty()
38    }
39
40    fn trait_ref(self, _: I) -> ty::TraitRef<I> {
41        self.trait_ref
42    }
43
44    fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self {
45        self.with_replaced_self_ty(cx, self_ty)
46    }
47
48    fn trait_def_id(self, _: I) -> I::TraitId {
49        self.def_id()
50    }
51
52    fn consider_additional_alias_assumptions(
53        _ecx: &mut EvalCtxt<'_, D>,
54        _goal: Goal<I, Self>,
55        _alias_ty: ty::AliasTy<I>,
56    ) -> Vec<Candidate<I>> {
57        ::alloc::vec::Vec::new()vec![]
58    }
59
60    fn consider_impl_candidate(
61        ecx: &mut EvalCtxt<'_, D>,
62        goal: Goal<I, TraitClause<I>>,
63        goal_trait_ref: TraitRef<I>,
64        impl_def_id: I::ImplId,
65        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
66    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
67        let cx = ecx.cx();
68
69        match (cx.impl_polarity(impl_def_id), goal.predicate.polarity) {
70            // Impl matches polarity
71            (ty::ImplPolarity::Positive, ty::ClausePolarity::Positive)
72            | (ty::ImplPolarity::Negative, ty::ClausePolarity::Negative) => {}
73
74            // Impl doesn't match polarity
75            (ty::ImplPolarity::Positive, ty::ClausePolarity::Negative)
76            | (ty::ImplPolarity::Negative, ty::ClausePolarity::Positive) => {
77                return Err(NoSolution.into());
78            }
79        }
80
81        if ecx.typing_mode().is_reflection() && !cx.is_fully_generic_for_reflection(impl_def_id) {
82            return Err(NoSolution.into());
83        }
84
85        ecx.probe_trait_candidate(CandidateSource::Impl(impl_def_id)).enter(|ecx| {
86            let impl_args = ecx.fresh_args_for_item(impl_def_id.into());
87            ecx.record_impl_args(impl_args);
88            let impl_trait_ref = cx.impl_trait_ref(impl_def_id);
89            let impl_trait_ref = impl_trait_ref.instantiate(cx, impl_args).skip_norm_wip();
90
91            ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?;
92            let where_clause_bounds = cx
93                .clauses_of(impl_def_id.into())
94                .iter_instantiated(cx, impl_args)
95                .map(Unnormalized::skip_norm_wip)
96                .map(|clause| goal.with(cx, clause));
97            ecx.add_goals(GoalSource::ImplWhereBound, where_clause_bounds)?;
98
99            // We currently elaborate all supertrait outlives obligations from impls.
100            // This can be removed when we actually do coinduction correctly, and prove
101            // all supertrait obligations unconditionally.
102            ecx.add_goals(
103                GoalSource::Misc,
104                cx.impl_super_outlives(impl_def_id)
105                    .iter_instantiated(cx, impl_args)
106                    .map(Unnormalized::skip_norm_wip)
107                    .map(|pred| goal.with(cx, pred)),
108            )?;
109
110            then(ecx)
111        })
112    }
113
114    fn consider_error_guaranteed_candidate(
115        ecx: &mut EvalCtxt<'_, D>,
116        _goal: Goal<I, Self>,
117        _guar: I::ErrorGuaranteed,
118    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
119        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
120            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
121    }
122
123    fn non_fast_rejected_caller_bounds(
124        ecx: &mut EvalCtxt<'_, D>,
125        goal: Goal<I, Self>,
126    ) -> impl Iterator<Item = ty::Binder<I, ty::ClauseKind<I>>> {
127        goal.param_env
128            .caller_bounds()
129            .trait_clauses(ecx.cx())
130            .with_polarity(goal.predicate.polarity)
131            .for_trait(goal.predicate.def_id())
132            .filter(move |trait_clause| {
133                DeepRejectCtxt::relate_rigid_rigid(ecx.cx()).args_may_unify(
134                    goal.predicate.trait_ref.args,
135                    trait_clause.skip_binder().trait_ref.args,
136                )
137            })
138            .iter()
139            .map(|i| i.map_bound(|x| ty::ClauseKind::Trait(x)))
140    }
141
142    fn fast_reject_assumption(
143        ecx: &mut EvalCtxt<'_, D>,
144        goal: Goal<I, Self>,
145        assumption: I::Clause,
146    ) -> Result<(), NoSolution> {
147        if let Some(trait_clause) = assumption.as_trait_clause()
148            && trait_clause.polarity() == goal.predicate.polarity
149            && trait_clause.def_id() == goal.predicate.def_id()
150            && DeepRejectCtxt::relate_rigid_rigid(ecx.cx()).args_may_unify(
151                goal.predicate.trait_ref.args,
152                trait_clause.skip_binder().trait_ref.args,
153            )
154        {
155            Ok(())
156        } else {
157            Err(NoSolution)
158        }
159    }
160
161    fn match_assumption(
162        ecx: &mut EvalCtxt<'_, D>,
163        goal: Goal<I, Self>,
164        assumption: ty::Binder<I, ty::ClauseKind<I>>,
165        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
166    ) -> QueryResultOrRerunNonErased<I> {
167        let trait_clause = assumption
168            .map_bound(|i| match i {
169                ty::ClauseKind::Trait(t) => Some(t),
170                _ => None,
171            })
172            .transpose()
173            .unwrap();
174
175        let assumption_trait_pred = ecx.instantiate_binder_with_infer(trait_clause);
176        ecx.eq(goal.param_env, goal.predicate.trait_ref, assumption_trait_pred.trait_ref)?;
177
178        then(ecx)
179    }
180
181    fn consider_auto_trait_candidate(
182        ecx: &mut EvalCtxt<'_, D>,
183        goal: Goal<I, Self>,
184    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
185        let cx = ecx.cx();
186        if goal.predicate.polarity != ty::ClausePolarity::Positive {
187            return Err(NoSolution.into());
188        }
189
190        // Fast path: when the feature is disabled,
191        // assume all types implement `Move`.
192        //
193        // This will trivially make the addition of
194        // `Move` backward compatible with trait bounds
195        if !cx.features().move_trait()
196            && cx.is_trait_lang_item(goal.predicate.def_id(), SolverTraitLangItem::Move)
197        {
198            return ecx
199                .probe_builtin_trait_candidate(BuiltinImplSource::Trivial)
200                .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes));
201        }
202
203        if let Some(result) = ecx.disqualify_auto_trait_candidate_due_to_possible_impl(goal) {
204            return result;
205        }
206
207        // Only consider auto impls of unsafe traits when there are no unsafe
208        // fields.
209        if cx.trait_is_unsafe(goal.predicate.def_id())
210            && goal.predicate.self_ty().has_unsafe_fields()
211        {
212            return Err(NoSolution.into());
213        }
214
215        // We leak the implemented auto traits of opaques outside of their defining scope.
216        // This depends on `typeck` of the defining scope of that opaque, which may result in
217        // fatal query cycles.
218        //
219        // We only get to this point if we're outside of the defining scope as we'd otherwise
220        // be able to normalize the opaque type. We may also cycle in case `typeck` of a defining
221        // scope relies on the current context, e.g. either because it also leaks auto trait
222        // bounds of opaques defined in the current context or by evaluating the current item.
223        //
224        // To avoid this we don't try to leak auto trait bounds if they can also be proven via
225        // item bounds of the opaque. These bounds are always applicable as auto traits must not
226        // have any generic parameters. They would also get preferred over the impl candidate
227        // when merging candidates anyways.
228        //
229        // See tests/ui/impl-trait/auto-trait-leakage/avoid-query-cycle-via-item-bound.rs.
230        if let ty::Alias(is_rigid, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) =
231            goal.predicate.self_ty().kind()
232        {
233            if true {
    if !(is_rigid == ty::IsRigid::Yes) {
        ::core::panicking::panic("assertion failed: is_rigid == ty::IsRigid::Yes")
    };
};debug_assert!(is_rigid == ty::IsRigid::Yes);
234            return ecx.consider_auto_trait_candidate_for_opaque_ty(goal, def_id, args);
235        }
236
237        // We need to make sure to stall any coroutines we are inferring to avoid query cycles.
238        if let Some(cand) = ecx.try_stall_coroutine(goal.predicate.self_ty()) {
239            return cand;
240        }
241
242        ecx.probe_and_evaluate_goal_for_constituent_tys(
243            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
244            goal,
245            structural_traits::instantiate_constituent_tys_for_auto_trait,
246        )
247    }
248
249    fn consider_trait_alias_candidate(
250        ecx: &mut EvalCtxt<'_, D>,
251        goal: Goal<I, Self>,
252    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
253        if goal.predicate.polarity != ty::ClausePolarity::Positive {
254            return Err(NoSolution.into());
255        }
256
257        let cx = ecx.cx();
258
259        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
260            let nested_obligations = cx
261                .clauses_of(goal.predicate.def_id().into())
262                .iter_instantiated(cx, goal.predicate.trait_ref.args)
263                .map(Unnormalized::skip_norm_wip)
264                .map(|c| goal.with(cx, c));
265            // While you could think of trait aliases to have a single builtin impl
266            // which uses its implied trait bounds as where-clauses, using
267            // `GoalSource::ImplWhereClause` here would be incorrect, as we also
268            // impl them, which means we're "stepping out of the impl constructor"
269            // again. To handle this, we treat these cycles as ambiguous for now.
270            ecx.add_goals(GoalSource::Misc, nested_obligations)?;
271            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
272        })
273    }
274
275    fn consider_builtin_sizedness_candidates(
276        ecx: &mut EvalCtxt<'_, D>,
277        goal: Goal<I, Self>,
278        sizedness: SizedTraitKind,
279    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
280        if goal.predicate.polarity != ty::ClausePolarity::Positive {
281            return Err(NoSolution.into());
282        }
283
284        ecx.probe_and_evaluate_goal_for_constituent_tys(
285            CandidateSource::BuiltinImpl(BuiltinImplSource::Trivial),
286            goal,
287            |ecx, ty| {
288                structural_traits::instantiate_constituent_tys_for_sizedness_trait(
289                    ecx, sizedness, ty,
290                )
291            },
292        )
293    }
294
295    fn consider_builtin_copy_clone_candidate(
296        ecx: &mut EvalCtxt<'_, D>,
297        goal: Goal<I, Self>,
298    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
299        if goal.predicate.polarity != ty::ClausePolarity::Positive {
300            return Err(NoSolution.into());
301        }
302
303        // We need to make sure to stall any coroutines we are inferring to avoid query cycles.
304        if let Some(cand) = ecx.try_stall_coroutine(goal.predicate.self_ty()) {
305            return cand;
306        }
307
308        ecx.probe_and_evaluate_goal_for_constituent_tys(
309            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
310            goal,
311            structural_traits::instantiate_constituent_tys_for_copy_clone_trait,
312        )
313    }
314
315    fn consider_builtin_fn_ptr_trait_candidate(
316        ecx: &mut EvalCtxt<'_, D>,
317        goal: Goal<I, Self>,
318    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
319        let self_ty = goal.predicate.self_ty();
320        match goal.predicate.polarity {
321            // impl FnPtr for FnPtr {}
322            ty::ClausePolarity::Positive => {
323                if self_ty.is_fn_ptr() {
324                    ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
325                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
326                    })
327                } else {
328                    Err(NoSolution.into())
329                }
330            }
331            //  impl !FnPtr for T where T != FnPtr && T is rigid {}
332            ty::ClausePolarity::Negative => {
333                // If a type is rigid and not a fn ptr, then we know for certain
334                // that it does *not* implement `FnPtr`.
335                if !self_ty.is_fn_ptr() && self_ty.is_known_rigid() {
336                    ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
337                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
338                    })
339                } else {
340                    Err(NoSolution.into())
341                }
342            }
343        }
344    }
345
346    fn consider_builtin_fn_static_trait_candidate(
347        ecx: &mut EvalCtxt<'_, D>,
348        goal: Goal<I, Self>,
349    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
350        let self_ty = goal.predicate.self_ty();
351        match goal.predicate.polarity {
352            // impl FnStatic for FnDef {}
353            ty::ClausePolarity::Positive => match self_ty.kind() {
354                ty::FnDef(_, _) => {
355                    ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
356                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
357                    })
358                }
359                _ => Err(NoSolution.into()),
360            },
361            //  impl !FnStatic for T where T != FnDef && T is rigid {}
362            ty::ClausePolarity::Negative => match self_ty.kind() {
363                ty::FnDef(_, _) if self_ty.is_known_rigid() => {
364                    ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
365                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
366                    })
367                }
368                _ => Err(NoSolution.into()),
369            },
370        }
371    }
372
373    fn consider_builtin_fn_trait_candidates(
374        ecx: &mut EvalCtxt<'_, D>,
375        goal: Goal<I, Self>,
376        goal_kind: ty::ClosureKind,
377    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
378        if goal.predicate.polarity != ty::ClausePolarity::Positive {
379            return Err(NoSolution.into());
380        }
381
382        let cx = ecx.cx();
383        let Some(tupled_inputs_and_output) =
384            structural_traits::extract_tupled_inputs_and_output_from_callable(
385                cx,
386                goal.predicate.self_ty(),
387                goal_kind,
388            )?
389        else {
390            return ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS);
391        };
392        let (inputs, output) = ecx.instantiate_binder_with_infer(tupled_inputs_and_output);
393
394        // A built-in `Fn` impl only holds if the output is sized.
395        // (FIXME: technically we only need to check this if the type is a fn ptr...)
396        let output_is_sized_pred =
397            ty::TraitRef::new(cx, cx.require_trait_lang_item(SolverTraitLangItem::Sized), [output]);
398
399        let pred =
400            ty::TraitRef::new(cx, goal.predicate.def_id(), [goal.predicate.self_ty(), inputs])
401                .upcast(cx);
402        Self::probe_and_consider_implied_clause(
403            ecx,
404            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
405            goal,
406            pred,
407            [(GoalSource::ImplWhereBound, goal.with(cx, output_is_sized_pred))],
408        )
409    }
410
411    fn consider_builtin_async_fn_trait_candidates(
412        ecx: &mut EvalCtxt<'_, D>,
413        goal: Goal<I, Self>,
414        goal_kind: ty::ClosureKind,
415    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
416        if goal.predicate.polarity != ty::ClausePolarity::Positive {
417            return Err(NoSolution.into());
418        }
419
420        let cx = ecx.cx();
421        let (tupled_inputs_and_output_and_coroutine, nested_preds) =
422            structural_traits::extract_tupled_inputs_and_output_from_async_callable(
423                cx,
424                goal.predicate.self_ty(),
425                goal_kind,
426                // This region doesn't matter because we're throwing away the coroutine type
427                Region::new_static(cx),
428            )?;
429        let AsyncCallableRelevantTypes {
430            tupled_inputs_ty,
431            output_coroutine_ty,
432            coroutine_return_ty: _,
433        } = ecx.instantiate_binder_with_infer(tupled_inputs_and_output_and_coroutine);
434
435        // A built-in `AsyncFn` impl only holds if the output is sized.
436        // (FIXME: technically we only need to check this if the type is a fn ptr...)
437        let output_is_sized_pred = ty::TraitRef::new(
438            cx,
439            cx.require_trait_lang_item(SolverTraitLangItem::Sized),
440            [output_coroutine_ty],
441        );
442
443        let pred = ty::TraitRef::new(
444            cx,
445            goal.predicate.def_id(),
446            [goal.predicate.self_ty(), tupled_inputs_ty],
447        )
448        .upcast(cx);
449        Self::probe_and_consider_implied_clause(
450            ecx,
451            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
452            goal,
453            pred,
454            [goal.with(cx, output_is_sized_pred)]
455                .into_iter()
456                .chain(nested_preds.into_iter().map(|pred| goal.with(cx, pred)))
457                .map(|goal| (GoalSource::ImplWhereBound, goal)),
458        )
459    }
460
461    fn consider_builtin_async_fn_kind_helper_candidate(
462        ecx: &mut EvalCtxt<'_, D>,
463        goal: Goal<I, Self>,
464    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
465        let [closure_fn_kind_ty, goal_kind_ty] = *goal.predicate.trait_ref.args.as_slice() else {
466            ::core::panicking::panic_default_msg();panic!();
467        };
468
469        let Some(closure_kind) = closure_fn_kind_ty.expect_ty().to_opt_closure_kind() else {
470            // We don't need to worry about the self type being an infer var.
471            return Err(NoSolution.into());
472        };
473        let goal_kind = goal_kind_ty.expect_ty().to_opt_closure_kind().unwrap();
474        if closure_kind.extends(goal_kind) {
475            ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
476                .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
477        } else {
478            Err(NoSolution.into())
479        }
480    }
481
482    /// ```rust, ignore (not valid rust syntax)
483    /// impl Tuple for () {}
484    /// impl Tuple for (T1,) {}
485    /// impl Tuple for (T1, T2) {}
486    /// impl Tuple for (T1, .., Tn) {}
487    /// ```
488    fn consider_builtin_tuple_candidate(
489        ecx: &mut EvalCtxt<'_, D>,
490        goal: Goal<I, Self>,
491    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
492        if goal.predicate.polarity != ty::ClausePolarity::Positive {
493            return Err(NoSolution.into());
494        }
495
496        if let ty::Tuple(..) = goal.predicate.self_ty().kind() {
497            ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
498                .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
499        } else {
500            Err(NoSolution.into())
501        }
502    }
503
504    fn consider_builtin_pointee_candidate(
505        ecx: &mut EvalCtxt<'_, D>,
506        goal: Goal<I, Self>,
507    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
508        if goal.predicate.polarity != ty::ClausePolarity::Positive {
509            return Err(NoSolution.into());
510        }
511
512        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
513            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
514    }
515
516    fn consider_builtin_future_candidate(
517        ecx: &mut EvalCtxt<'_, D>,
518        goal: Goal<I, Self>,
519    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
520        if goal.predicate.polarity != ty::ClausePolarity::Positive {
521            return Err(NoSolution.into());
522        }
523
524        let ty::Coroutine(def_id, _) = goal.predicate.self_ty().kind() else {
525            return Err(NoSolution.into());
526        };
527
528        // Coroutines are not futures unless they come from `async` desugaring
529        let cx = ecx.cx();
530        if !cx.coroutine_is_async(def_id) {
531            return Err(NoSolution.into());
532        }
533
534        // Async coroutine unconditionally implement `Future`
535        // Technically, we need to check that the future output type is Sized,
536        // but that's already proven by the coroutine being WF.
537        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
538            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
539    }
540
541    fn consider_builtin_iterator_candidate(
542        ecx: &mut EvalCtxt<'_, D>,
543        goal: Goal<I, Self>,
544    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
545        if goal.predicate.polarity != ty::ClausePolarity::Positive {
546            return Err(NoSolution.into());
547        }
548
549        let ty::Coroutine(def_id, _) = goal.predicate.self_ty().kind() else {
550            return Err(NoSolution.into());
551        };
552
553        // Coroutines are not iterators unless they come from `gen` desugaring
554        let cx = ecx.cx();
555        if !cx.coroutine_is_gen(def_id) {
556            return Err(NoSolution.into());
557        }
558
559        // Gen coroutines unconditionally implement `Iterator`
560        // Technically, we need to check that the iterator output type is Sized,
561        // but that's already proven by the coroutines being WF.
562        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
563            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
564    }
565
566    fn consider_builtin_fused_iterator_candidate(
567        ecx: &mut EvalCtxt<'_, D>,
568        goal: Goal<I, Self>,
569    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
570        if goal.predicate.polarity != ty::ClausePolarity::Positive {
571            return Err(NoSolution.into());
572        }
573
574        let ty::Coroutine(def_id, _) = goal.predicate.self_ty().kind() else {
575            return Err(NoSolution.into());
576        };
577
578        // Coroutines are not iterators unless they come from `gen` desugaring
579        let cx = ecx.cx();
580        if !cx.coroutine_is_gen(def_id) {
581            return Err(NoSolution.into());
582        }
583
584        // Gen coroutines unconditionally implement `FusedIterator`.
585        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
586            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
587    }
588
589    fn consider_builtin_async_iterator_candidate(
590        ecx: &mut EvalCtxt<'_, D>,
591        goal: Goal<I, Self>,
592    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
593        if goal.predicate.polarity != ty::ClausePolarity::Positive {
594            return Err(NoSolution.into());
595        }
596
597        let ty::Coroutine(def_id, _) = goal.predicate.self_ty().kind() else {
598            return Err(NoSolution.into());
599        };
600
601        // Coroutines are not iterators unless they come from `gen` desugaring
602        let cx = ecx.cx();
603        if !cx.coroutine_is_async_gen(def_id) {
604            return Err(NoSolution.into());
605        }
606
607        // Gen coroutines unconditionally implement `Iterator`
608        // Technically, we need to check that the iterator output type is Sized,
609        // but that's already proven by the coroutines being WF.
610        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
611            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
612    }
613
614    fn consider_builtin_coroutine_candidate(
615        ecx: &mut EvalCtxt<'_, D>,
616        goal: Goal<I, Self>,
617    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
618        if goal.predicate.polarity != ty::ClausePolarity::Positive {
619            return Err(NoSolution.into());
620        }
621
622        let self_ty = goal.predicate.self_ty();
623        let ty::Coroutine(def_id, args) = self_ty.kind() else {
624            return Err(NoSolution.into());
625        };
626
627        // `async`-desugared coroutines do not implement the coroutine trait
628        let cx = ecx.cx();
629        if !cx.is_general_coroutine(def_id) {
630            return Err(NoSolution.into());
631        }
632
633        let coroutine = args.as_coroutine();
634        Self::probe_and_consider_implied_clause(
635            ecx,
636            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
637            goal,
638            ty::TraitRef::new(cx, goal.predicate.def_id(), [self_ty, coroutine.resume_ty()])
639                .upcast(cx),
640            // Technically, we need to check that the coroutine types are Sized,
641            // but that's already proven by the coroutine being WF.
642            [],
643        )
644    }
645
646    fn consider_builtin_discriminant_kind_candidate(
647        ecx: &mut EvalCtxt<'_, D>,
648        goal: Goal<I, Self>,
649    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
650        if goal.predicate.polarity != ty::ClausePolarity::Positive {
651            return Err(NoSolution.into());
652        }
653
654        // `DiscriminantKind` is automatically implemented for every type.
655        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
656            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
657    }
658
659    fn consider_builtin_destruct_candidate(
660        ecx: &mut EvalCtxt<'_, D>,
661        goal: Goal<I, Self>,
662    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
663        if goal.predicate.polarity != ty::ClausePolarity::Positive {
664            return Err(NoSolution.into());
665        }
666
667        // `Destruct` is automatically implemented for every type in
668        // non-const environments.
669        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
670            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
671    }
672
673    fn consider_builtin_transmute_candidate(
674        ecx: &mut EvalCtxt<'_, D>,
675        goal: Goal<I, Self>,
676    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
677        use rustc_type_ir::transmute::Answer;
678
679        if goal.predicate.polarity != ty::ClausePolarity::Positive {
680            return Err(NoSolution.into());
681        }
682
683        // `rustc_transmute` does not have support for type or const params
684        if goal.predicate.has_non_region_placeholders() {
685            return Err(NoSolution.into());
686        }
687
688        // Match the old solver by treating unresolved inference variables as
689        // ambiguous until `rustc_transmute` can compute their layout.
690        if goal.has_non_region_infer() {
691            return ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS);
692        }
693
694        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(
695            |ecx| -> Result<_, NoSolutionOrRerunNonErased> {
696                let assume = ecx.structurally_normalize_const(
697                    goal.param_env,
698                    goal.predicate.trait_ref.args.const_at(2),
699                )?;
700
701                let answer = ecx.is_transmutable(
702                    goal.predicate.trait_ref.args.type_at(0),
703                    goal.predicate.trait_ref.args.type_at(1),
704                    assume,
705                )?;
706
707                let certainty = match answer {
708                    Answer::No(_) => return Err(NoSolution.into()),
709                    Answer::Yes => Certainty::Yes,
710                    Answer::If(cond) => {
711                        let tcx = ecx.cx();
712                        ecx.add_goals(
713                            GoalSource::Misc,
714                            flatten_answer_tree(tcx, goal.predicate, cond)
715                                .into_iter()
716                                .map(|predicate| Goal::new(tcx, goal.param_env, predicate)),
717                        )?;
718
719                        Certainty::Yes
720                    }
721                };
722
723                ecx.evaluate_added_goals_and_make_canonical_response(certainty)
724            },
725        )
726    }
727
728    /// NOTE: This is implemented as a built-in goal and not a set of impls like:
729    ///
730    /// ```rust,ignore (illustrative)
731    /// impl<T> BikeshedGuaranteedNoDrop for T where T: Copy {}
732    /// impl<T> BikeshedGuaranteedNoDrop for ManuallyDrop<T> {}
733    /// ```
734    ///
735    /// because these impls overlap, and I'd rather not build a coherence hack for
736    /// this harmless overlap.
737    ///
738    /// This trait is indirectly exposed on stable, so do *not* extend the set of types that
739    /// implement the trait without FCP!
740    fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
741        ecx: &mut EvalCtxt<'_, D>,
742        goal: Goal<I, Self>,
743    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
744        if goal.predicate.polarity != ty::ClausePolarity::Positive {
745            return Err(NoSolution.into());
746        }
747
748        let cx = ecx.cx();
749        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
750            let ty = goal.predicate.self_ty();
751            match ty.kind() {
752                // `&mut T` and `&T` always implement `BikeshedGuaranteedNoDrop`.
753                ty::Ref(..) => {}
754                // `ManuallyDrop<T>` always implements `BikeshedGuaranteedNoDrop`.
755                ty::Adt(def, _) if def.is_manually_drop() => {}
756                // Arrays and tuples implement `BikeshedGuaranteedNoDrop` only if
757                // their constituent types implement `BikeshedGuaranteedNoDrop`.
758                ty::Tuple(tys) => {
759                    ecx.add_goals(
760                        GoalSource::ImplWhereBound,
761                        tys.iter().map(|elem_ty| {
762                            goal.with(cx, ty::TraitRef::new(cx, goal.predicate.def_id(), [elem_ty]))
763                        }),
764                    )?;
765                }
766                ty::Array(elem_ty, _) => {
767                    ecx.add_goal(
768                        GoalSource::ImplWhereBound,
769                        goal.with(cx, ty::TraitRef::new(cx, goal.predicate.def_id(), [elem_ty])),
770                    )?;
771                }
772
773                // All other types implement `BikeshedGuaranteedNoDrop` only if
774                // they implement `Copy`. We could be smart here and short-circuit
775                // some trivially `Copy`/`!Copy` types, but there's no benefit.
776                ty::FnDef(..)
777                | ty::FnPtr(..)
778                | ty::Error(_)
779                | ty::Uint(_)
780                | ty::Int(_)
781                | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
782                | ty::Bool
783                | ty::Float(_)
784                | ty::Char
785                | ty::RawPtr(..)
786                | ty::Never
787                | ty::Pat(..)
788                | ty::Dynamic(..)
789                | ty::Str
790                | ty::Slice(_)
791                | ty::Foreign(..)
792                | ty::Adt(..)
793                | ty::Alias(..)
794                | ty::Param(_)
795                | ty::Placeholder(..)
796                | ty::Closure(..)
797                | ty::CoroutineClosure(..)
798                | ty::Coroutine(..)
799                | ty::UnsafeBinder(_)
800                | ty::CoroutineWitness(..) => {
801                    ecx.add_goal(
802                        GoalSource::ImplWhereBound,
803                        goal.with(
804                            cx,
805                            ty::TraitRef::new(
806                                cx,
807                                cx.require_trait_lang_item(SolverTraitLangItem::Copy),
808                                [ty],
809                            ),
810                        ),
811                    )?;
812                }
813
814                ty::Bound(..)
815                | ty::Infer(
816                    ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_),
817                ) => {
818                    { ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`", ty)); }panic!("unexpected type `{ty:?}`")
819                }
820
821                // FIXME(scrabsha)
822                ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
823            }
824
825            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
826        })
827    }
828
829    /// ```ignore (builtin impl example)
830    /// trait Trait {
831    ///     fn foo(&self);
832    /// }
833    /// // results in the following builtin impl
834    /// impl<'a, T: Trait + 'a> Unsize<dyn Trait + 'a> for T {}
835    /// ```
836    fn consider_structural_builtin_unsize_candidates(
837        ecx: &mut EvalCtxt<'_, D>,
838        goal: Goal<I, Self>,
839    ) -> Result<Vec<Candidate<I>>, RerunNonErased> {
840        if goal.predicate.polarity != ty::ClausePolarity::Positive {
841            return Ok(::alloc::vec::Vec::new()vec![]);
842        }
843
844        let result = ecx.probe(|_| ProbeKind::UnsizeAssembly).enter(
845            |ecx| -> Result<Vec<Candidate<I>>, NoSolutionOrRerunNonErased> {
846                let a_ty = goal.predicate.self_ty();
847                // We need to normalize the b_ty since it's matched structurally
848                // in the other functions below.
849                let b_ty = ecx.structurally_normalize_ty(
850                    goal.param_env,
851                    goal.predicate.trait_ref.args.type_at(1),
852                )?;
853
854                let goal = goal.with(ecx.cx(), (a_ty, b_ty));
855                match (a_ty.kind(), b_ty.kind()) {
856                    (ty::Infer(ty::TyVar(..)), ..) => {
    ::core::panicking::panic_fmt(format_args!("unexpected infer {0:?} {1:?}",
            a_ty, b_ty));
}panic!("unexpected infer {a_ty:?} {b_ty:?}"),
857
858                    (_, ty::Infer(ty::TyVar(..))) => {
859                        Ok(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS)?]))vec![ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS)?])
860                    }
861
862                    // Trait upcasting, or `dyn Trait + Auto + 'a` -> `dyn Trait + 'b`.
863                    (ty::Dynamic(a_data, a_region), ty::Dynamic(b_data, b_region)) => Ok(ecx
864                        .consider_builtin_dyn_upcast_candidates(
865                            goal, a_data, a_region, b_data, b_region,
866                        )),
867
868                    // `T` -> `dyn Trait` unsizing.
869                    (_, ty::Dynamic(b_region, b_data)) => Ok(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ecx.consider_builtin_unsize_to_dyn_candidate(goal, b_region,
                        b_data)?]))vec![
870                        ecx.consider_builtin_unsize_to_dyn_candidate(goal, b_region, b_data)?,
871                    ]),
872
873                    // `[T; N]` -> `[T]` unsizing
874                    (ty::Array(a_elem_ty, ..), ty::Slice(b_elem_ty)) => {
875                        Ok(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ecx.consider_builtin_array_unsize(goal, a_elem_ty, b_elem_ty)?]))vec![ecx.consider_builtin_array_unsize(goal, a_elem_ty, b_elem_ty)?])
876                    }
877
878                    // `Struct<T>` -> `Struct<U>` where `T: Unsize<U>`
879                    (ty::Adt(a_def, a_args), ty::Adt(b_def, b_args))
880                        if a_def.is_struct() && a_def == b_def =>
881                    {
882                        Ok(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ecx.consider_builtin_struct_unsize(goal, a_def, a_args, b_args)?]))vec![ecx.consider_builtin_struct_unsize(goal, a_def, a_args, b_args)?])
883                    }
884
885                    _ => Err(NoSolution.into()),
886                }
887            },
888        );
889
890        match result.map_err_to_rerun()? {
891            Ok(resp) => Ok(resp),
892            Err(NoSolution) => Ok(::alloc::vec::Vec::new()vec![]),
893        }
894    }
895
896    fn consider_builtin_try_as_dyn_candidate(
897        ecx: &mut EvalCtxt<'_, D>,
898        goal: Goal<I, Self>,
899    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
900        if goal.predicate.polarity != ty::ClausePolarity::Positive {
901            return Err(NoSolution.into());
902        }
903        let cx = ecx.cx();
904
905        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
906            let self_ty = goal.predicate.self_ty();
907            let ty_lifetime = goal.predicate.trait_ref.args.region_at(1);
908            match self_ty.kind() {
909                ty::Dynamic(bounds, lifetime) => {
910                    for bound in bounds.iter() {
911                        match bound.skip_binder() {
912                            ExistentialPredicate::Trait(_) => {}
913                            // FIXME(try_as_dyn): check what kind of projections we can allow
914                            ExistentialPredicate::Projection(_) => return Err(NoSolution.into()),
915                            // Auto traits do not affect lifetimes outside of specialization,
916                            // which is disabled in reflection.
917                            ExistentialPredicate::AutoTrait(_) => {}
918                        }
919                    }
920                    ecx.add_goal(
921                        GoalSource::Misc,
922                        goal.with(cx, ty::OutlivesClause(ty_lifetime, lifetime)),
923                    )?;
924                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
925                }
926
927                ty::Bound(..)
928                | ty::Infer(
929                    ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_),
930                ) => {
931                    {
    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
            self_ty));
}panic!("unexpected type `{self_ty:?}`")
932                }
933
934                _ => Err(NoSolution.into()),
935            }
936        })
937    }
938
939    fn consider_builtin_field_candidate(
940        ecx: &mut EvalCtxt<'_, D>,
941        goal: Goal<I, Self>,
942    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
943        if goal.predicate.polarity != ty::ClausePolarity::Positive {
944            return Err(NoSolution.into());
945        }
946
947        let ty::Adt(def, args) = goal.predicate.self_ty().kind() else {
948            return Err(NoSolution.into());
949        };
950
951        let Some(FieldInfo { base, ty, .. }) = def.field_representing_type_info(ecx.cx(), args)
952        else {
953            return Err(NoSolution.into());
954        };
955
956        match base.kind() {
957            ty::Adt(def, _) if def.is_struct() && !def.is_packed() => {}
958            ty::Adt(..) => return Err(NoSolution.into()),
959            ty::Tuple(..) => {}
960            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
961        }
962
963        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
964            let sized_trait = ecx.cx().require_trait_lang_item(SolverTraitLangItem::Sized);
965
966            // FIXME: add better support for builtin impls of traits that check for the bounds
967            // on the trait definition in std.
968            //
969            // NOTE: these bounds have to be kept in sync with the definition of the `Field`
970            // trait in `library/core/src/field.rs` as well as the old trait solver `fn
971            // assemble_candidates_for_field_trait` in
972            // `compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs`.
973            ecx.add_goal(
974                GoalSource::ImplWhereBound,
975                Goal {
976                    param_env: goal.param_env,
977                    predicate: TraitRef::new(ecx.cx(), sized_trait, [base]).upcast(ecx.cx()),
978                },
979            )?;
980            ecx.add_goal(
981                GoalSource::ImplWhereBound,
982                Goal {
983                    param_env: goal.param_env,
984                    predicate: TraitRef::new(ecx.cx(), sized_trait, [ty]).upcast(ecx.cx()),
985                },
986            )?;
987
988            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
989        })
990    }
991}
992
993impl<D, I> EvalCtxt<'_, D>
994where
995    D: SolverDelegate<Interner = I>,
996    I: Interner,
997{
998    /// Trait upcasting allows for coercions between trait objects:
999    /// ```ignore (builtin impl example)
1000    /// trait Super {}
1001    /// trait Trait: Super {}
1002    /// // results in builtin impls upcasting to a super trait
1003    /// impl<'a, 'b: 'a> Unsize<dyn Super + 'a> for dyn Trait + 'b {}
1004    /// // and impls removing auto trait bounds.
1005    /// impl<'a, 'b: 'a> Unsize<dyn Trait + 'a> for dyn Trait + Send + 'b {}
1006    /// ```
1007    fn consider_builtin_dyn_upcast_candidates(
1008        &mut self,
1009        goal: Goal<I, (I::Ty, I::Ty)>,
1010        a_data: I::BoundExistentialPredicates,
1011        a_region: Region<I>,
1012        b_data: I::BoundExistentialPredicates,
1013        b_region: Region<I>,
1014    ) -> Vec<Candidate<I>> {
1015        let cx = self.cx();
1016        let Goal { predicate: (a_ty, _b_ty), .. } = goal;
1017
1018        let mut responses = ::alloc::vec::Vec::new()vec![];
1019        // If the principal def ids match (or are both none), then we're not doing
1020        // trait upcasting. We're just removing auto traits (or shortening the lifetime).
1021        let b_principal_def_id = b_data.principal_def_id();
1022        if a_data.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
1023            responses.extend(self.consider_builtin_upcast_to_principal(
1024                goal,
1025                CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
1026                a_data,
1027                a_region,
1028                b_data,
1029                b_region,
1030                a_data.principal(),
1031            ));
1032        } else if let Some(a_principal) = a_data.principal() {
1033            for (idx, new_a_principal) in
1034                elaborate::supertraits(self.cx(), a_principal.with_self_ty(cx, a_ty))
1035                    .enumerate()
1036                    .skip(1)
1037            {
1038                responses.extend(self.consider_builtin_upcast_to_principal(
1039                    goal,
1040                    CandidateSource::BuiltinImpl(BuiltinImplSource::TraitUpcasting(idx)),
1041                    a_data,
1042                    a_region,
1043                    b_data,
1044                    b_region,
1045                    Some(new_a_principal.skip_norm_wip().map_bound(|trait_ref| {
1046                        ty::ExistentialTraitRef::erase_self_ty(cx, trait_ref)
1047                    })),
1048                ));
1049            }
1050        }
1051
1052        responses
1053    }
1054
1055    fn consider_builtin_unsize_to_dyn_candidate(
1056        &mut self,
1057        goal: Goal<I, (I::Ty, I::Ty)>,
1058        b_data: I::BoundExistentialPredicates,
1059        b_region: Region<I>,
1060    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1061        let cx = self.cx();
1062        let Goal { predicate: (a_ty, _), .. } = goal;
1063
1064        // Can only unsize to an dyn-compatible trait.
1065        if b_data.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
1066            return Err(NoSolution.into());
1067        }
1068
1069        self.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1070            // Check that the type implements all of the predicates of the trait object.
1071            // (i.e. the principal, all of the associated types match, and any auto traits)
1072            ecx.add_goals(
1073                GoalSource::ImplWhereBound,
1074                b_data.iter().map(|pred| goal.with(cx, pred.with_self_ty(cx, a_ty))),
1075            )?;
1076
1077            // The type must be `Sized` to be unsized.
1078            ecx.add_goal(
1079                GoalSource::ImplWhereBound,
1080                goal.with(
1081                    cx,
1082                    ty::TraitRef::new(
1083                        cx,
1084                        cx.require_trait_lang_item(SolverTraitLangItem::Sized),
1085                        [a_ty],
1086                    ),
1087                ),
1088            )?;
1089
1090            // The type must outlive the lifetime of the `dyn` we're unsizing into.
1091            ecx.add_goal(GoalSource::Misc, goal.with(cx, ty::OutlivesClause(a_ty, b_region)))?;
1092            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1093        })
1094    }
1095
1096    fn consider_builtin_upcast_to_principal(
1097        &mut self,
1098        goal: Goal<I, (I::Ty, I::Ty)>,
1099        source: CandidateSource<I>,
1100        a_data: I::BoundExistentialPredicates,
1101        a_region: Region<I>,
1102        b_data: I::BoundExistentialPredicates,
1103        b_region: Region<I>,
1104        upcast_principal: Option<ty::Binder<I, ty::ExistentialTraitRef<I>>>,
1105    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1106        let param_env = goal.param_env;
1107
1108        // We may upcast to auto traits that are either explicitly listed in
1109        // the object type's bounds, or implied by the principal trait ref's
1110        // supertraits.
1111        let a_auto_traits: IndexSet<I::TraitId> = a_data
1112            .auto_traits()
1113            .into_iter()
1114            .chain(a_data.principal_def_id().into_iter().flat_map(|principal_def_id| {
1115                self.cx()
1116                    .supertrait_def_ids(principal_def_id)
1117                    .filter(|def_id| self.cx().trait_is_auto(*def_id))
1118            }))
1119            .collect();
1120
1121        // More than one projection in a_ty's bounds may match the projection
1122        // in b_ty's bound. Use this to first determine *which* apply without
1123        // having any inference side-effects. We process obligations because
1124        // unification may initially succeed due to deferred projection equality.
1125        let projection_may_match =
1126            |ecx: &mut EvalCtxt<'_, D>,
1127             source_projection: ty::Binder<I, ty::ExistentialProjection<I>>,
1128             target_projection: ty::Binder<I, ty::ExistentialProjection<I>>|
1129             -> Result<bool, RerunNonErased> {
1130                if source_projection.item_def_id() != target_projection.item_def_id() {
1131                    return Ok(false);
1132                }
1133                match ecx.probe(|_| ProbeKind::ProjectionCompatibility).enter(|ecx| {
1134                    let target_projection = ecx.deeply_resolve_ignoring_regions(target_projection);
1135                    ecx.enter_forall_with_assumptions(
1136                        target_projection,
1137                        param_env,
1138                        |ecx, target_projection| {
1139                            let source_projection =
1140                                ecx.instantiate_binder_with_infer(source_projection);
1141                            ecx.eq(param_env, source_projection, target_projection)?;
1142                            ecx.try_evaluate_added_goals()
1143                        },
1144                    )
1145                }) {
1146                    Ok(_) => Ok(true),
1147                    Err(NoSolutionOrRerunNonErased::NoSolution(_)) => Ok(false),
1148                    Err(NoSolutionOrRerunNonErased::RerunNonErased(rerun)) => Err(rerun),
1149                }
1150            };
1151
1152        self.probe_trait_candidate(source).enter(|ecx| {
1153            for bound in b_data.iter() {
1154                match bound.skip_binder() {
1155                    // Check that a's supertrait (upcast_principal) is compatible
1156                    // with the target (b_ty).
1157                    ty::ExistentialPredicate::Trait(target_principal) => {
1158                        let source_principal = upcast_principal.unwrap();
1159                        let target_principal = bound.rebind(target_principal);
1160                        // We might unify infer vars in previous iterations.
1161                        let target_principal =
1162                            ecx.deeply_resolve_ignoring_regions(target_principal);
1163                        ecx.enter_forall_with_assumptions(
1164                            target_principal,
1165                            param_env,
1166                            |ecx, target_principal| {
1167                                let source_principal =
1168                                    ecx.instantiate_binder_with_infer(source_principal);
1169                                ecx.eq(param_env, source_principal, target_principal)?;
1170                                ecx.try_evaluate_added_goals()
1171                            },
1172                        )?;
1173                    }
1174                    // Check that b_ty's projection is satisfied by exactly one of
1175                    // a_ty's projections. First, we look through the list to see if
1176                    // any match. If not, error. Then, if *more* than one matches, we
1177                    // return ambiguity. Otherwise, if exactly one matches, equate
1178                    // it with b_ty's projection.
1179                    ty::ExistentialPredicate::Projection(target_projection) => {
1180                        let target_projection = bound.rebind(target_projection);
1181                        let mut matching_projection = None;
1182                        for source_projection in a_data.projection_bounds() {
1183                            if projection_may_match(ecx, source_projection, target_projection)? {
1184                                if matching_projection.is_some() {
1185                                    return ecx.evaluate_added_goals_and_make_canonical_response(
1186                                        Certainty::AMBIGUOUS,
1187                                    );
1188                                }
1189                                matching_projection = Some(source_projection);
1190                            }
1191                        }
1192                        let Some(matching) = matching_projection else {
1193                            return Err(NoSolution.into());
1194                        };
1195
1196                        // We might unify infer vars in previous iterations.
1197                        let target_projection =
1198                            ecx.deeply_resolve_ignoring_regions(target_projection);
1199                        ecx.enter_forall_with_assumptions(
1200                            target_projection,
1201                            param_env,
1202                            |ecx, target_projection| {
1203                                let source_projection = ecx.instantiate_binder_with_infer(matching);
1204                                ecx.eq(param_env, source_projection, target_projection)?;
1205                                ecx.try_evaluate_added_goals()
1206                            },
1207                        )?;
1208                    }
1209                    // Check that b_ty's auto traits are present in a_ty's bounds.
1210                    ty::ExistentialPredicate::AutoTrait(def_id) => {
1211                        if !a_auto_traits.contains(&def_id) {
1212                            return Err(NoSolution.into());
1213                        }
1214                    }
1215                }
1216            }
1217
1218            // Also require that a_ty's lifetime outlives b_ty's lifetime.
1219            ecx.add_goal(
1220                GoalSource::ImplWhereBound,
1221                Goal::new(ecx.cx(), param_env, ty::OutlivesClause(a_region, b_region)),
1222            )?;
1223
1224            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1225        })
1226    }
1227
1228    /// We have the following builtin impls for arrays:
1229    /// ```ignore (builtin impl example)
1230    /// impl<T: ?Sized, const N: usize> Unsize<[T]> for [T; N] {}
1231    /// ```
1232    /// While the impl itself could theoretically not be builtin,
1233    /// the actual unsizing behavior is builtin. Its also easier to
1234    /// make all impls of `Unsize` builtin as we're able to use
1235    /// `#[rustc_deny_explicit_impl]` in this case.
1236    fn consider_builtin_array_unsize(
1237        &mut self,
1238        goal: Goal<I, (I::Ty, I::Ty)>,
1239        a_elem_ty: I::Ty,
1240        b_elem_ty: I::Ty,
1241    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1242        self.eq(goal.param_env, a_elem_ty, b_elem_ty)?;
1243        self.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
1244            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
1245    }
1246
1247    /// We generate a builtin `Unsize` impls for structs with generic parameters only
1248    /// mentioned by the last field.
1249    /// ```ignore (builtin impl example)
1250    /// struct Foo<T, U: ?Sized> {
1251    ///     sized_field: Vec<T>,
1252    ///     unsizable: Box<U>,
1253    /// }
1254    /// // results in the following builtin impl
1255    /// impl<T: ?Sized, U: ?Sized, V: ?Sized> Unsize<Foo<T, V>> for Foo<T, U>
1256    /// where
1257    ///     Box<U>: Unsize<Box<V>>,
1258    /// {}
1259    /// ```
1260    fn consider_builtin_struct_unsize(
1261        &mut self,
1262        goal: Goal<I, (I::Ty, I::Ty)>,
1263        def: I::AdtDef,
1264        a_args: I::GenericArgs,
1265        b_args: I::GenericArgs,
1266    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1267        let cx = self.cx();
1268        let Goal { predicate: (_a_ty, b_ty), .. } = goal;
1269
1270        let unsizing_params = cx.unsizing_params_for_adt(def.def_id());
1271        // We must be unsizing some type parameters. This also implies
1272        // that the struct has a tail field.
1273        if unsizing_params.is_empty() {
1274            return Err(NoSolution.into());
1275        }
1276
1277        let tail_field_ty = def.struct_tail_ty(cx).unwrap();
1278
1279        let a_tail_ty = tail_field_ty.instantiate(cx, a_args).skip_norm_wip();
1280        let b_tail_ty = tail_field_ty.instantiate(cx, b_args).skip_norm_wip();
1281
1282        // Instantiate just the unsizing params from B into A. The type after
1283        // this instantiation must be equal to B. This is so we don't unsize
1284        // unrelated type parameters.
1285        let new_a_args = cx.mk_args_from_iter(a_args.iter().enumerate().map(|(i, a)| {
1286            if unsizing_params.contains(i as u32) { b_args.get(i).unwrap() } else { a }
1287        }));
1288        let unsized_a_ty = Ty::new_adt(cx, def, new_a_args);
1289
1290        // Finally, we require that `TailA: Unsize<TailB>` for the tail field
1291        // types.
1292        self.eq(goal.param_env, unsized_a_ty, b_ty)?;
1293        self.add_goal(
1294            GoalSource::ImplWhereBound,
1295            goal.with(
1296                cx,
1297                ty::TraitRef::new(
1298                    cx,
1299                    cx.require_trait_lang_item(SolverTraitLangItem::Unsize),
1300                    [a_tail_ty, b_tail_ty],
1301                ),
1302            ),
1303        )?;
1304        self.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
1305            .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))
1306    }
1307
1308    fn consider_auto_trait_candidate_for_opaque_ty(
1309        &mut self,
1310        goal: Goal<I, TraitClause<I>>,
1311        def_id: I::OpaqueTyId,
1312        args: I::GenericArgs,
1313    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1314        let cx = self.cx();
1315        let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1316
1317        for item_bound in cx.item_self_bounds(def_id.into()).skip_binder() {
1318            if item_bound.as_trait_clause().is_some_and(|b| b.def_id() == goal.predicate.def_id()) {
1319                return Err(NoSolution.into());
1320            }
1321        }
1322
1323        let candidate = self.probe_trait_candidate(source).enter(|ecx| {
1324            let hidden_ty = cx.type_of(def_id.into()).instantiate(cx, args).skip_norm_wip();
1325            ecx.add_goal(
1326                GoalSource::ImplWhereBound,
1327                goal.with(cx, goal.predicate.with_replaced_self_ty(cx, hidden_ty)),
1328            )?;
1329            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1330        })?;
1331
1332        // Proving an auto trait for the hidden type must not constrain inference
1333        // variables, as that would leak the hidden type itself.
1334        if candidate.result.value.var_values_is_identity == IsIdentity::No {
1335            return self.forced_ambiguity(MaybeInfo::AMBIGUOUS);
1336        }
1337
1338        let ExternalConstraintsData {
1339            region_constraints: _,
1340            ref opaque_types,
1341            ref normalization_nested_goals,
1342        } = *candidate.result.value.external_constraints;
1343        if true {
    if !normalization_nested_goals.is_empty() {
        ::core::panicking::panic("assertion failed: normalization_nested_goals.is_empty()")
    };
};debug_assert!(normalization_nested_goals.is_empty());
1344
1345        // New defining uses may leak an opaque's hidden type into the caller's
1346        // inference state. This is safe after typeck, where hidden types are already
1347        // fixed and only regions are inferred, but not during typeck while hidden
1348        // types may still contain inference variables.
1349        if !opaque_types.is_empty() {
1350            let typing_mode = self.typing_mode();
1351
1352            match typing_mode {
1353                // We're inferring regions of opaque types, but
1354                // the type itself is already fully known, no way
1355                // to leak the hidden type.
1356                TypingMode::PostTypeckThroughBorrowck { .. } => {}
1357                // We're inferring the hidden type of opaques, could
1358                // leak types through it.
1359                TypingMode::Typeck { .. } => {
1360                    return self.forced_ambiguity(MaybeInfo::AMBIGUOUS);
1361                }
1362                // we never add new uses to the opaque type storage
1363                TypingMode::Coherence
1364                | TypingMode::PostBorrowck { .. }
1365                | TypingMode::Reflection
1366                | TypingMode::PostAnalysis
1367                | TypingMode::Codegen
1368                | TypingMode::ErasedNotCoherence(MayBeErased) => {
1369                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("we never add new uses to opaque types in typing mode {0:?}",
                typing_mode)));
};unreachable!(
1370                        "we never add new uses to opaque types in typing mode {typing_mode:?}"
1371                    );
1372                }
1373            }
1374        }
1375
1376        Ok(candidate)
1377    }
1378
1379    // Return `Some` if there is an impl (built-in or user provided) that may
1380    // hold for the self type of the goal, which for coherence and soundness
1381    // purposes must disqualify the built-in auto impl assembled by considering
1382    // the type's constituent types.
1383    fn disqualify_auto_trait_candidate_due_to_possible_impl(
1384        &mut self,
1385        goal: Goal<I, TraitClause<I>>,
1386    ) -> Option<Result<Candidate<I>, NoSolutionOrRerunNonErased>> {
1387        let self_ty = goal.predicate.self_ty();
1388        let check_impls = || {
1389            let mut disqualifying_impl = None;
1390            self.cx().for_each_relevant_impl(goal.predicate.trait_ref, |impl_def_id| {
1391                disqualifying_impl = Some(impl_def_id);
1392            });
1393            if let Some(def_id) = disqualifying_impl {
1394                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs:1394",
                        "rustc_next_trait_solver::solve::trait_goals",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs"),
                        ::tracing_core::__macro_support::Option::Some(1394u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::trait_goals"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("def_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("def_id");
                                            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::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("disqualified auto-trait implementation")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(?def_id, ?goal, "disqualified auto-trait implementation");
1395                // No need to actually consider the candidate here,
1396                // since we do that in `consider_impl_candidate`.
1397                return Some(Err(NoSolution.into()));
1398            } else {
1399                None
1400            }
1401        };
1402
1403        match self_ty.kind() {
1404            // Stall int and float vars until they are resolved to a concrete
1405            // numerical type. That's because the check for impls below treats
1406            // int vars as matching any impl. Even if we filtered such impls,
1407            // we probably don't want to treat an `impl !AutoTrait for i32` as
1408            // disqualifying the built-in auto impl for `i64: AutoTrait` either.
1409            ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
1410                Some(self.forced_ambiguity(MaybeInfo::AMBIGUOUS))
1411            }
1412
1413            // Backward compatibility for default auto traits.
1414            // Test: ui/traits/default_auto_traits/extern-types.rs
1415            ty::Foreign(..)
1416                if self
1417                    .cx()
1418                    .is_implicit_trait(goal.predicate.def_id(), IncludeSizedImplicitBounds::No) =>
1419            {
1420                check_impls()
1421            }
1422
1423            // These types cannot be structurally decomposed into constituent
1424            // types, and therefore have no built-in auto impl.
1425            ty::Dynamic(..)
1426            | ty::Param(..)
1427            | ty::Foreign(..)
1428            | ty::Alias(
1429                ty::IsRigid::Yes,
1430                ty::AliasTy {
1431                    kind: ty::Projection { .. } | ty::Free { .. } | ty::Inherent { .. },
1432                    ..
1433                },
1434            )
1435            | ty::Placeholder(..) => Some(Err(NoSolution.into())),
1436
1437            // Coroutines have one special built-in candidate, `Unpin`, which
1438            // takes precedence over the structural auto trait candidate being
1439            // assembled.
1440            ty::Coroutine(def_id, _)
1441                if self
1442                    .cx()
1443                    .is_trait_lang_item(goal.predicate.def_id(), SolverTraitLangItem::Unpin) =>
1444            {
1445                match self.cx().coroutine_movability(def_id) {
1446                    Movability::Static => Some(Err(NoSolution.into())),
1447                    Movability::Movable => Some(
1448                        self.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1449                            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1450                        }),
1451                    ),
1452                }
1453            }
1454
1455            // If we still have an alias here, it must be rigid. For opaques, it's always
1456            // okay to consider auto traits because that'll reveal its hidden type. For
1457            // non-opaque aliases, we will not assemble any candidates since there's no way
1458            // to further look into its type.
1459            ty::Alias(ty::IsRigid::Yes, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => None,
1460
1461            // For rigid types, any possible implementation that could apply to
1462            // the type (even if after unification and processing nested goals
1463            // it does not hold) will disqualify the built-in auto impl.
1464            //
1465            // We've originally had a more permissive check here which resulted
1466            // in unsoundness, see #84857.
1467            ty::Bool
1468            | ty::Char
1469            | ty::Int(_)
1470            | ty::Uint(_)
1471            | ty::Float(_)
1472            | ty::Str
1473            | ty::Array(_, _)
1474            | ty::Pat(_, _)
1475            | ty::Slice(_)
1476            | ty::RawPtr(_, _)
1477            | ty::Ref(_, _, _)
1478            | ty::FnDef(_, _)
1479            | ty::FnPtr(..)
1480            | ty::Closure(..)
1481            | ty::CoroutineClosure(..)
1482            | ty::Coroutine(_, _)
1483            | ty::CoroutineWitness(..)
1484            | ty::Never
1485            | ty::Tuple(_)
1486            | ty::Adt(_, _)
1487            | ty::UnsafeBinder(_) => check_impls(),
1488            ty::Error(_) => None,
1489
1490            ty::Infer(_) | ty::Alias(ty::IsRigid::No, _) | ty::Bound(_, _) => {
1491                {
    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
            self_ty));
}panic!("unexpected type `{self_ty:?}`")
1492            }
1493
1494            // FIXME(scrabsha)
1495            ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
1496        }
1497    }
1498
1499    /// Convenience function for traits that are structural, i.e. that only
1500    /// have nested subgoals that only change the self type. Unlike other
1501    /// evaluate-like helpers, this does a probe, so it doesn't need to be
1502    /// wrapped in one.
1503    fn probe_and_evaluate_goal_for_constituent_tys(
1504        &mut self,
1505        source: CandidateSource<I>,
1506        goal: Goal<I, TraitClause<I>>,
1507        constituent_tys: impl Fn(
1508            &EvalCtxt<'_, D>,
1509            I::Ty,
1510        ) -> Result<ty::Binder<I, Vec<I::Ty>>, NoSolution>,
1511    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1512        self.probe_trait_candidate(source).enter(|ecx| {
1513            let goals = ecx.enter_forall_with_assumptions(
1514                constituent_tys(ecx, goal.predicate.self_ty())?,
1515                goal.param_env,
1516                |ecx, tys| {
1517                    tys.into_iter()
1518                        .map(|ty| {
1519                            goal.with(ecx.cx(), goal.predicate.with_replaced_self_ty(ecx.cx(), ty))
1520                        })
1521                        .collect::<Vec<_>>()
1522                },
1523            );
1524            ecx.add_goals(GoalSource::ImplWhereBound, goals)?;
1525            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1526        })
1527    }
1528}
1529
1530/// How we've proven this trait goal.
1531///
1532/// This is used by `SelectAssocCandidate` goals to only normalize
1533/// by using the same 'kind of candidate' we've used to prove
1534/// its corresponding trait goal. Most notably, we do not
1535/// normalize by using an impl if the trait goal has been
1536/// proven via a `ParamEnv` candidate.
1537///
1538/// This is necessary to avoid unnecessary region constraints,
1539/// see trait-system-refactor-initiative#125 for more details.
1540#[derive(#[automatically_derived]impl ::core::fmt::Debug for TraitGoalProvenVia {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                TraitGoalProvenVia::Misc => "Misc",
                TraitGoalProvenVia::ParamEnv => "ParamEnv",
                TraitGoalProvenVia::AliasBound => "AliasBound",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TraitGoalProvenVia {
}
#[automatically_derived]impl ::core::clone::Clone for TraitGoalProvenVia {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for TraitGoalProvenVia { }Copy)]
1541pub(super) enum TraitGoalProvenVia {
1542    /// We've proven the trait goal by something which is
1543    /// is not a non-global where-bound or an alias-bound.
1544    ///
1545    /// This means we don't disable any candidates during
1546    /// normalization.
1547    Misc,
1548    ParamEnv,
1549    AliasBound,
1550}
1551
1552impl<D, I> EvalCtxt<'_, D>
1553where
1554    D: SolverDelegate<Interner = I>,
1555    I: Interner,
1556{
1557    /// FIXME(#57893): For backwards compatibility with the old trait solver implementation,
1558    /// we need to handle overlap between builtin and user-written impls for trait objects.
1559    ///
1560    /// This overlap is unsound in general and something which we intend to fix separately.
1561    /// To avoid blocking the stabilization of the trait solver, we add this hack to avoid
1562    /// breakage in cases which are *mostly fine*â„¢. Importantly, this preference is strictly
1563    /// weaker than the old behavior.
1564    ///
1565    /// We only prefer builtin over user-written impls if there are no inference constraints.
1566    /// Importantly, we also only prefer the builtin impls for trait goals, and not during
1567    /// normalization. This means the only case where this special-case results in exploitable
1568    /// unsoundness should be lifetime dependent user-written impls.
1569    pub(super) fn unsound_prefer_builtin_dyn_impl(&mut self, candidates: &mut Vec<Candidate<I>>) {
1570        if self.typing_mode().is_coherence() {
1571            return;
1572        }
1573
1574        if candidates
1575            .iter()
1576            .find(|c| {
1577                #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::BuiltinImpl(BuiltinImplSource::Object(_)) => true,
    _ => false,
}matches!(c.source, CandidateSource::BuiltinImpl(BuiltinImplSource::Object(_)))
1578            })
1579            .is_some_and(|c| has_only_region_constraints(c.result))
1580        {
1581            candidates.retain(|c| {
1582                if #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::Impl(_) => true,
    _ => false,
}matches!(c.source, CandidateSource::Impl(_)) {
1583                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs:1583",
                        "rustc_next_trait_solver::solve::trait_goals",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs"),
                        ::tracing_core::__macro_support::Option::Some(1583u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::trait_goals"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("c")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("c");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unsoundly dropping impl in favor of builtin dyn-candidate")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&c)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?c, "unsoundly dropping impl in favor of builtin dyn-candidate");
1584                    false
1585                } else {
1586                    true
1587                }
1588            });
1589        }
1590    }
1591
1592    /// Like `try_merge_candidates`, but returns `None` if there are multiple user-written
1593    /// impls, or a user-written impl and a builtin impl, in which case we bail with ambiguity.
1594    ///
1595    /// Candidates with equal responses can still come from conflicting impls, ex - two
1596    /// overlapping impls which both apply due to impossible where-clauses. We don't want
1597    /// to merge these. Multiple builtin impls are still merged as usual. This is not
1598    /// done for marker traits, as their impls are allowed to overlap.
1599    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("try_merge_impl_candidates",
                                "rustc_next_trait_solver::solve::trait_goals",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs"),
                                ::tracing_core::__macro_support::Option::Some(1599u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::trait_goals"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("trait_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("trait_def_id");
                                                    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::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
                                                        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();
}
#[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:
                                Option<CanonicalResponse<I>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let is_marker = self.cx().trait_is_marker(trait_def_id);
                        let all_builtin =
                            candidates.iter().all(|candidate|
                                    #[allow(non_exhaustive_omitted_patterns)] match candidate.source
                                        {
                                        CandidateSource::BuiltinImpl(_) => true,
                                        _ => false,
                                    });
                        if is_marker || all_builtin {
                            self.try_merge_candidates(candidates)
                        } else if candidates.len() > 1 {
                            None
                        } else {
                            candidates.first().map(|candidate| candidate.result)
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs:1599",
                        "rustc_next_trait_solver::solve::trait_goals",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs"),
                        ::tracing_core::__macro_support::Option::Some(1599u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::trait_goals"),
                        ::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::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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 = "trace", skip(self), ret)]
1600    fn try_merge_impl_candidates(
1601        &mut self,
1602        trait_def_id: I::TraitId,
1603        candidates: &[Candidate<I>],
1604    ) -> Option<CanonicalResponse<I>> {
1605        let is_marker = self.cx().trait_is_marker(trait_def_id);
1606        let all_builtin = candidates
1607            .iter()
1608            .all(|candidate| matches!(candidate.source, CandidateSource::BuiltinImpl(_)));
1609
1610        if is_marker || all_builtin {
1611            self.try_merge_candidates(candidates)
1612        } else if candidates.len() > 1 {
1613            None
1614        } else {
1615            candidates.first().map(|candidate| candidate.result)
1616        }
1617    }
1618
1619    fn merge_candidates_or_bail_with_ambiguity(
1620        &mut self,
1621        candidates: &[Candidate<I>],
1622        proven_via: TraitGoalProvenVia,
1623    ) -> (CanonicalResponse<I>, Option<TraitGoalProvenVia>) {
1624        if let Some(response) = self.try_merge_candidates(candidates) {
1625            (response, Some(proven_via))
1626        } else {
1627            (self.bail_with_ambiguity(candidates), None)
1628        }
1629    }
1630
1631    fn merge_impl_candidates_or_bail_with_ambiguity(
1632        &mut self,
1633        trait_def_id: I::TraitId,
1634        candidates: &[Candidate<I>],
1635    ) -> (CanonicalResponse<I>, Option<TraitGoalProvenVia>) {
1636        if true {
    if !candidates.iter().all(|c|
                    #[allow(non_exhaustive_omitted_patterns)] match c.source {
                        CandidateSource::Impl(_) | CandidateSource::BuiltinImpl(_)
                            => true,
                        _ => false,
                    }) {
        ::core::panicking::panic("assertion failed: candidates.iter().all(|c|\n        matches!(c.source, CandidateSource::Impl(_) |\n            CandidateSource::BuiltinImpl(_)))")
    };
};debug_assert!(candidates.iter().all(|c| matches!(
1637            c.source,
1638            CandidateSource::Impl(_) | CandidateSource::BuiltinImpl(_)
1639        )));
1640        match self.try_merge_impl_candidates(trait_def_id, candidates) {
1641            Some(response) => (response, Some(TraitGoalProvenVia::Misc)),
1642            None => (self.bail_with_ambiguity(candidates), None),
1643        }
1644    }
1645
1646    {}
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("merge_trait_candidates",
                                "rustc_next_trait_solver::solve::trait_goals",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs"),
                                ::tracing_core::__macro_support::Option::Some(1646u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::trait_goals"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("trait_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("trait_def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("candidates")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("candidates");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("failed_candidate_info")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("failed_candidate_info");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&failed_candidate_info)
                                                        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:
                                Result<(CanonicalResponse<I>, Option<TraitGoalProvenVia>),
                                NoSolution> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if candidates.is_empty() { return Err(NoSolution); }
                        let candidate_preference_mode =
                            CandidatePreferenceMode::compute(self.cx(), trait_def_id);
                        if self.typing_mode().is_coherence() {
                            return Ok(match self.try_merge_impl_candidates(trait_def_id,
                                            &candidates) {
                                        Some(response) =>
                                            (response, Some(TraitGoalProvenVia::Misc)),
                                        None => (self.bail_with_ambiguity(&candidates), None),
                                    });
                        }
                        let mut trivial_builtin_impls =
                            candidates.iter().filter(|c|
                                    {

                                        #[allow(non_exhaustive_omitted_patterns)]
                                        match c.source {
                                            CandidateSource::BuiltinImpl(BuiltinImplSource::Trivial) =>
                                                true,
                                            _ => false,
                                        }
                                    });
                        if let Some(candidate) = trivial_builtin_impls.next() {
                            if !trivial_builtin_impls.next().is_none() {
                                ::core::panicking::panic("assertion failed: trivial_builtin_impls.next().is_none()")
                            };
                            return Ok((candidate.result,
                                        Some(TraitGoalProvenVia::Misc)));
                        }
                        if #[allow(non_exhaustive_omitted_patterns)] match candidate_preference_mode
                                    {
                                    CandidatePreferenceMode::Marker => true,
                                    _ => false,
                                } &&
                                candidates.iter().any(|c|
                                        {

                                            #[allow(non_exhaustive_omitted_patterns)]
                                            match c.source {
                                                CandidateSource::AliasBound(AliasBoundKind::SelfBounds) =>
                                                    true,
                                                _ => false,
                                            }
                                        }) {
                            let alias_bounds: Vec<_> =
                                candidates.extract_if(..,
                                        |c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::AliasBound(..) => true,
                                                _ => false,
                                            }).collect();
                            candidates.into_iter().for_each(|c|
                                    self.ignore_candidate_head_usages(c.head_usages));
                            return Ok(self.merge_candidates_or_bail_with_ambiguity(&alias_bounds,
                                        TraitGoalProvenVia::AliasBound));
                        }
                        let has_non_global_where_bounds =
                            candidates.iter().any(|c|
                                    #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                        CandidateSource::ParamEnv(ParamEnvSource::NonGlobal) =>
                                            true,
                                        _ => false,
                                    });
                        if has_non_global_where_bounds {
                            let where_bounds: Vec<_> =
                                candidates.extract_if(..,
                                        |c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            }).collect();
                            candidates.into_iter().for_each(|c|
                                    self.ignore_candidate_head_usages(c.head_usages));
                            let Some(response) =
                                self.try_merge_candidates(&where_bounds) else {
                                    return Ok((self.bail_with_ambiguity(&where_bounds), None));
                                };
                            return Ok((response, Some(TraitGoalProvenVia::ParamEnv)));
                        }
                        if candidates.iter().any(|c|
                                    #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                        CandidateSource::AliasBound(_) => true,
                                        _ => false,
                                    }) {
                            let alias_bounds: Vec<_> =
                                candidates.extract_if(..,
                                        |c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::AliasBound(_) => true,
                                                _ => false,
                                            }).collect();
                            candidates.into_iter().for_each(|c|
                                    self.ignore_candidate_head_usages(c.head_usages));
                            return Ok(self.merge_candidates_or_bail_with_ambiguity(&alias_bounds,
                                        TraitGoalProvenVia::AliasBound));
                        }
                        self.filter_specialized_impls(AllowInferenceConstraints::No,
                            &mut candidates);
                        self.unsound_prefer_builtin_dyn_impl(&mut candidates);
                        let only_global_where_bounds =
                            candidates.iter().all(|c|
                                    #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                        CandidateSource::ParamEnv(ParamEnvSource::Global) => true,
                                        _ => false,
                                    });
                        if only_global_where_bounds {
                            Ok(self.merge_candidates_or_bail_with_ambiguity(&candidates,
                                    TraitGoalProvenVia::ParamEnv))
                        } else {
                            candidates.retain(|c|
                                    !#[allow(non_exhaustive_omitted_patterns)] match c.source {
                                            CandidateSource::ParamEnv(ParamEnvSource::Global) => true,
                                            _ => false,
                                        });
                            Ok(self.merge_impl_candidates_or_bail_with_ambiguity(trait_def_id,
                                    &candidates))
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs:1646",
                        "rustc_next_trait_solver::solve::trait_goals",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs"),
                        ::tracing_core::__macro_support::Option::Some(1646u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::trait_goals"),
                        ::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(self), ret)]
1647    pub(super) fn merge_trait_candidates(
1648        &mut self,
1649        trait_def_id: I::TraitId,
1650        mut candidates: Vec<Candidate<I>>,
1651        failed_candidate_info: FailedCandidateInfo,
1652    ) -> Result<(CanonicalResponse<I>, Option<TraitGoalProvenVia>), NoSolution> {
1653        if candidates.is_empty() {
1654            return Err(NoSolution);
1655        }
1656
1657        let candidate_preference_mode = CandidatePreferenceMode::compute(self.cx(), trait_def_id);
1658        if self.typing_mode().is_coherence() {
1659            return Ok(match self.try_merge_impl_candidates(trait_def_id, &candidates) {
1660                Some(response) => (response, Some(TraitGoalProvenVia::Misc)),
1661                None => (self.bail_with_ambiguity(&candidates), None),
1662            });
1663        }
1664
1665        // We prefer trivial builtin candidates, i.e. builtin impls without any
1666        // nested requirements, over all others. This is a fix for #53123 and
1667        // prevents where-bounds from accidentally extending the lifetime of a
1668        // variable.
1669        let mut trivial_builtin_impls = candidates.iter().filter(|c| {
1670            matches!(c.source, CandidateSource::BuiltinImpl(BuiltinImplSource::Trivial))
1671        });
1672        if let Some(candidate) = trivial_builtin_impls.next() {
1673            // There should only ever be a single trivial builtin candidate
1674            // as they would otherwise overlap.
1675            assert!(trivial_builtin_impls.next().is_none());
1676            return Ok((candidate.result, Some(TraitGoalProvenVia::Misc)));
1677        }
1678
1679        // Extract non-nested alias bound candidates, will be preferred over where bounds if
1680        // we're proving an auto-trait, sizedness trait or default trait.
1681        if matches!(candidate_preference_mode, CandidatePreferenceMode::Marker)
1682            && candidates.iter().any(|c| {
1683                matches!(c.source, CandidateSource::AliasBound(AliasBoundKind::SelfBounds))
1684            })
1685        {
1686            let alias_bounds: Vec<_> = candidates
1687                .extract_if(.., |c| matches!(c.source, CandidateSource::AliasBound(..)))
1688                .collect();
1689            candidates.into_iter().for_each(|c| self.ignore_candidate_head_usages(c.head_usages));
1690            return Ok(self.merge_candidates_or_bail_with_ambiguity(
1691                &alias_bounds,
1692                TraitGoalProvenVia::AliasBound,
1693            ));
1694        }
1695
1696        // If there are non-global where-bounds, prefer where-bounds
1697        // (including global ones) over everything else.
1698        let has_non_global_where_bounds = candidates
1699            .iter()
1700            .any(|c| matches!(c.source, CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)));
1701        if has_non_global_where_bounds {
1702            let where_bounds: Vec<_> = candidates
1703                .extract_if(.., |c| matches!(c.source, CandidateSource::ParamEnv(_)))
1704                .collect();
1705            candidates.into_iter().for_each(|c| self.ignore_candidate_head_usages(c.head_usages));
1706            let Some(response) = self.try_merge_candidates(&where_bounds) else {
1707                return Ok((self.bail_with_ambiguity(&where_bounds), None));
1708            };
1709            return Ok((response, Some(TraitGoalProvenVia::ParamEnv)));
1710        }
1711
1712        // Next, prefer any alias bound (nested or otherwise).
1713        if candidates.iter().any(|c| matches!(c.source, CandidateSource::AliasBound(_))) {
1714            let alias_bounds: Vec<_> = candidates
1715                .extract_if(.., |c| matches!(c.source, CandidateSource::AliasBound(_)))
1716                .collect();
1717            candidates.into_iter().for_each(|c| self.ignore_candidate_head_usages(c.head_usages));
1718            return Ok(self.merge_candidates_or_bail_with_ambiguity(
1719                &alias_bounds,
1720                TraitGoalProvenVia::AliasBound,
1721            ));
1722        }
1723
1724        self.filter_specialized_impls(AllowInferenceConstraints::No, &mut candidates);
1725        self.unsound_prefer_builtin_dyn_impl(&mut candidates);
1726
1727        // If there are *only* global where bounds, then make sure to return that this
1728        // is still reported as being proven-via the param-env so that rigid projections
1729        // operate correctly. Otherwise, drop all global where-bounds before merging the
1730        // remaining candidates.
1731        let only_global_where_bounds = candidates
1732            .iter()
1733            .all(|c| matches!(c.source, CandidateSource::ParamEnv(ParamEnvSource::Global)));
1734        if only_global_where_bounds {
1735            Ok(self
1736                .merge_candidates_or_bail_with_ambiguity(&candidates, TraitGoalProvenVia::ParamEnv))
1737        } else {
1738            candidates
1739                .retain(|c| !matches!(c.source, CandidateSource::ParamEnv(ParamEnvSource::Global)));
1740            Ok(self.merge_impl_candidates_or_bail_with_ambiguity(trait_def_id, &candidates))
1741        }
1742    }
1743
1744    {}
#[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("compute_trait_goal",
                                    "rustc_next_trait_solver::solve::trait_goals",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1744u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::trait_goals"),
                                    ::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()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<(CanonicalResponse<I>, Option<TraitGoalProvenVia>),
                    NoSolutionOrRerunNonErased> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (candidates, failed_candidate_info) =
                self.assemble_and_evaluate_candidates(goal,
                        AssembleCandidatesFrom::All)?;
            self.merge_trait_candidates(goal.predicate.def_id(), candidates,
                    failed_candidate_info).map_err(Into::into)
        }
    }
}#[instrument(level = "trace", skip(self))]
1745    pub(super) fn compute_trait_goal(
1746        &mut self,
1747        goal: Goal<I, TraitClause<I>>,
1748    ) -> Result<(CanonicalResponse<I>, Option<TraitGoalProvenVia>), NoSolutionOrRerunNonErased>
1749    {
1750        let (candidates, failed_candidate_info) =
1751            self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1752        self.merge_trait_candidates(goal.predicate.def_id(), candidates, failed_candidate_info)
1753            .map_err(Into::into)
1754    }
1755
1756    fn try_stall_coroutine(
1757        &mut self,
1758        self_ty: I::Ty,
1759    ) -> Option<Result<Candidate<I>, NoSolutionOrRerunNonErased>> {
1760        if let ty::Coroutine(def_id, _) = self_ty.kind() {
1761            match self.typing_mode() {
1762                TypingMode::Typeck { defining_opaque_types_and_generators: stalled_generators } => {
1763                    if def_id.as_local().is_some_and(|def_id| stalled_generators.contains(&def_id))
1764                    {
1765                        return Some(self.forced_ambiguity(MaybeInfo {
1766                            cause: MaybeCause::Ambiguity,
1767                            opaque_types_jank: OpaqueTypesJank::AllGood,
1768                            stalled_on_coroutines: StalledOnCoroutines::Yes,
1769                        }));
1770                    }
1771                }
1772                TypingMode::ErasedNotCoherence(MayBeErased) => {
1773                    // Trying to continue here isn't worth it.
1774                    return Some(
1775                        match self.opaque_accesses.rerun_always(RerunReason::TryStallCoroutine) {
1776                            Err(e) => Err(e.into()),
1777                        },
1778                    );
1779                }
1780                TypingMode::Coherence
1781                | TypingMode::PostAnalysis
1782                | TypingMode::Reflection
1783                | TypingMode::Codegen
1784                | TypingMode::PostTypeckThroughBorrowck { defining_opaque_types: _ }
1785                | TypingMode::PostBorrowck { defined_opaque_types: _ } => {}
1786            }
1787        }
1788
1789        None
1790    }
1791}