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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<(CanonicalResponse<I>, Option<TraitGoalProvenVia>),
                    NoSolutionOrRerunNonErased> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (candidates, failed_candidate_info) =
                self.assemble_and_evaluate_candidates(goal,
                        AssembleCandidatesFrom::All)?;
            let candidate_preference_mode =
                CandidatePreferenceMode::compute(self.cx(),
                    goal.predicate.def_id());
            self.merge_trait_candidates(candidate_preference_mode, candidates,
                    failed_candidate_info).map_err(Into::into)
        }
    }
}#[instrument(level = "trace", skip(self))]
1573    pub(super) fn compute_trait_goal(
1574        &mut self,
1575        goal: Goal<I, TraitPredicate<I>>,
1576    ) -> Result<(CanonicalResponse<I>, Option<TraitGoalProvenVia>), NoSolutionOrRerunNonErased>
1577    {
1578        let (candidates, failed_candidate_info) =
1579            self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1580        let candidate_preference_mode =
1581            CandidatePreferenceMode::compute(self.cx(), goal.predicate.def_id());
1582        self.merge_trait_candidates(candidate_preference_mode, candidates, failed_candidate_info)
1583            .map_err(Into::into)
1584    }
1585
1586    fn try_stall_coroutine(
1587        &mut self,
1588        self_ty: I::Ty,
1589    ) -> Option<Result<Candidate<I>, NoSolutionOrRerunNonErased>> {
1590        if let ty::Coroutine(def_id, _) = self_ty.kind() {
1591            match self.typing_mode() {
1592                TypingMode::Analysis {
1593                    defining_opaque_types_and_generators: stalled_generators,
1594                } => {
1595                    if def_id.as_local().is_some_and(|def_id| stalled_generators.contains(&def_id))
1596                    {
1597                        return Some(self.forced_ambiguity(MaybeInfo {
1598                            cause: MaybeCause::Ambiguity,
1599                            opaque_types_jank: OpaqueTypesJank::AllGood,
1600                            stalled_on_coroutines: StalledOnCoroutines::Yes,
1601                        }));
1602                    }
1603                }
1604                TypingMode::ErasedNotCoherence(MayBeErased) => {
1605                    // Trying to continue here isn't worth it.
1606                    return Some(
1607                        match self.opaque_accesses.rerun_always(RerunReason::TryStallCoroutine) {
1608                            Err(e) => Err(e.into()),
1609                        },
1610                    );
1611                }
1612                TypingMode::Coherence
1613                | TypingMode::PostAnalysis
1614                | TypingMode::Borrowck { defining_opaque_types: _ }
1615                | TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ } => {}
1616            }
1617        }
1618
1619        None
1620    }
1621}