1pub(super) mod structural_traits;
4
5use std::cell::Cell;
6use std::ops::ControlFlow;
7
8use derive_where::derive_where;
9use rustc_type_ir::inherent::*;
10use rustc_type_ir::lang_items::SolverTraitLangItem;
11use rustc_type_ir::search_graph::CandidateHeadUsages;
12use rustc_type_ir::solve::{AliasBoundKind, SizedTraitKind};
13use rustc_type_ir::{
14 self as ty, Interner, TypeFlags, TypeFoldable, TypeFolder, TypeSuperFoldable,
15 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast,
16 elaborate,
17};
18use tracing::{debug, instrument};
19
20use super::trait_goals::TraitGoalProvenVia;
21use super::{has_only_region_constraints, inspect};
22use crate::delegate::SolverDelegate;
23use crate::solve::inspect::ProbeKind;
24use crate::solve::{
25 BuiltinImplSource, CandidateSource, CanonicalResponse, Certainty, EvalCtxt, Goal, GoalSource,
26 MaybeCause, NoSolution, OpaqueTypesJank, ParamEnvSource, QueryResult,
27 has_no_inference_or_external_constraints,
28};
29
30#[derive_where(Debug; I: Interner)]
35pub(super) struct Candidate<I: Interner> {
36 pub(super) source: CandidateSource<I>,
37 pub(super) result: CanonicalResponse<I>,
38 pub(super) head_usages: CandidateHeadUsages,
39}
40
41pub(super) trait GoalKind<D, I = <D as SolverDelegate>::Interner>:
43 TypeFoldable<I> + Copy + Eq + std::fmt::Display
44where
45 D: SolverDelegate<Interner = I>,
46 I: Interner,
47{
48 fn self_ty(self) -> I::Ty;
49
50 fn trait_ref(self, cx: I) -> ty::TraitRef<I>;
51
52 fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self;
53
54 fn trait_def_id(self, cx: I) -> I::TraitId;
55
56 fn probe_and_consider_implied_clause(
60 ecx: &mut EvalCtxt<'_, D>,
61 parent_source: CandidateSource<I>,
62 goal: Goal<I, Self>,
63 assumption: I::Clause,
64 requirements: impl IntoIterator<Item = (GoalSource, Goal<I, I::Predicate>)>,
65 ) -> Result<Candidate<I>, NoSolution> {
66 Self::probe_and_match_goal_against_assumption(ecx, parent_source, goal, assumption, |ecx| {
67 for (nested_source, goal) in requirements {
68 ecx.add_goal(nested_source, goal);
69 }
70 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
71 })
72 }
73
74 fn probe_and_consider_object_bound_candidate(
78 ecx: &mut EvalCtxt<'_, D>,
79 source: CandidateSource<I>,
80 goal: Goal<I, Self>,
81 assumption: I::Clause,
82 ) -> Result<Candidate<I>, NoSolution> {
83 Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| {
84 let cx = ecx.cx();
85 let ty::Dynamic(bounds, _) = goal.predicate.self_ty().kind() else {
86 panic!("expected object type in `probe_and_consider_object_bound_candidate`");
87 };
88 match structural_traits::predicates_for_object_candidate(
89 ecx,
90 goal.param_env,
91 goal.predicate.trait_ref(cx),
92 bounds,
93 ) {
94 Ok(requirements) => {
95 ecx.add_goals(GoalSource::ImplWhereBound, requirements);
96 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
97 }
98 Err(_) => {
99 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
100 }
101 }
102 })
103 }
104
105 fn consider_additional_alias_assumptions(
109 ecx: &mut EvalCtxt<'_, D>,
110 goal: Goal<I, Self>,
111 alias_ty: ty::AliasTy<I>,
112 ) -> Vec<Candidate<I>>;
113
114 fn probe_and_consider_param_env_candidate(
115 ecx: &mut EvalCtxt<'_, D>,
116 goal: Goal<I, Self>,
117 assumption: I::Clause,
118 ) -> Result<Candidate<I>, CandidateHeadUsages> {
119 match Self::fast_reject_assumption(ecx, goal, assumption) {
120 Ok(()) => {}
121 Err(NoSolution) => return Err(CandidateHeadUsages::default()),
122 }
123
124 let source = Cell::new(CandidateSource::ParamEnv(ParamEnvSource::Global));
131 let (result, head_usages) = ecx
132 .probe(|result: &QueryResult<I>| inspect::ProbeKind::TraitCandidate {
133 source: source.get(),
134 result: *result,
135 })
136 .enter_single_candidate(|ecx| {
137 Self::match_assumption(ecx, goal, assumption, |ecx| {
138 ecx.try_evaluate_added_goals()?;
139 source.set(ecx.characterize_param_env_assumption(goal.param_env, assumption)?);
140 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
141 })
142 });
143
144 match result {
145 Ok(result) => Ok(Candidate { source: source.get(), result, head_usages }),
146 Err(NoSolution) => Err(head_usages),
147 }
148 }
149
150 fn probe_and_match_goal_against_assumption(
155 ecx: &mut EvalCtxt<'_, D>,
156 source: CandidateSource<I>,
157 goal: Goal<I, Self>,
158 assumption: I::Clause,
159 then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
160 ) -> Result<Candidate<I>, NoSolution> {
161 Self::fast_reject_assumption(ecx, goal, assumption)?;
162
163 ecx.probe_trait_candidate(source)
164 .enter(|ecx| Self::match_assumption(ecx, goal, assumption, then))
165 }
166
167 fn fast_reject_assumption(
170 ecx: &mut EvalCtxt<'_, D>,
171 goal: Goal<I, Self>,
172 assumption: I::Clause,
173 ) -> Result<(), NoSolution>;
174
175 fn match_assumption(
177 ecx: &mut EvalCtxt<'_, D>,
178 goal: Goal<I, Self>,
179 assumption: I::Clause,
180 then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
181 ) -> QueryResult<I>;
182
183 fn consider_impl_candidate(
184 ecx: &mut EvalCtxt<'_, D>,
185 goal: Goal<I, Self>,
186 impl_def_id: I::ImplId,
187 then: impl FnOnce(&mut EvalCtxt<'_, D>, Certainty) -> QueryResult<I>,
188 ) -> Result<Candidate<I>, NoSolution>;
189
190 fn consider_error_guaranteed_candidate(
197 ecx: &mut EvalCtxt<'_, D>,
198 guar: I::ErrorGuaranteed,
199 ) -> Result<Candidate<I>, NoSolution>;
200
201 fn consider_auto_trait_candidate(
206 ecx: &mut EvalCtxt<'_, D>,
207 goal: Goal<I, Self>,
208 ) -> Result<Candidate<I>, NoSolution>;
209
210 fn consider_trait_alias_candidate(
212 ecx: &mut EvalCtxt<'_, D>,
213 goal: Goal<I, Self>,
214 ) -> Result<Candidate<I>, NoSolution>;
215
216 fn consider_builtin_sizedness_candidates(
222 ecx: &mut EvalCtxt<'_, D>,
223 goal: Goal<I, Self>,
224 sizedness: SizedTraitKind,
225 ) -> Result<Candidate<I>, NoSolution>;
226
227 fn consider_builtin_copy_clone_candidate(
232 ecx: &mut EvalCtxt<'_, D>,
233 goal: Goal<I, Self>,
234 ) -> Result<Candidate<I>, NoSolution>;
235
236 fn consider_builtin_fn_ptr_trait_candidate(
238 ecx: &mut EvalCtxt<'_, D>,
239 goal: Goal<I, Self>,
240 ) -> Result<Candidate<I>, NoSolution>;
241
242 fn consider_builtin_fn_trait_candidates(
245 ecx: &mut EvalCtxt<'_, D>,
246 goal: Goal<I, Self>,
247 kind: ty::ClosureKind,
248 ) -> Result<Candidate<I>, NoSolution>;
249
250 fn consider_builtin_async_fn_trait_candidates(
253 ecx: &mut EvalCtxt<'_, D>,
254 goal: Goal<I, Self>,
255 kind: ty::ClosureKind,
256 ) -> Result<Candidate<I>, NoSolution>;
257
258 fn consider_builtin_async_fn_kind_helper_candidate(
262 ecx: &mut EvalCtxt<'_, D>,
263 goal: Goal<I, Self>,
264 ) -> Result<Candidate<I>, NoSolution>;
265
266 fn consider_builtin_tuple_candidate(
268 ecx: &mut EvalCtxt<'_, D>,
269 goal: Goal<I, Self>,
270 ) -> Result<Candidate<I>, NoSolution>;
271
272 fn consider_builtin_pointee_candidate(
278 ecx: &mut EvalCtxt<'_, D>,
279 goal: Goal<I, Self>,
280 ) -> Result<Candidate<I>, NoSolution>;
281
282 fn consider_builtin_future_candidate(
286 ecx: &mut EvalCtxt<'_, D>,
287 goal: Goal<I, Self>,
288 ) -> Result<Candidate<I>, NoSolution>;
289
290 fn consider_builtin_iterator_candidate(
294 ecx: &mut EvalCtxt<'_, D>,
295 goal: Goal<I, Self>,
296 ) -> Result<Candidate<I>, NoSolution>;
297
298 fn consider_builtin_fused_iterator_candidate(
301 ecx: &mut EvalCtxt<'_, D>,
302 goal: Goal<I, Self>,
303 ) -> Result<Candidate<I>, NoSolution>;
304
305 fn consider_builtin_async_iterator_candidate(
306 ecx: &mut EvalCtxt<'_, D>,
307 goal: Goal<I, Self>,
308 ) -> Result<Candidate<I>, NoSolution>;
309
310 fn consider_builtin_coroutine_candidate(
314 ecx: &mut EvalCtxt<'_, D>,
315 goal: Goal<I, Self>,
316 ) -> Result<Candidate<I>, NoSolution>;
317
318 fn consider_builtin_discriminant_kind_candidate(
319 ecx: &mut EvalCtxt<'_, D>,
320 goal: Goal<I, Self>,
321 ) -> Result<Candidate<I>, NoSolution>;
322
323 fn consider_builtin_destruct_candidate(
324 ecx: &mut EvalCtxt<'_, D>,
325 goal: Goal<I, Self>,
326 ) -> Result<Candidate<I>, NoSolution>;
327
328 fn consider_builtin_transmute_candidate(
329 ecx: &mut EvalCtxt<'_, D>,
330 goal: Goal<I, Self>,
331 ) -> Result<Candidate<I>, NoSolution>;
332
333 fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
334 ecx: &mut EvalCtxt<'_, D>,
335 goal: Goal<I, Self>,
336 ) -> Result<Candidate<I>, NoSolution>;
337
338 fn consider_structural_builtin_unsize_candidates(
346 ecx: &mut EvalCtxt<'_, D>,
347 goal: Goal<I, Self>,
348 ) -> Vec<Candidate<I>>;
349}
350
351pub(super) enum AssembleCandidatesFrom {
359 All,
360 EnvAndBounds,
364}
365
366impl AssembleCandidatesFrom {
367 fn should_assemble_impl_candidates(&self) -> bool {
368 match self {
369 AssembleCandidatesFrom::All => true,
370 AssembleCandidatesFrom::EnvAndBounds => false,
371 }
372 }
373}
374
375#[derive(Debug)]
384pub(super) struct FailedCandidateInfo {
385 pub param_env_head_usages: CandidateHeadUsages,
386}
387
388impl<D, I> EvalCtxt<'_, D>
389where
390 D: SolverDelegate<Interner = I>,
391 I: Interner,
392{
393 pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<D>>(
394 &mut self,
395 goal: Goal<I, G>,
396 assemble_from: AssembleCandidatesFrom,
397 ) -> (Vec<Candidate<I>>, FailedCandidateInfo) {
398 let mut candidates = vec![];
399 let mut failed_candidate_info =
400 FailedCandidateInfo { param_env_head_usages: CandidateHeadUsages::default() };
401 let Ok(normalized_self_ty) =
402 self.structurally_normalize_ty(goal.param_env, goal.predicate.self_ty())
403 else {
404 return (candidates, failed_candidate_info);
405 };
406
407 let goal: Goal<I, G> = goal
408 .with(self.cx(), goal.predicate.with_replaced_self_ty(self.cx(), normalized_self_ty));
409
410 if normalized_self_ty.is_ty_var() {
411 debug!("self type has been normalized to infer");
412 self.try_assemble_bounds_via_registered_opaques(goal, assemble_from, &mut candidates);
413 return (candidates, failed_candidate_info);
414 }
415
416 let goal = self.resolve_vars_if_possible(goal);
419
420 if let TypingMode::Coherence = self.typing_mode()
421 && let Ok(candidate) = self.consider_coherence_unknowable_candidate(goal)
422 {
423 candidates.push(candidate);
424 return (candidates, failed_candidate_info);
425 }
426
427 self.assemble_alias_bound_candidates(goal, &mut candidates);
428 self.assemble_param_env_candidates(goal, &mut candidates, &mut failed_candidate_info);
429
430 match assemble_from {
431 AssembleCandidatesFrom::All => {
432 self.assemble_builtin_impl_candidates(goal, &mut candidates);
433 if TypingMode::Coherence == self.typing_mode()
445 || !candidates.iter().any(|c| {
446 matches!(
447 c.source,
448 CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)
449 | CandidateSource::AliasBound(_)
450 ) && has_no_inference_or_external_constraints(c.result)
451 })
452 {
453 self.assemble_impl_candidates(goal, &mut candidates);
454 self.assemble_object_bound_candidates(goal, &mut candidates);
455 }
456 }
457 AssembleCandidatesFrom::EnvAndBounds => {}
458 }
459
460 (candidates, failed_candidate_info)
461 }
462
463 pub(super) fn forced_ambiguity(
464 &mut self,
465 cause: MaybeCause,
466 ) -> Result<Candidate<I>, NoSolution> {
467 let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
476 let certainty = Certainty::Maybe { cause, opaque_types_jank: OpaqueTypesJank::AllGood };
477 self.probe_trait_candidate(source)
478 .enter(|this| this.evaluate_added_goals_and_make_canonical_response(certainty))
479 }
480
481 #[instrument(level = "trace", skip_all)]
482 fn assemble_impl_candidates<G: GoalKind<D>>(
483 &mut self,
484 goal: Goal<I, G>,
485 candidates: &mut Vec<Candidate<I>>,
486 ) {
487 let cx = self.cx();
488 cx.for_each_relevant_impl(
489 goal.predicate.trait_def_id(cx),
490 goal.predicate.self_ty(),
491 |impl_def_id| {
492 if cx.impl_is_default(impl_def_id) {
496 return;
497 }
498 match G::consider_impl_candidate(self, goal, impl_def_id, |ecx, certainty| {
499 ecx.evaluate_added_goals_and_make_canonical_response(certainty)
500 }) {
501 Ok(candidate) => candidates.push(candidate),
502 Err(NoSolution) => (),
503 }
504 },
505 );
506 }
507
508 #[instrument(level = "trace", skip_all)]
509 fn assemble_builtin_impl_candidates<G: GoalKind<D>>(
510 &mut self,
511 goal: Goal<I, G>,
512 candidates: &mut Vec<Candidate<I>>,
513 ) {
514 let cx = self.cx();
515 let trait_def_id = goal.predicate.trait_def_id(cx);
516
517 let result = if let Err(guar) = goal.predicate.error_reported() {
525 G::consider_error_guaranteed_candidate(self, guar)
526 } else if cx.trait_is_auto(trait_def_id) {
527 G::consider_auto_trait_candidate(self, goal)
528 } else if cx.trait_is_alias(trait_def_id) {
529 G::consider_trait_alias_candidate(self, goal)
530 } else {
531 match cx.as_trait_lang_item(trait_def_id) {
532 Some(SolverTraitLangItem::Sized) => {
533 G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::Sized)
534 }
535 Some(SolverTraitLangItem::MetaSized) => {
536 G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::MetaSized)
537 }
538 Some(SolverTraitLangItem::PointeeSized) => {
539 unreachable!("`PointeeSized` is removed during lowering");
540 }
541 Some(SolverTraitLangItem::Copy | SolverTraitLangItem::Clone) => {
542 G::consider_builtin_copy_clone_candidate(self, goal)
543 }
544 Some(SolverTraitLangItem::Fn) => {
545 G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
546 }
547 Some(SolverTraitLangItem::FnMut) => {
548 G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnMut)
549 }
550 Some(SolverTraitLangItem::FnOnce) => {
551 G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnOnce)
552 }
553 Some(SolverTraitLangItem::AsyncFn) => {
554 G::consider_builtin_async_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
555 }
556 Some(SolverTraitLangItem::AsyncFnMut) => {
557 G::consider_builtin_async_fn_trait_candidates(
558 self,
559 goal,
560 ty::ClosureKind::FnMut,
561 )
562 }
563 Some(SolverTraitLangItem::AsyncFnOnce) => {
564 G::consider_builtin_async_fn_trait_candidates(
565 self,
566 goal,
567 ty::ClosureKind::FnOnce,
568 )
569 }
570 Some(SolverTraitLangItem::FnPtrTrait) => {
571 G::consider_builtin_fn_ptr_trait_candidate(self, goal)
572 }
573 Some(SolverTraitLangItem::AsyncFnKindHelper) => {
574 G::consider_builtin_async_fn_kind_helper_candidate(self, goal)
575 }
576 Some(SolverTraitLangItem::Tuple) => G::consider_builtin_tuple_candidate(self, goal),
577 Some(SolverTraitLangItem::PointeeTrait) => {
578 G::consider_builtin_pointee_candidate(self, goal)
579 }
580 Some(SolverTraitLangItem::Future) => {
581 G::consider_builtin_future_candidate(self, goal)
582 }
583 Some(SolverTraitLangItem::Iterator) => {
584 G::consider_builtin_iterator_candidate(self, goal)
585 }
586 Some(SolverTraitLangItem::FusedIterator) => {
587 G::consider_builtin_fused_iterator_candidate(self, goal)
588 }
589 Some(SolverTraitLangItem::AsyncIterator) => {
590 G::consider_builtin_async_iterator_candidate(self, goal)
591 }
592 Some(SolverTraitLangItem::Coroutine) => {
593 G::consider_builtin_coroutine_candidate(self, goal)
594 }
595 Some(SolverTraitLangItem::DiscriminantKind) => {
596 G::consider_builtin_discriminant_kind_candidate(self, goal)
597 }
598 Some(SolverTraitLangItem::Destruct) => {
599 G::consider_builtin_destruct_candidate(self, goal)
600 }
601 Some(SolverTraitLangItem::TransmuteTrait) => {
602 G::consider_builtin_transmute_candidate(self, goal)
603 }
604 Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
605 G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self, goal)
606 }
607 _ => Err(NoSolution),
608 }
609 };
610
611 candidates.extend(result);
612
613 if cx.is_trait_lang_item(trait_def_id, SolverTraitLangItem::Unsize) {
616 candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal));
617 }
618 }
619
620 #[instrument(level = "trace", skip_all)]
621 fn assemble_param_env_candidates<G: GoalKind<D>>(
622 &mut self,
623 goal: Goal<I, G>,
624 candidates: &mut Vec<Candidate<I>>,
625 failed_candidate_info: &mut FailedCandidateInfo,
626 ) {
627 for assumption in goal.param_env.caller_bounds().iter() {
628 match G::probe_and_consider_param_env_candidate(self, goal, assumption) {
629 Ok(candidate) => candidates.push(candidate),
630 Err(head_usages) => {
631 failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
632 }
633 }
634 }
635 }
636
637 #[instrument(level = "trace", skip_all)]
638 fn assemble_alias_bound_candidates<G: GoalKind<D>>(
639 &mut self,
640 goal: Goal<I, G>,
641 candidates: &mut Vec<Candidate<I>>,
642 ) {
643 let () = self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
644 ecx.assemble_alias_bound_candidates_recur(
645 goal.predicate.self_ty(),
646 goal,
647 candidates,
648 AliasBoundKind::SelfBounds,
649 );
650 });
651 }
652
653 fn assemble_alias_bound_candidates_recur<G: GoalKind<D>>(
663 &mut self,
664 self_ty: I::Ty,
665 goal: Goal<I, G>,
666 candidates: &mut Vec<Candidate<I>>,
667 consider_self_bounds: AliasBoundKind,
668 ) {
669 let (kind, alias_ty) = match self_ty.kind() {
670 ty::Bool
671 | ty::Char
672 | ty::Int(_)
673 | ty::Uint(_)
674 | ty::Float(_)
675 | ty::Adt(_, _)
676 | ty::Foreign(_)
677 | ty::Str
678 | ty::Array(_, _)
679 | ty::Pat(_, _)
680 | ty::Slice(_)
681 | ty::RawPtr(_, _)
682 | ty::Ref(_, _, _)
683 | ty::FnDef(_, _)
684 | ty::FnPtr(..)
685 | ty::UnsafeBinder(_)
686 | ty::Dynamic(..)
687 | ty::Closure(..)
688 | ty::CoroutineClosure(..)
689 | ty::Coroutine(..)
690 | ty::CoroutineWitness(..)
691 | ty::Never
692 | ty::Tuple(_)
693 | ty::Param(_)
694 | ty::Placeholder(..)
695 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
696 | ty::Error(_) => return,
697 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => {
698 panic!("unexpected self type for `{goal:?}`")
699 }
700
701 ty::Infer(ty::TyVar(_)) => {
702 if let Ok(result) =
706 self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
707 {
708 candidates.push(Candidate {
709 source: CandidateSource::AliasBound(consider_self_bounds),
710 result,
711 head_usages: CandidateHeadUsages::default(),
712 });
713 }
714 return;
715 }
716
717 ty::Alias(kind @ (ty::Projection | ty::Opaque), alias_ty) => (kind, alias_ty),
718 ty::Alias(ty::Inherent | ty::Free, _) => {
719 self.cx().delay_bug(format!("could not normalize {self_ty:?}, it is not WF"));
720 return;
721 }
722 };
723
724 match consider_self_bounds {
725 AliasBoundKind::SelfBounds => {
726 for assumption in self
727 .cx()
728 .item_self_bounds(alias_ty.def_id)
729 .iter_instantiated(self.cx(), alias_ty.args)
730 {
731 candidates.extend(G::probe_and_consider_implied_clause(
732 self,
733 CandidateSource::AliasBound(consider_self_bounds),
734 goal,
735 assumption,
736 [],
737 ));
738 }
739 }
740 AliasBoundKind::NonSelfBounds => {
741 for assumption in self
742 .cx()
743 .item_non_self_bounds(alias_ty.def_id)
744 .iter_instantiated(self.cx(), alias_ty.args)
745 {
746 candidates.extend(G::probe_and_consider_implied_clause(
747 self,
748 CandidateSource::AliasBound(consider_self_bounds),
749 goal,
750 assumption,
751 [],
752 ));
753 }
754 }
755 }
756
757 candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty));
758
759 if kind != ty::Projection {
760 return;
761 }
762
763 match self.structurally_normalize_ty(goal.param_env, alias_ty.self_ty()) {
765 Ok(next_self_ty) => self.assemble_alias_bound_candidates_recur(
766 next_self_ty,
767 goal,
768 candidates,
769 AliasBoundKind::NonSelfBounds,
770 ),
771 Err(NoSolution) => {}
772 }
773 }
774
775 #[instrument(level = "trace", skip_all)]
776 fn assemble_object_bound_candidates<G: GoalKind<D>>(
777 &mut self,
778 goal: Goal<I, G>,
779 candidates: &mut Vec<Candidate<I>>,
780 ) {
781 let cx = self.cx();
782 if !cx.trait_may_be_implemented_via_object(goal.predicate.trait_def_id(cx)) {
783 return;
784 }
785
786 let self_ty = goal.predicate.self_ty();
787 let bounds = match self_ty.kind() {
788 ty::Bool
789 | ty::Char
790 | ty::Int(_)
791 | ty::Uint(_)
792 | ty::Float(_)
793 | ty::Adt(_, _)
794 | ty::Foreign(_)
795 | ty::Str
796 | ty::Array(_, _)
797 | ty::Pat(_, _)
798 | ty::Slice(_)
799 | ty::RawPtr(_, _)
800 | ty::Ref(_, _, _)
801 | ty::FnDef(_, _)
802 | ty::FnPtr(..)
803 | ty::UnsafeBinder(_)
804 | ty::Alias(..)
805 | ty::Closure(..)
806 | ty::CoroutineClosure(..)
807 | ty::Coroutine(..)
808 | ty::CoroutineWitness(..)
809 | ty::Never
810 | ty::Tuple(_)
811 | ty::Param(_)
812 | ty::Placeholder(..)
813 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
814 | ty::Error(_) => return,
815 ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
816 | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"),
817 ty::Dynamic(bounds, ..) => bounds,
818 };
819
820 if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
822 return;
823 }
824
825 for bound in bounds.iter() {
829 match bound.skip_binder() {
830 ty::ExistentialPredicate::Trait(_) => {
831 }
833 ty::ExistentialPredicate::Projection(_)
834 | ty::ExistentialPredicate::AutoTrait(_) => {
835 candidates.extend(G::probe_and_consider_object_bound_candidate(
836 self,
837 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
838 goal,
839 bound.with_self_ty(cx, self_ty),
840 ));
841 }
842 }
843 }
844
845 if let Some(principal) = bounds.principal() {
849 let principal_trait_ref = principal.with_self_ty(cx, self_ty);
850 for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
851 candidates.extend(G::probe_and_consider_object_bound_candidate(
852 self,
853 CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
854 goal,
855 assumption.upcast(cx),
856 ));
857 }
858 }
859 }
860
861 #[instrument(level = "trace", skip_all)]
868 fn consider_coherence_unknowable_candidate<G: GoalKind<D>>(
869 &mut self,
870 goal: Goal<I, G>,
871 ) -> Result<Candidate<I>, NoSolution> {
872 self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx| {
873 let cx = ecx.cx();
874 let trait_ref = goal.predicate.trait_ref(cx);
875 if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
876 Err(NoSolution)
877 } else {
878 let predicate: I::Predicate = trait_ref.upcast(cx);
884 ecx.add_goals(
885 GoalSource::Misc,
886 elaborate::elaborate(cx, [predicate])
887 .skip(1)
888 .map(|predicate| goal.with(cx, predicate)),
889 );
890 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
891 }
892 })
893 }
894}
895
896pub(super) enum AllowInferenceConstraints {
897 Yes,
898 No,
899}
900
901impl<D, I> EvalCtxt<'_, D>
902where
903 D: SolverDelegate<Interner = I>,
904 I: Interner,
905{
906 pub(super) fn filter_specialized_impls(
910 &mut self,
911 allow_inference_constraints: AllowInferenceConstraints,
912 candidates: &mut Vec<Candidate<I>>,
913 ) {
914 match self.typing_mode() {
915 TypingMode::Coherence => return,
916 TypingMode::Analysis { .. }
917 | TypingMode::Borrowck { .. }
918 | TypingMode::PostBorrowckAnalysis { .. }
919 | TypingMode::PostAnalysis => {}
920 }
921
922 let mut i = 0;
923 'outer: while i < candidates.len() {
924 let CandidateSource::Impl(victim_def_id) = candidates[i].source else {
925 i += 1;
926 continue;
927 };
928
929 for (j, c) in candidates.iter().enumerate() {
930 if i == j {
931 continue;
932 }
933
934 let CandidateSource::Impl(other_def_id) = c.source else {
935 continue;
936 };
937
938 if matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
945 || has_only_region_constraints(c.result)
946 {
947 if self.cx().impl_specializes(other_def_id, victim_def_id) {
948 candidates.remove(i);
949 continue 'outer;
950 }
951 }
952 }
953
954 i += 1;
955 }
956 }
957
958 fn try_assemble_bounds_via_registered_opaques<G: GoalKind<D>>(
970 &mut self,
971 goal: Goal<I, G>,
972 assemble_from: AssembleCandidatesFrom,
973 candidates: &mut Vec<Candidate<I>>,
974 ) {
975 let self_ty = goal.predicate.self_ty();
976 let opaque_types = match self.typing_mode() {
978 TypingMode::Analysis { .. } => self.opaques_with_sub_unified_hidden_type(self_ty),
979 TypingMode::Coherence
980 | TypingMode::Borrowck { .. }
981 | TypingMode::PostBorrowckAnalysis { .. }
982 | TypingMode::PostAnalysis => vec![],
983 };
984
985 if opaque_types.is_empty() {
986 candidates.extend(self.forced_ambiguity(MaybeCause::Ambiguity));
987 return;
988 }
989
990 for &alias_ty in &opaque_types {
991 debug!("self ty is sub unified with {alias_ty:?}");
992
993 struct ReplaceOpaque<I: Interner> {
994 cx: I,
995 alias_ty: ty::AliasTy<I>,
996 self_ty: I::Ty,
997 }
998 impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
999 fn cx(&self) -> I {
1000 self.cx
1001 }
1002 fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1003 if let ty::Alias(ty::Opaque, alias_ty) = ty.kind() {
1004 if alias_ty == self.alias_ty {
1005 return self.self_ty;
1006 }
1007 }
1008 ty.super_fold_with(self)
1009 }
1010 }
1011
1012 for item_bound in self
1020 .cx()
1021 .item_self_bounds(alias_ty.def_id)
1022 .iter_instantiated(self.cx(), alias_ty.args)
1023 {
1024 let assumption =
1025 item_bound.fold_with(&mut ReplaceOpaque { cx: self.cx(), alias_ty, self_ty });
1026 candidates.extend(G::probe_and_match_goal_against_assumption(
1027 self,
1028 CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
1029 goal,
1030 assumption,
1031 |ecx| {
1032 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1035 },
1036 ));
1037 }
1038 }
1039
1040 if assemble_from.should_assemble_impl_candidates() {
1045 let cx = self.cx();
1046 cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx), |impl_def_id| {
1047 if cx.impl_is_default(impl_def_id) {
1051 return;
1052 }
1053
1054 match G::consider_impl_candidate(self, goal, impl_def_id, |ecx, certainty| {
1055 if ecx.shallow_resolve(self_ty).is_ty_var() {
1056 let certainty = certainty.and(Certainty::AMBIGUOUS);
1058 ecx.evaluate_added_goals_and_make_canonical_response(certainty)
1059 } else {
1060 Err(NoSolution)
1066 }
1067 }) {
1068 Ok(candidate) => candidates.push(candidate),
1069 Err(NoSolution) => (),
1070 }
1071 });
1072 }
1073
1074 if candidates.is_empty() {
1075 let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1076 let certainty = Certainty::Maybe {
1077 cause: MaybeCause::Ambiguity,
1078 opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
1079 };
1080 candidates
1081 .extend(self.probe_trait_candidate(source).enter(|this| {
1082 this.evaluate_added_goals_and_make_canonical_response(certainty)
1083 }));
1084 }
1085 }
1086
1087 #[instrument(level = "debug", skip(self, inject_normalize_to_rigid_candidate), ret)]
1118 pub(super) fn assemble_and_merge_candidates<G: GoalKind<D>>(
1119 &mut self,
1120 proven_via: Option<TraitGoalProvenVia>,
1121 goal: Goal<I, G>,
1122 inject_normalize_to_rigid_candidate: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
1123 ) -> QueryResult<I> {
1124 let Some(proven_via) = proven_via else {
1125 return self.forced_ambiguity(MaybeCause::Ambiguity).map(|cand| cand.result);
1132 };
1133
1134 match proven_via {
1135 TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => {
1136 let (mut candidates, _) = self
1140 .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds);
1141
1142 if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1145 candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1146 } else if candidates.is_empty() {
1147 return inject_normalize_to_rigid_candidate(self);
1150 }
1151
1152 if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1153 Ok(response)
1154 } else {
1155 self.flounder(&candidates)
1156 }
1157 }
1158 TraitGoalProvenVia::Misc => {
1159 let (mut candidates, _) =
1160 self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All);
1161
1162 if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1165 candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1166 }
1167
1168 self.filter_specialized_impls(AllowInferenceConstraints::Yes, &mut candidates);
1174 if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1175 Ok(response)
1176 } else {
1177 self.flounder(&candidates)
1178 }
1179 }
1180 }
1181 }
1182
1183 fn characterize_param_env_assumption(
1197 &mut self,
1198 param_env: I::ParamEnv,
1199 assumption: I::Clause,
1200 ) -> Result<CandidateSource<I>, NoSolution> {
1201 if assumption.has_bound_vars() {
1204 return Ok(CandidateSource::ParamEnv(ParamEnvSource::NonGlobal));
1205 }
1206
1207 match assumption.visit_with(&mut FindParamInClause {
1208 ecx: self,
1209 param_env,
1210 universes: vec![],
1211 }) {
1212 ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1213 ControlFlow::Break(Ok(())) => Ok(CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)),
1214 ControlFlow::Continue(()) => Ok(CandidateSource::ParamEnv(ParamEnvSource::Global)),
1215 }
1216 }
1217}
1218
1219struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1220 ecx: &'a mut EvalCtxt<'b, D>,
1221 param_env: I::ParamEnv,
1222 universes: Vec<Option<ty::UniverseIndex>>,
1223}
1224
1225impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1226where
1227 D: SolverDelegate<Interner = I>,
1228 I: Interner,
1229{
1230 type Result = ControlFlow<Result<(), NoSolution>>;
1231
1232 fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1233 self.universes.push(None);
1234 t.super_visit_with(self)?;
1235 self.universes.pop();
1236 ControlFlow::Continue(())
1237 }
1238
1239 fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1240 let ty = self.ecx.replace_bound_vars(ty, &mut self.universes);
1241 let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1242 return ControlFlow::Break(Err(NoSolution));
1243 };
1244
1245 if let ty::Placeholder(p) = ty.kind() {
1246 if p.universe() == ty::UniverseIndex::ROOT {
1247 ControlFlow::Break(Ok(()))
1248 } else {
1249 ControlFlow::Continue(())
1250 }
1251 } else if ty.has_type_flags(TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_RE_INFER) {
1252 ty.super_visit_with(self)
1253 } else {
1254 ControlFlow::Continue(())
1255 }
1256 }
1257
1258 fn visit_const(&mut self, ct: I::Const) -> Self::Result {
1259 let ct = self.ecx.replace_bound_vars(ct, &mut self.universes);
1260 let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1261 return ControlFlow::Break(Err(NoSolution));
1262 };
1263
1264 if let ty::ConstKind::Placeholder(p) = ct.kind() {
1265 if p.universe() == ty::UniverseIndex::ROOT {
1266 ControlFlow::Break(Ok(()))
1267 } else {
1268 ControlFlow::Continue(())
1269 }
1270 } else if ct.has_type_flags(TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_RE_INFER) {
1271 ct.super_visit_with(self)
1272 } else {
1273 ControlFlow::Continue(())
1274 }
1275 }
1276
1277 fn visit_region(&mut self, r: I::Region) -> Self::Result {
1278 match self.ecx.eager_resolve_region(r).kind() {
1279 ty::ReStatic | ty::ReError(_) | ty::ReBound(..) => ControlFlow::Continue(()),
1280 ty::RePlaceholder(p) => {
1281 if p.universe() == ty::UniverseIndex::ROOT {
1282 ControlFlow::Break(Ok(()))
1283 } else {
1284 ControlFlow::Continue(())
1285 }
1286 }
1287 ty::ReVar(_) => ControlFlow::Break(Ok(())),
1288 ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
1289 unreachable!("unexpected region in param-env clause")
1290 }
1291 }
1292 }
1293}