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