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