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