1use std::{cell::RefCell, convert::Infallible, ops::ControlFlow};
5
6use base_db::FxIndexMap;
7use hir_def::{
8 AssocItemId, FunctionId, GenericParamId, ImplId, ItemContainerId, TraitId,
9 hir::generics::GenericParams,
10 signatures::{FunctionSignature, TraitFlags, TraitSignature},
11};
12use hir_expand::name::Name;
13use rustc_ast_ir::Mutability;
14use rustc_hash::FxHashSet;
15use rustc_type_ir::{
16 InferTy, TypeVisitableExt, Upcast, Variance,
17 elaborate::{self, supertrait_def_ids},
18 fast_reject::{DeepRejectCtxt, TreatParams, simplify_type},
19 inherent::{BoundExistentialPredicates as _, IntoKind, Ty as _},
20};
21use smallvec::{SmallVec, smallvec};
22use tracing::{debug, instrument};
23
24use self::CandidateKind::*;
25pub(super) use self::PickKind::*;
26use crate::{
27 autoderef::Autoderef,
28 db::HirDatabase,
29 lower::GenericPredicates,
30 method_resolution::{
31 CandidateId, CandidateSource, InherentImpls, MethodError, MethodResolutionContext,
32 simplified_type_module, with_incoherent_inherent_impls,
33 },
34 next_solver::{
35 Binder, Canonical, ClauseKind, DbInterner, FnSig, GenericArg, GenericArgs, Goal, ParamEnv,
36 PolyTraitRef, Predicate, Region, SimplifiedType, TraitRef, Ty, TyKind, Unnormalized,
37 infer::{
38 BoundRegionConversionTime, InferCtxt, InferOk,
39 canonical::{QueryResponse, canonicalizer::OriginalQueryValues},
40 select::{ImplSource, Selection, SelectionResult},
41 traits::{Obligation, ObligationCause, PredicateObligation},
42 },
43 obligation_ctxt::ObligationCtxt,
44 util::clauses_as_obligations,
45 },
46};
47
48struct ProbeContext<'a, 'db, Choice> {
49 ctx: &'a MethodResolutionContext<'a, 'db>,
50 mode: Mode,
51
52 orig_steps_var_values: &'a OriginalQueryValues<'db>,
55 steps: &'a [CandidateStep<'db>],
56
57 inherent_candidates: Vec<Candidate<'db>>,
58 extension_candidates: Vec<Candidate<'db>>,
59 impl_dups: FxHashSet<ImplId>,
60
61 private_candidates: Vec<Candidate<'db>>,
64
65 static_candidates: Vec<CandidateSource>,
68
69 choice: Choice,
70}
71
72#[derive(Debug)]
73pub struct CandidateWithPrivate<'db> {
74 pub candidate: Candidate<'db>,
75 pub is_visible: bool,
76}
77
78#[derive(Debug, Clone)]
79pub struct Candidate<'db> {
80 pub item: CandidateId,
81 pub kind: CandidateKind<'db>,
82}
83
84#[derive(Debug, Clone)]
85pub enum CandidateKind<'db> {
86 InherentImplCandidate { impl_def_id: ImplId, receiver_steps: usize },
87 ObjectCandidate(PolyTraitRef<'db>),
88 TraitCandidate(PolyTraitRef<'db>),
89 WhereClauseCandidate(PolyTraitRef<'db>),
90}
91
92#[derive(Debug, PartialEq, Eq, Copy, Clone)]
93enum ProbeResult {
94 NoMatch,
95 Match,
96}
97
98#[derive(Debug, PartialEq, Copy, Clone)]
111pub enum AutorefOrPtrAdjustment {
112 Autoref {
115 mutbl: Mutability,
116
117 unsize: bool,
120 },
121 ToConstPtr,
123}
124
125impl AutorefOrPtrAdjustment {
126 fn get_unsize(&self) -> bool {
127 match self {
128 AutorefOrPtrAdjustment::Autoref { mutbl: _, unsize } => *unsize,
129 AutorefOrPtrAdjustment::ToConstPtr => false,
130 }
131 }
132}
133
134#[derive(Debug)]
138struct PickConstraintsForShadowed {
139 autoderefs: usize,
140 receiver_steps: Option<usize>,
141 def_id: CandidateId,
142}
143
144impl PickConstraintsForShadowed {
145 fn may_shadow_based_on_autoderefs(&self, autoderefs: usize) -> bool {
146 autoderefs == self.autoderefs
147 }
148
149 fn candidate_may_shadow(&self, candidate: &Candidate<'_>) -> bool {
150 candidate.item != self.def_id
152 && match candidate.kind {
156 CandidateKind::InherentImplCandidate { receiver_steps, .. } => match self.receiver_steps {
157 Some(shadowed_receiver_steps) => receiver_steps > shadowed_receiver_steps,
158 _ => false
159 },
160 _ => false
161 }
162 }
163}
164
165#[derive(Debug, Clone)]
166pub struct Pick<'db> {
167 pub item: CandidateId,
168 pub kind: PickKind<'db>,
169
170 pub autoderefs: usize,
175
176 pub autoref_or_ptr_adjustment: Option<AutorefOrPtrAdjustment>,
179 pub self_ty: Ty<'db>,
180
181 pub receiver_steps: Option<usize>,
185
186 pub shadowed_candidates: Vec<CandidateId>,
188}
189
190#[derive(Clone, Debug, PartialEq, Eq)]
191pub enum PickKind<'db> {
192 InherentImplPick(ImplId),
193 ObjectPick(TraitId),
194 TraitPick(TraitId),
195 WhereClausePick(
196 PolyTraitRef<'db>,
198 ),
199}
200
201pub(crate) type PickResult<'db> = Result<Pick<'db>, MethodError<'db>>;
202
203#[derive(PartialEq, Eq, Copy, Clone, Debug)]
204pub enum Mode {
205 MethodCall,
209 Path,
213}
214
215#[derive(Debug, Clone)]
216pub struct CandidateStep<'db> {
217 pub self_ty: Canonical<'db, QueryResponse<'db, Ty<'db>>>,
218 pub self_ty_is_opaque: bool,
219 pub autoderefs: usize,
220 pub from_unsafe_deref: bool,
226 pub unsize: bool,
227 pub reachable_via_deref: bool,
236}
237
238#[derive(Clone, Debug)]
239struct MethodAutoderefStepsResult<'db> {
240 pub steps: SmallVec<[CandidateStep<'db>; 3]>,
243 pub opt_bad_ty: Option<MethodAutoderefBadTy<'db>>,
245 pub reached_recursion_limit: bool,
248}
249
250#[derive(Debug, Clone)]
251struct MethodAutoderefBadTy<'db> {
252 pub reached_raw_pointer: bool,
253 pub ty: Canonical<'db, QueryResponse<'db, Ty<'db>>>,
254}
255
256impl<'a, 'db> MethodResolutionContext<'a, 'db> {
257 #[instrument(level = "debug", skip(self))]
258 pub fn probe_for_name(&self, mode: Mode, item_name: Name, self_ty: Ty<'db>) -> PickResult<'db> {
259 self.probe_op(mode, self_ty, ProbeForNameChoice { private_candidate: None, item_name })
260 }
261
262 #[instrument(level = "debug", skip(self))]
263 pub fn probe_all(
264 &self,
265 mode: Mode,
266 self_ty: Ty<'db>,
267 ) -> impl Iterator<Item = CandidateWithPrivate<'db>> {
268 self.probe_op(mode, self_ty, ProbeAllChoice::new()).candidates.into_inner().into_values()
269 }
270
271 fn probe_op<Choice: ProbeChoice<'db>>(
272 &self,
273 mode: Mode,
274 self_ty: Ty<'db>,
275 choice: Choice,
276 ) -> Choice::FinalChoice {
277 let mut orig_values = OriginalQueryValues::default();
278 let query_input = self.infcx.canonicalize_query(self_ty, &mut orig_values);
279 let steps = match mode {
280 Mode::MethodCall => self.method_autoderef_steps(&query_input),
281 Mode::Path => self.infcx.probe(|_| {
282 let infcx = self.infcx;
288 let (self_ty, var_values) =
289 infcx.instantiate_canonical(self.call_span, &query_input);
290 debug!(?self_ty, ?query_input, "probe_op: Mode::Path");
291 let prev_opaque_entries =
292 self.infcx.inner.borrow_mut().opaque_types().num_entries();
293 MethodAutoderefStepsResult {
294 steps: smallvec![CandidateStep {
295 self_ty: self.infcx.make_query_response_ignoring_pending_obligations(
296 var_values,
297 self_ty,
298 prev_opaque_entries
299 ),
300 self_ty_is_opaque: false,
301 autoderefs: 0,
302 from_unsafe_deref: false,
303 unsize: false,
304 reachable_via_deref: true,
305 }],
306 opt_bad_ty: None,
307 reached_recursion_limit: false,
308 }
309 }),
310 };
311
312 if steps.reached_recursion_limit {
313 }
315
316 if let Some(bad_ty) = &steps.opt_bad_ty {
319 if bad_ty.reached_raw_pointer
320 && !self.features.arbitrary_self_types_pointers
321 && self.edition.at_least_2018()
322 {
323 } else {
336 let ty = &bad_ty.ty;
340 let ty = self
341 .infcx
342 .instantiate_query_response_and_region_obligations(
343 &ObligationCause::new(self.receiver_span),
344 self.param_env,
345 &orig_values,
346 ty,
347 )
348 .unwrap_or_else(|_| panic!("instantiating {:?} failed?", ty));
349 let ty = self.infcx.resolve_vars_if_possible(ty.value);
350 match ty.kind() {
351 TyKind::Infer(InferTy::TyVar(_)) => {
352 }
354 TyKind::Error(_) => {}
355 _ => panic!("unexpected bad final type in method autoderef"),
356 };
357 return Choice::final_choice_from_err(MethodError::ErrorReported);
358 }
359 }
360
361 debug!("ProbeContext: steps for self_ty={:?} are {:?}", self_ty, steps);
362
363 self.infcx.probe(|_| {
366 let mut probe_cx = ProbeContext::new(self, mode, &orig_values, &steps.steps, choice);
367
368 probe_cx.assemble_inherent_candidates();
369 probe_cx.assemble_extension_candidates_for_traits_in_scope();
370 Choice::choose(probe_cx)
371 })
372 }
373
374 fn method_autoderef_steps(
375 &self,
376 self_ty: &Canonical<'db, Ty<'db>>,
377 ) -> MethodAutoderefStepsResult<'db> {
378 self.infcx.probe(|_| {
379 debug!("method_autoderef_steps({:?})", self_ty);
380
381 let infcx = self.infcx;
385 let (self_ty, inference_vars) =
386 infcx.instantiate_canonical(self.receiver_span, self_ty);
387 let prev_opaque_entries = infcx.inner.borrow_mut().opaque_types().num_entries();
388
389 let self_ty_is_opaque = |ty: Ty<'_>| {
390 if let TyKind::Infer(InferTy::TyVar(vid)) = ty.kind() {
391 infcx.has_opaques_with_sub_unified_hidden_type(vid)
392 } else {
393 false
394 }
395 };
396
397 let mut autoderef_via_deref =
407 Autoderef::new(infcx, self.param_env, self_ty, self.receiver_span)
408 .include_raw_pointers();
409
410 let mut reached_raw_pointer = false;
411 let arbitrary_self_types_enabled =
412 self.features.arbitrary_self_types || self.features.arbitrary_self_types_pointers;
413 let (mut steps, reached_recursion_limit) = if arbitrary_self_types_enabled {
414 let reachable_via_deref =
415 autoderef_via_deref.by_ref().map(|_| true).chain(std::iter::repeat(false));
416
417 let mut autoderef_via_receiver =
418 Autoderef::new(infcx, self.param_env, self_ty, self.receiver_span)
419 .include_raw_pointers()
420 .use_receiver_trait();
421 let steps = autoderef_via_receiver
422 .by_ref()
423 .zip(reachable_via_deref)
424 .map(|((ty, d), reachable_via_deref)| {
425 let step = CandidateStep {
426 self_ty: infcx.make_query_response_ignoring_pending_obligations(
427 inference_vars,
428 ty,
429 prev_opaque_entries,
430 ),
431 self_ty_is_opaque: self_ty_is_opaque(ty),
432 autoderefs: d,
433 from_unsafe_deref: reached_raw_pointer,
434 unsize: false,
435 reachable_via_deref,
436 };
437 if ty.is_raw_ptr() {
438 reached_raw_pointer = true;
440 }
441 step
442 })
443 .collect::<SmallVec<[_; _]>>();
444 (steps, autoderef_via_receiver.reached_recursion_limit())
445 } else {
446 let steps = autoderef_via_deref
447 .by_ref()
448 .map(|(ty, d)| {
449 let step = CandidateStep {
450 self_ty: infcx.make_query_response_ignoring_pending_obligations(
451 inference_vars,
452 ty,
453 prev_opaque_entries,
454 ),
455 self_ty_is_opaque: self_ty_is_opaque(ty),
456 autoderefs: d,
457 from_unsafe_deref: reached_raw_pointer,
458 unsize: false,
459 reachable_via_deref: true,
460 };
461 if ty.is_raw_ptr() {
462 reached_raw_pointer = true;
464 }
465 step
466 })
467 .collect();
468 (steps, autoderef_via_deref.reached_recursion_limit())
469 };
470 let final_ty = autoderef_via_deref.final_ty();
471 let opt_bad_ty = match final_ty.kind() {
472 TyKind::Infer(InferTy::TyVar(_)) if !self_ty_is_opaque(final_ty) => {
473 Some(MethodAutoderefBadTy {
474 reached_raw_pointer,
475 ty: infcx.make_query_response_ignoring_pending_obligations(
476 inference_vars,
477 final_ty,
478 prev_opaque_entries,
479 ),
480 })
481 }
482 TyKind::Error(_) => Some(MethodAutoderefBadTy {
483 reached_raw_pointer,
484 ty: infcx.make_query_response_ignoring_pending_obligations(
485 inference_vars,
486 final_ty,
487 prev_opaque_entries,
488 ),
489 }),
490 TyKind::Array(elem_ty, _) => {
491 let autoderefs = steps.iter().filter(|s| s.reachable_via_deref).count() - 1;
492 steps.push(CandidateStep {
493 self_ty: infcx.make_query_response_ignoring_pending_obligations(
494 inference_vars,
495 Ty::new_slice(infcx.interner, elem_ty),
496 prev_opaque_entries,
497 ),
498 self_ty_is_opaque: false,
499 autoderefs,
500 from_unsafe_deref: reached_raw_pointer,
503 unsize: true,
504 reachable_via_deref: true, });
507
508 None
509 }
510 _ => None,
511 };
512
513 debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
514 MethodAutoderefStepsResult { steps, opt_bad_ty, reached_recursion_limit }
515 })
516 }
517}
518
519trait ProbeChoice<'db>: Sized {
520 type Choice;
521 type FinalChoice;
522
523 fn with_impl_or_trait_item<'a>(
527 this: &mut ProbeContext<'a, 'db, Self>,
528 items: &[(Name, AssocItemId)],
529 callback: impl FnMut(&mut ProbeContext<'a, 'db, Self>, CandidateId),
530 );
531
532 fn consider_candidates(
533 this: &ProbeContext<'_, 'db, Self>,
534 self_ty: Ty<'db>,
535 candidates: Vec<&Candidate<'db>>,
536 ) -> ControlFlow<Self::Choice>;
537
538 fn consider_private_candidates(
539 this: &mut ProbeContext<'_, 'db, Self>,
540 self_ty: Ty<'db>,
541 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
542 );
543
544 fn map_choice_pick(
545 choice: Self::Choice,
546 f: impl FnOnce(Pick<'db>) -> Pick<'db>,
547 ) -> Self::Choice;
548
549 fn check_by_value_method_shadowing(
550 this: &mut ProbeContext<'_, 'db, Self>,
551 by_value_pick: &Self::Choice,
552 step: &CandidateStep<'db>,
553 self_ty: Ty<'db>,
554 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
555 ) -> ControlFlow<Self::Choice>;
556
557 fn check_autorefed_method_shadowing(
558 this: &mut ProbeContext<'_, 'db, Self>,
559 autoref_pick: &Self::Choice,
560 step: &CandidateStep<'db>,
561 self_ty: Ty<'db>,
562 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
563 ) -> ControlFlow<Self::Choice>;
564
565 fn final_choice_from_err(err: MethodError<'db>) -> Self::FinalChoice;
566
567 fn choose(this: ProbeContext<'_, 'db, Self>) -> Self::FinalChoice;
568}
569
570#[derive(Debug)]
571struct ProbeForNameChoice<'db> {
572 item_name: Name,
573
574 private_candidate: Option<Pick<'db>>,
576}
577
578impl<'db> ProbeChoice<'db> for ProbeForNameChoice<'db> {
579 type Choice = PickResult<'db>;
580 type FinalChoice = PickResult<'db>;
581
582 fn with_impl_or_trait_item<'a>(
583 this: &mut ProbeContext<'a, 'db, Self>,
584 items: &[(Name, AssocItemId)],
585 mut callback: impl FnMut(&mut ProbeContext<'a, 'db, Self>, CandidateId),
586 ) {
587 let item = items
588 .iter()
589 .filter_map(|(name, id)| {
590 let id = match *id {
591 AssocItemId::FunctionId(id) => id.into(),
592 AssocItemId::ConstId(id) => id.into(),
593 AssocItemId::TypeAliasId(_) => return None,
594 };
595 Some((name, id))
596 })
597 .find(|(name, _)| **name == this.choice.item_name)
598 .map(|(_, id)| id)
599 .filter(|id| this.mode == Mode::Path || matches!(id, CandidateId::FunctionId(_)));
600 if let Some(item) = item {
601 callback(this, item);
602 }
603 }
604
605 fn consider_candidates(
606 this: &ProbeContext<'_, 'db, Self>,
607 self_ty: Ty<'db>,
608 mut applicable_candidates: Vec<&Candidate<'db>>,
609 ) -> ControlFlow<Self::Choice> {
610 if applicable_candidates.len() > 1
611 && let Some(pick) =
612 this.collapse_candidates_to_trait_pick(self_ty, &applicable_candidates)
613 {
614 return ControlFlow::Break(Ok(pick));
615 }
616
617 if applicable_candidates.len() > 1 {
618 if this.ctx.features.supertrait_item_shadowing
622 && let Some(pick) =
623 this.collapse_candidates_to_subtrait_pick(self_ty, &applicable_candidates)
624 {
625 return ControlFlow::Break(Ok(pick));
626 }
627
628 let sources =
629 applicable_candidates.iter().map(|p| this.candidate_source(p, self_ty)).collect();
630 return ControlFlow::Break(Err(MethodError::Ambiguity(sources)));
631 }
632
633 match applicable_candidates.pop() {
634 Some(probe) => ControlFlow::Break(Ok(probe.to_unadjusted_pick(self_ty))),
635 None => ControlFlow::Continue(()),
636 }
637 }
638
639 fn consider_private_candidates(
640 this: &mut ProbeContext<'_, 'db, Self>,
641 self_ty: Ty<'db>,
642 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
643 ) {
644 if this.choice.private_candidate.is_none()
645 && let ControlFlow::Break(Ok(pick)) = this.consider_candidates(
646 self_ty,
647 instantiate_self_ty_obligations,
648 &this.private_candidates,
649 None,
650 )
651 {
652 this.choice.private_candidate = Some(pick);
653 }
654 }
655
656 fn map_choice_pick(
657 choice: Self::Choice,
658 f: impl FnOnce(Pick<'db>) -> Pick<'db>,
659 ) -> Self::Choice {
660 choice.map(f)
661 }
662
663 fn check_by_value_method_shadowing(
664 this: &mut ProbeContext<'_, 'db, Self>,
665 by_value_pick: &Self::Choice,
666 step: &CandidateStep<'db>,
667 self_ty: Ty<'db>,
668 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
669 ) -> ControlFlow<Self::Choice> {
670 if let Ok(by_value_pick) = by_value_pick
671 && matches!(by_value_pick.kind, PickKind::InherentImplPick(_))
672 {
673 for mutbl in [Mutability::Not, Mutability::Mut] {
674 if let Err(e) = this.check_for_shadowed_autorefd_method(
675 by_value_pick,
676 step,
677 self_ty,
678 instantiate_self_ty_obligations,
679 mutbl,
680 ) {
681 return ControlFlow::Break(Err(e));
682 }
683 }
684 }
685 ControlFlow::Continue(())
686 }
687
688 fn check_autorefed_method_shadowing(
689 this: &mut ProbeContext<'_, 'db, Self>,
690 autoref_pick: &Self::Choice,
691 step: &CandidateStep<'db>,
692 self_ty: Ty<'db>,
693 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
694 ) -> ControlFlow<Self::Choice> {
695 if let Ok(autoref_pick) = autoref_pick.as_ref() {
696 if matches!(autoref_pick.kind, PickKind::InherentImplPick(_))
698 && let Err(e) = this.check_for_shadowed_autorefd_method(
699 autoref_pick,
700 step,
701 self_ty,
702 instantiate_self_ty_obligations,
703 Mutability::Mut,
704 )
705 {
706 return ControlFlow::Break(Err(e));
707 }
708 }
709 ControlFlow::Continue(())
710 }
711
712 fn final_choice_from_err(err: MethodError<'db>) -> Self::FinalChoice {
713 Err(err)
714 }
715
716 fn choose(this: ProbeContext<'_, 'db, Self>) -> Self::FinalChoice {
717 this.pick()
718 }
719}
720
721#[derive(Debug)]
722struct ProbeAllChoice<'db> {
723 candidates: RefCell<FxIndexMap<CandidateId, CandidateWithPrivate<'db>>>,
724 considering_visible_candidates: bool,
725}
726
727impl ProbeAllChoice<'_> {
728 fn new() -> Self {
729 Self { candidates: RefCell::default(), considering_visible_candidates: true }
730 }
731}
732
733impl<'db> ProbeChoice<'db> for ProbeAllChoice<'db> {
734 type Choice = Infallible;
735 type FinalChoice = Self;
736
737 fn with_impl_or_trait_item<'a>(
738 this: &mut ProbeContext<'a, 'db, Self>,
739 items: &[(Name, AssocItemId)],
740 mut callback: impl FnMut(&mut ProbeContext<'a, 'db, Self>, CandidateId),
741 ) {
742 let mode = this.mode;
743 items
744 .iter()
745 .filter_map(|(_, id)| is_relevant_kind_for_mode(mode, *id))
746 .for_each(|id| callback(this, id));
747 }
748
749 fn consider_candidates(
750 this: &ProbeContext<'_, 'db, Self>,
751 _self_ty: Ty<'db>,
752 candidates: Vec<&Candidate<'db>>,
753 ) -> ControlFlow<Self::Choice> {
754 let is_visible = this.choice.considering_visible_candidates;
755 let mut all_candidates = this.choice.candidates.borrow_mut();
756 for candidate in candidates {
757 all_candidates
760 .entry(candidate.item)
761 .or_insert(CandidateWithPrivate { candidate: candidate.clone(), is_visible });
762 }
763 ControlFlow::Continue(())
764 }
765
766 fn consider_private_candidates(
767 this: &mut ProbeContext<'_, 'db, Self>,
768 self_ty: Ty<'db>,
769 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
770 ) {
771 this.choice.considering_visible_candidates = false;
772 let ControlFlow::Continue(()) = this.consider_candidates(
773 self_ty,
774 instantiate_self_ty_obligations,
775 &this.private_candidates,
776 None,
777 );
778 this.choice.considering_visible_candidates = true;
779 }
780
781 fn map_choice_pick(
782 choice: Self::Choice,
783 _f: impl FnOnce(Pick<'db>) -> Pick<'db>,
784 ) -> Self::Choice {
785 choice
786 }
787
788 fn check_by_value_method_shadowing(
789 _this: &mut ProbeContext<'_, 'db, Self>,
790 _by_value_pick: &Self::Choice,
791 _step: &CandidateStep<'db>,
792 _self_ty: Ty<'db>,
793 _instantiate_self_ty_obligations: &[PredicateObligation<'db>],
794 ) -> ControlFlow<Self::Choice> {
795 ControlFlow::Continue(())
796 }
797
798 fn check_autorefed_method_shadowing(
799 _this: &mut ProbeContext<'_, 'db, Self>,
800 _autoref_pick: &Self::Choice,
801 _step: &CandidateStep<'db>,
802 _self_ty: Ty<'db>,
803 _instantiate_self_ty_obligations: &[PredicateObligation<'db>],
804 ) -> ControlFlow<Self::Choice> {
805 ControlFlow::Continue(())
806 }
807
808 fn final_choice_from_err(_err: MethodError<'db>) -> Self::FinalChoice {
809 Self::new()
810 }
811
812 fn choose(mut this: ProbeContext<'_, 'db, Self>) -> Self::FinalChoice {
813 let ControlFlow::Continue(()) = this.pick_all_method();
814 this.choice
815 }
816}
817
818impl<'a, 'db, Choice: ProbeChoice<'db>> ProbeContext<'a, 'db, Choice> {
819 fn new(
820 ctx: &'a MethodResolutionContext<'a, 'db>,
821 mode: Mode,
822 orig_steps_var_values: &'a OriginalQueryValues<'db>,
823 steps: &'a [CandidateStep<'db>],
824 choice: Choice,
825 ) -> ProbeContext<'a, 'db, Choice> {
826 ProbeContext {
827 ctx,
828 mode,
829 inherent_candidates: Vec::new(),
830 extension_candidates: Vec::new(),
831 impl_dups: FxHashSet::default(),
832 orig_steps_var_values,
833 steps,
834 private_candidates: Vec::new(),
835 static_candidates: Vec::new(),
836 choice,
837 }
838 }
839
840 #[inline]
841 fn db(&self) -> &'db dyn HirDatabase {
842 self.ctx.infcx.interner.db
843 }
844
845 #[inline]
846 fn interner(&self) -> DbInterner<'db> {
847 self.ctx.infcx.interner
848 }
849
850 #[inline]
851 fn infcx(&self) -> &'a InferCtxt<'db> {
852 self.ctx.infcx
853 }
854
855 #[inline]
856 fn param_env(&self) -> ParamEnv<'db> {
857 self.ctx.param_env
858 }
859
860 fn variance(&self) -> Variance {
864 match self.mode {
865 Mode::MethodCall => Variance::Covariant,
866 Mode::Path => Variance::Invariant,
867 }
868 }
869
870 fn push_candidate(&mut self, candidate: Candidate<'db>, is_inherent: bool) {
874 let is_accessible = if is_inherent {
875 let candidate_id: AssocItemId = match candidate.item {
876 CandidateId::FunctionId(id) => id.into(),
877 CandidateId::ConstId(id) => id.into(),
878 };
879 let visibility = candidate_id.assoc_visibility(self.db());
880 self.ctx.resolver.is_visible(self.db(), visibility)
881 } else {
882 true
883 };
884 if is_accessible {
885 if is_inherent {
886 self.inherent_candidates.push(candidate);
887 } else {
888 self.extension_candidates.push(candidate);
889 }
890 } else {
891 self.private_candidates.push(candidate);
892 }
893 }
894
895 fn assemble_inherent_candidates(&mut self) {
896 for step in self.steps.iter() {
897 self.assemble_probe(&step.self_ty, step.autoderefs);
898 }
899 }
900
901 #[instrument(level = "debug", skip(self))]
902 fn assemble_probe(
903 &mut self,
904 self_ty: &Canonical<'db, QueryResponse<'db, Ty<'db>>>,
905 receiver_steps: usize,
906 ) {
907 let raw_self_ty = self_ty.value.value;
908 match raw_self_ty.kind() {
909 TyKind::Dynamic(data, ..) => {
910 if let Some(p) = data.principal() {
911 let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
929 self.infcx().instantiate_canonical(self.ctx.call_span, self_ty);
930
931 self.assemble_inherent_candidates_from_object(generalized_self_ty);
932 self.assemble_inherent_impl_candidates_for_type(
933 &SimplifiedType::Trait(p.def_id().0.into()),
934 receiver_steps,
935 );
936 self.assemble_inherent_candidates_for_incoherent_ty(
937 raw_self_ty,
938 receiver_steps,
939 );
940 }
941 }
942 TyKind::Adt(def, _) => {
943 let def_id = def.def_id();
944 self.assemble_inherent_impl_candidates_for_type(
945 &SimplifiedType::Adt(def_id.into()),
946 receiver_steps,
947 );
948 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
949 }
950 TyKind::Foreign(did) => {
951 self.assemble_inherent_impl_candidates_for_type(
952 &SimplifiedType::Foreign(did.0.into()),
953 receiver_steps,
954 );
955 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
956 }
957 TyKind::Param(_) => {
958 self.assemble_inherent_candidates_from_param(raw_self_ty);
959 }
960 TyKind::Bool
961 | TyKind::Char
962 | TyKind::Int(_)
963 | TyKind::Uint(_)
964 | TyKind::Float(_)
965 | TyKind::Str
966 | TyKind::Array(..)
967 | TyKind::Slice(_)
968 | TyKind::RawPtr(_, _)
969 | TyKind::Ref(..)
970 | TyKind::Never
971 | TyKind::Tuple(..) => {
972 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps)
973 }
974 _ => {}
975 }
976 }
977
978 fn assemble_inherent_candidates_for_incoherent_ty(
979 &mut self,
980 self_ty: Ty<'db>,
981 receiver_steps: usize,
982 ) {
983 let Some(simp) = simplify_type(self.interner(), self_ty, TreatParams::InstantiateWithInfer)
984 else {
985 panic!("unexpected incoherent type: {:?}", self_ty)
986 };
987 with_incoherent_inherent_impls(self.db(), self.ctx.resolver.krate(), &simp, |impls| {
988 for &impl_def_id in impls {
989 self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
990 }
991 });
992 }
993
994 fn assemble_inherent_impl_candidates_for_type(
995 &mut self,
996 self_ty: &SimplifiedType<'db>,
997 receiver_steps: usize,
998 ) {
999 let Some(module) = simplified_type_module(self.db(), self_ty) else {
1000 return;
1001 };
1002 InherentImpls::for_each_crate_and_block(
1003 self.db(),
1004 module.krate(self.db()),
1005 module.block(self.db()),
1006 &mut |impls| {
1007 for &impl_def_id in impls.for_self_ty(self_ty) {
1008 self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
1009 }
1010 },
1011 );
1012 }
1013
1014 #[instrument(level = "debug", skip(self))]
1015 fn assemble_inherent_impl_probe(&mut self, impl_def_id: ImplId, receiver_steps: usize) {
1016 if !self.impl_dups.insert(impl_def_id) {
1017 return; }
1019
1020 self.with_impl_item(impl_def_id, |this, item| {
1021 if !this.has_applicable_self(item) {
1022 this.record_static_candidate(CandidateSource::Impl(impl_def_id.into()));
1024 return;
1025 }
1026 this.push_candidate(
1027 Candidate { item, kind: InherentImplCandidate { impl_def_id, receiver_steps } },
1028 true,
1029 );
1030 });
1031 }
1032
1033 #[instrument(level = "debug", skip(self))]
1034 fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'db>) {
1035 let principal = match self_ty.kind() {
1036 TyKind::Dynamic(data, ..) => Some(data),
1037 _ => None,
1038 }
1039 .and_then(|data| data.principal())
1040 .unwrap_or_else(|| {
1041 panic!("non-object {:?} in assemble_inherent_candidates_from_object", self_ty)
1042 });
1043
1044 let trait_ref = principal.with_self_ty(self.interner(), self_ty);
1051 self.assemble_candidates_for_bounds(
1052 elaborate::supertraits(self.interner(), trait_ref),
1053 |this, new_trait_ref, item| {
1054 this.push_candidate(Candidate { item, kind: ObjectCandidate(new_trait_ref) }, true);
1055 },
1056 );
1057 }
1058
1059 #[instrument(level = "debug", skip(self))]
1060 fn assemble_inherent_candidates_from_param(&mut self, param_ty: Ty<'db>) {
1061 debug_assert!(matches!(param_ty.kind(), TyKind::Param(_)));
1062
1063 let interner = self.interner();
1064
1065 let bounds = self.param_env().clauses.iter().filter_map(|predicate| {
1069 let bound_predicate = predicate.kind();
1070 match bound_predicate.skip_binder() {
1071 ClauseKind::Trait(trait_predicate) => DeepRejectCtxt::relate_rigid_rigid(interner)
1072 .types_may_unify(param_ty, trait_predicate.trait_ref.self_ty())
1073 .then(|| bound_predicate.rebind(trait_predicate.trait_ref)),
1074 ClauseKind::RegionOutlives(_)
1075 | ClauseKind::TypeOutlives(_)
1076 | ClauseKind::Projection(_)
1077 | ClauseKind::ConstArgHasType(_, _)
1078 | ClauseKind::WellFormed(_)
1079 | ClauseKind::ConstEvaluatable(_)
1080 | ClauseKind::UnstableFeature(_)
1081 | ClauseKind::HostEffect(..) => None,
1082 }
1083 });
1084
1085 self.assemble_candidates_for_bounds(bounds, |this, poly_trait_ref, item| {
1086 this.push_candidate(
1087 Candidate { item, kind: WhereClauseCandidate(poly_trait_ref) },
1088 true,
1089 );
1090 });
1091 }
1092
1093 fn assemble_candidates_for_bounds<F>(
1096 &mut self,
1097 bounds: impl Iterator<Item = PolyTraitRef<'db>>,
1098 mut mk_cand: F,
1099 ) where
1100 F: for<'b> FnMut(&mut ProbeContext<'b, 'db, Choice>, PolyTraitRef<'db>, CandidateId),
1101 {
1102 for bound_trait_ref in bounds {
1103 debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
1104 self.with_trait_item(bound_trait_ref.def_id().0, |this, item| {
1105 if !this.has_applicable_self(item) {
1106 this.record_static_candidate(CandidateSource::Trait(
1107 bound_trait_ref.def_id().0,
1108 ));
1109 } else {
1110 mk_cand(this, bound_trait_ref, item);
1111 }
1112 });
1113 }
1114 }
1115
1116 #[instrument(level = "debug", skip(self))]
1117 fn assemble_extension_candidates_for_traits_in_scope(&mut self) {
1118 for &trait_did in self.ctx.traits_in_scope {
1119 self.assemble_extension_candidates_for_trait(trait_did);
1120 }
1121 }
1122
1123 #[instrument(level = "debug", skip(self))]
1124 fn assemble_extension_candidates_for_trait(&mut self, trait_def_id: TraitId) {
1125 let mut trait_ref = None;
1126 self.with_trait_item(trait_def_id, |this, item| {
1127 if !this.has_applicable_self(item) {
1129 debug!("method has inapplicable self");
1130 this.record_static_candidate(CandidateSource::Trait(trait_def_id));
1131 return;
1132 }
1133 let trait_ref = *trait_ref.get_or_insert_with(|| {
1134 let trait_args =
1135 this.infcx().fresh_args_for_item(this.ctx.call_span, trait_def_id.into());
1136 TraitRef::new_from_args(this.interner(), trait_def_id.into(), trait_args)
1137 });
1138 this.push_candidate(
1139 Candidate { item, kind: TraitCandidate(Binder::dummy(trait_ref)) },
1140 false,
1141 );
1142 });
1143 }
1144}
1145
1146impl<'a, 'db> ProbeContext<'a, 'db, ProbeForNameChoice<'db>> {
1149 #[instrument(level = "debug", skip(self))]
1150 fn pick(mut self) -> PickResult<'db> {
1151 if let Some(r) = self.pick_core() {
1152 return r;
1153 }
1154
1155 debug!("pick: actual search failed, assemble diagnostics");
1156
1157 if let Some(candidate) = self.choice.private_candidate {
1158 return Err(MethodError::PrivateMatch(candidate));
1159 }
1160
1161 Err(MethodError::NoMatch)
1162 }
1163
1164 fn pick_core(&mut self) -> Option<PickResult<'db>> {
1165 self.pick_all_method().break_value()
1166 }
1167
1168 fn check_for_shadowed_autorefd_method(
1184 &mut self,
1185 possible_shadower: &Pick<'db>,
1186 step: &CandidateStep<'db>,
1187 self_ty: Ty<'db>,
1188 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
1189 mutbl: Mutability,
1190 ) -> Result<(), MethodError<'db>> {
1191 if !self.ctx.features.arbitrary_self_types
1195 && !self.ctx.features.arbitrary_self_types_pointers
1196 {
1197 return Ok(());
1198 }
1199
1200 let pick_constraints = PickConstraintsForShadowed {
1202 autoderefs: possible_shadower.autoderefs,
1204 receiver_steps: possible_shadower.receiver_steps,
1208 def_id: possible_shadower.item,
1211 };
1212 let potentially_shadowed_pick = self.pick_autorefd_method(
1242 step,
1243 self_ty,
1244 instantiate_self_ty_obligations,
1245 mutbl,
1246 Some(&pick_constraints),
1247 );
1248 if let ControlFlow::Break(Ok(possible_shadowed)) = &potentially_shadowed_pick {
1251 let sources = [possible_shadower, possible_shadowed]
1252 .into_iter()
1253 .map(|p| self.candidate_source_from_pick(p))
1254 .collect();
1255 return Err(MethodError::Ambiguity(sources));
1256 }
1257 Ok(())
1258 }
1259}
1260
1261impl<'a, 'db, Choice: ProbeChoice<'db>> ProbeContext<'a, 'db, Choice> {
1262 fn pick_all_method(&mut self) -> ControlFlow<Choice::Choice> {
1263 self.steps
1264 .iter()
1265 .filter(|step| step.reachable_via_deref)
1269 .filter(|step| {
1270 debug!("pick_all_method: step={:?}", step);
1271 !step.self_ty.value.value.references_only_ty_error() && !step.from_unsafe_deref
1274 })
1275 .try_for_each(|step| {
1276 let InferOk { value: self_ty, obligations: instantiate_self_ty_obligations } = self
1277 .infcx()
1278 .instantiate_query_response_and_region_obligations(
1279 &ObligationCause::new(self.ctx.receiver_span),
1280 self.param_env(),
1281 self.orig_steps_var_values,
1282 &step.self_ty,
1283 )
1284 .unwrap_or_else(|_| panic!("{:?} was applicable but now isn't?", step.self_ty));
1285
1286 let by_value_pick =
1287 self.pick_by_value_method(step, self_ty, &instantiate_self_ty_obligations);
1288
1289 if let ControlFlow::Break(by_value_pick) = by_value_pick {
1291 Choice::check_by_value_method_shadowing(
1292 self,
1293 &by_value_pick,
1294 step,
1295 self_ty,
1296 &instantiate_self_ty_obligations,
1297 )?;
1298 return ControlFlow::Break(by_value_pick);
1299 }
1300
1301 if self.mode == Mode::Path {
1302 return ControlFlow::Continue(());
1308 }
1309
1310 let autoref_pick = self.pick_autorefd_method(
1311 step,
1312 self_ty,
1313 &instantiate_self_ty_obligations,
1314 Mutability::Not,
1315 None,
1316 );
1317 if let ControlFlow::Break(autoref_pick) = autoref_pick {
1319 Choice::check_autorefed_method_shadowing(
1320 self,
1321 &autoref_pick,
1322 step,
1323 self_ty,
1324 &instantiate_self_ty_obligations,
1325 )?;
1326 return ControlFlow::Break(autoref_pick);
1327 }
1328
1329 self.pick_autorefd_method(
1353 step,
1354 self_ty,
1355 &instantiate_self_ty_obligations,
1356 Mutability::Mut,
1357 None,
1358 )?;
1359 self.pick_const_ptr_method(step, self_ty, &instantiate_self_ty_obligations)
1360 })
1361 }
1362
1363 fn pick_by_value_method(
1370 &mut self,
1371 step: &CandidateStep<'db>,
1372 self_ty: Ty<'db>,
1373 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
1374 ) -> ControlFlow<Choice::Choice> {
1375 if step.unsize {
1376 return ControlFlow::Continue(());
1377 }
1378
1379 self.pick_method(self_ty, instantiate_self_ty_obligations, None).map_break(|r| {
1380 Choice::map_choice_pick(r, |mut pick| {
1381 pick.autoderefs = step.autoderefs;
1382
1383 match step.self_ty.value.value.kind() {
1384 TyKind::Ref(_, _, mutbl) => {
1386 pick.autoderefs += 1;
1387 pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::Autoref {
1388 mutbl,
1389 unsize: pick.autoref_or_ptr_adjustment.is_some_and(|a| a.get_unsize()),
1390 })
1391 }
1392
1393 _ => (),
1394 }
1395
1396 pick
1397 })
1398 })
1399 }
1400
1401 fn pick_autorefd_method(
1402 &mut self,
1403 step: &CandidateStep<'db>,
1404 self_ty: Ty<'db>,
1405 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
1406 mutbl: Mutability,
1407 pick_constraints: Option<&PickConstraintsForShadowed>,
1408 ) -> ControlFlow<Choice::Choice> {
1409 let interner = self.interner();
1410
1411 if let Some(pick_constraints) = pick_constraints
1412 && !pick_constraints.may_shadow_based_on_autoderefs(step.autoderefs)
1413 {
1414 return ControlFlow::Continue(());
1415 }
1416
1417 let region = Region::new_erased(interner);
1419
1420 let autoref_ty = Ty::new_ref(interner, region, self_ty, mutbl);
1421 self.pick_method(autoref_ty, instantiate_self_ty_obligations, pick_constraints).map_break(
1422 |r| {
1423 Choice::map_choice_pick(r, |mut pick| {
1424 pick.autoderefs = step.autoderefs;
1425 pick.autoref_or_ptr_adjustment =
1426 Some(AutorefOrPtrAdjustment::Autoref { mutbl, unsize: step.unsize });
1427 pick
1428 })
1429 },
1430 )
1431 }
1432
1433 fn pick_const_ptr_method(
1437 &mut self,
1438 step: &CandidateStep<'db>,
1439 self_ty: Ty<'db>,
1440 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
1441 ) -> ControlFlow<Choice::Choice> {
1442 if step.unsize {
1444 return ControlFlow::Continue(());
1445 }
1446
1447 let TyKind::RawPtr(ty, Mutability::Mut) = self_ty.kind() else {
1448 return ControlFlow::Continue(());
1449 };
1450
1451 let const_ptr_ty = Ty::new_ptr(self.interner(), ty, Mutability::Not);
1452 self.pick_method(const_ptr_ty, instantiate_self_ty_obligations, None).map_break(|r| {
1453 Choice::map_choice_pick(r, |mut pick| {
1454 pick.autoderefs = step.autoderefs;
1455 pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::ToConstPtr);
1456 pick
1457 })
1458 })
1459 }
1460
1461 fn pick_method(
1462 &mut self,
1463 self_ty: Ty<'db>,
1464 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
1465 pick_constraints: Option<&PickConstraintsForShadowed>,
1466 ) -> ControlFlow<Choice::Choice> {
1467 debug!("pick_method(self_ty={:?})", self_ty);
1468
1469 for (kind, candidates) in
1470 [("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1471 {
1472 debug!("searching {} candidates", kind);
1473 self.consider_candidates(
1474 self_ty,
1475 instantiate_self_ty_obligations,
1476 candidates,
1477 pick_constraints,
1478 )?;
1479 }
1480
1481 Choice::consider_private_candidates(self, self_ty, instantiate_self_ty_obligations);
1482
1483 ControlFlow::Continue(())
1484 }
1485
1486 fn consider_candidates(
1487 &self,
1488 self_ty: Ty<'db>,
1489 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
1490 candidates: &[Candidate<'db>],
1491 pick_constraints: Option<&PickConstraintsForShadowed>,
1492 ) -> ControlFlow<Choice::Choice> {
1493 let applicable_candidates: Vec<_> = candidates
1494 .iter()
1495 .filter(|candidate| {
1496 pick_constraints
1497 .map(|pick_constraints| pick_constraints.candidate_may_shadow(candidate))
1498 .unwrap_or(true)
1499 })
1500 .filter(|probe| {
1501 self.consider_probe(self_ty, instantiate_self_ty_obligations, probe)
1502 != ProbeResult::NoMatch
1503 })
1504 .collect();
1505
1506 debug!("applicable_candidates: {:?}", applicable_candidates);
1507
1508 Choice::consider_candidates(self, self_ty, applicable_candidates)
1509 }
1510
1511 fn select_trait_candidate(
1512 &self,
1513 trait_ref: TraitRef<'db>,
1514 ) -> SelectionResult<'db, Selection<'db>> {
1515 let obligation = Obligation::new(
1516 self.interner(),
1517 ObligationCause::new(self.ctx.call_span),
1518 self.param_env(),
1519 trait_ref,
1520 );
1521 self.infcx().select(&obligation)
1522 }
1523
1524 fn candidate_source(&self, candidate: &Candidate<'db>, self_ty: Ty<'db>) -> CandidateSource {
1527 match candidate.kind {
1528 InherentImplCandidate { impl_def_id, .. } => CandidateSource::Impl(impl_def_id.into()),
1529 ObjectCandidate(trait_ref) | WhereClauseCandidate(trait_ref) => {
1530 CandidateSource::Trait(trait_ref.def_id().0)
1531 }
1532 TraitCandidate(trait_ref) => self.infcx().probe(|_| {
1533 let trait_ref = self.infcx().instantiate_binder_with_fresh_vars(
1534 self.ctx.call_span,
1535 BoundRegionConversionTime::FnCall,
1536 trait_ref,
1537 );
1538 let (xform_self_ty, _) = self.xform_self_ty(
1539 candidate.item,
1540 trait_ref.self_ty(),
1541 trait_ref.args.as_slice(),
1542 );
1543 let _ = self
1546 .infcx()
1547 .at(&ObligationCause::new(self.ctx.call_span), self.param_env())
1548 .sup(xform_self_ty, self_ty);
1549 match self.select_trait_candidate(trait_ref) {
1550 Ok(Some(ImplSource::UserDefined(ref impl_data))) => {
1551 CandidateSource::Impl(impl_data.impl_def_id)
1554 }
1555 _ => CandidateSource::Trait(trait_ref.def_id.0),
1556 }
1557 }),
1558 }
1559 }
1560
1561 fn candidate_source_from_pick(&self, pick: &Pick<'db>) -> CandidateSource {
1562 match pick.kind {
1563 InherentImplPick(impl_) => CandidateSource::Impl(impl_.into()),
1564 ObjectPick(trait_) | TraitPick(trait_) => CandidateSource::Trait(trait_),
1565 WhereClausePick(trait_ref) => CandidateSource::Trait(trait_ref.skip_binder().def_id.0),
1566 }
1567 }
1568
1569 #[instrument(level = "debug", skip(self), ret)]
1570 fn consider_probe(
1571 &self,
1572 self_ty: Ty<'db>,
1573 instantiate_self_ty_obligations: &[PredicateObligation<'db>],
1574 probe: &Candidate<'db>,
1575 ) -> ProbeResult {
1576 self.infcx().probe(|_| {
1577 let mut result = ProbeResult::Match;
1578 let cause = &ObligationCause::new(self.ctx.call_span);
1579 let mut ocx = ObligationCtxt::new(self.infcx());
1580
1581 ocx.register_obligations(instantiate_self_ty_obligations.iter().cloned());
1589 let errors = ocx.try_evaluate_obligations();
1590 if !errors.is_empty() {
1591 unreachable!("unexpected autoderef error {errors:?}");
1592 }
1593
1594 let mut trait_predicate = None;
1595 let (xform_self_ty, xform_ret_ty);
1596
1597 match probe.kind {
1598 InherentImplCandidate { impl_def_id, .. } => {
1599 let impl_args =
1600 self.infcx().fresh_args_for_item(self.ctx.call_span, impl_def_id.into());
1601 let impl_ty = self
1602 .db()
1603 .impl_self_ty(impl_def_id)
1604 .instantiate(self.interner(), impl_args)
1605 .skip_norm_wip();
1606 (xform_self_ty, xform_ret_ty) =
1607 self.xform_self_ty(probe.item, impl_ty, impl_args.as_slice());
1608 match ocx.relate(
1609 cause,
1610 self.param_env(),
1611 self.variance(),
1612 self_ty,
1613 xform_self_ty,
1614 ) {
1615 Ok(()) => {}
1616 Err(err) => {
1617 debug!("--> cannot relate self-types {:?}", err);
1618 return ProbeResult::NoMatch;
1619 }
1620 }
1621 let impl_bounds = GenericPredicates::query_all(self.db(), impl_def_id.into());
1623 let impl_bounds = clauses_as_obligations(
1624 impl_bounds
1625 .iter_instantiated(self.interner(), impl_args.as_slice())
1626 .map(Unnormalized::skip_norm_wip),
1627 ObligationCause::new(self.ctx.call_span),
1628 self.param_env(),
1629 );
1630 ocx.register_obligations(impl_bounds);
1632 }
1633 TraitCandidate(poly_trait_ref) => {
1634 if self_ty.is_array() && !self.ctx.edition.at_least_2021() {
1637 let trait_signature =
1638 TraitSignature::of(self.db(), poly_trait_ref.def_id().0);
1639 if trait_signature
1640 .flags
1641 .contains(TraitFlags::SKIP_ARRAY_DURING_METHOD_DISPATCH)
1642 {
1643 return ProbeResult::NoMatch;
1644 }
1645 }
1646
1647 if self_ty.boxed_ty().is_some_and(Ty::is_slice)
1650 && !self.ctx.edition.at_least_2024()
1651 {
1652 let trait_signature =
1653 TraitSignature::of(self.db(), poly_trait_ref.def_id().0);
1654 if trait_signature
1655 .flags
1656 .contains(TraitFlags::SKIP_BOXED_SLICE_DURING_METHOD_DISPATCH)
1657 {
1658 return ProbeResult::NoMatch;
1659 }
1660 }
1661
1662 let trait_ref = self.infcx().instantiate_binder_with_fresh_vars(
1663 self.ctx.call_span,
1664 BoundRegionConversionTime::FnCall,
1665 poly_trait_ref,
1666 );
1667 (xform_self_ty, xform_ret_ty) = self.xform_self_ty(
1668 probe.item,
1669 trait_ref.self_ty(),
1670 trait_ref.args.as_slice(),
1671 );
1672 match ocx.relate(
1673 cause,
1674 self.param_env(),
1675 self.variance(),
1676 self_ty,
1677 xform_self_ty,
1678 ) {
1679 Ok(()) => {}
1680 Err(err) => {
1681 debug!("--> cannot relate self-types {:?}", err);
1682 return ProbeResult::NoMatch;
1683 }
1684 }
1685 let obligation = Obligation::new(
1686 self.interner(),
1687 *cause,
1688 self.param_env(),
1689 Binder::dummy(trait_ref),
1690 );
1691
1692 ocx.register_obligation(obligation);
1694
1695 trait_predicate = Some(trait_ref.upcast(self.interner()));
1696 }
1697 ObjectCandidate(poly_trait_ref) | WhereClauseCandidate(poly_trait_ref) => {
1698 let trait_ref = self.infcx().instantiate_binder_with_fresh_vars(
1699 self.ctx.call_span,
1700 BoundRegionConversionTime::FnCall,
1701 poly_trait_ref,
1702 );
1703 (xform_self_ty, xform_ret_ty) = self.xform_self_ty(
1704 probe.item,
1705 trait_ref.self_ty(),
1706 trait_ref.args.as_slice(),
1707 );
1708
1709 if matches!(probe.kind, WhereClauseCandidate(_)) {
1710 match ocx.structurally_normalize_ty(
1714 cause,
1715 self.param_env(),
1716 trait_ref.self_ty(),
1717 ) {
1718 Ok(ty) => {
1719 if !matches!(ty.kind(), TyKind::Param(_)) {
1720 debug!("--> not a param ty: {xform_self_ty:?}");
1721 return ProbeResult::NoMatch;
1722 }
1723 }
1724 Err(errors) => {
1725 debug!("--> cannot relate self-types {:?}", errors);
1726 return ProbeResult::NoMatch;
1727 }
1728 }
1729 }
1730
1731 match ocx.relate(
1732 cause,
1733 self.param_env(),
1734 self.variance(),
1735 self_ty,
1736 xform_self_ty,
1737 ) {
1738 Ok(()) => {}
1739 Err(err) => {
1740 debug!("--> cannot relate self-types {:?}", err);
1741 return ProbeResult::NoMatch;
1742 }
1743 }
1744 }
1745 }
1746
1747 if let Some(xform_ret_ty) = xform_ret_ty {
1759 ocx.register_obligation(Obligation::new(
1760 self.interner(),
1761 *cause,
1762 self.param_env(),
1763 ClauseKind::WellFormed(xform_ret_ty.into()),
1764 ));
1765 }
1766
1767 if !ocx.try_evaluate_obligations().is_empty() {
1768 result = ProbeResult::NoMatch;
1769 }
1770
1771 if self.should_reject_candidate_due_to_opaque_treated_as_rigid(trait_predicate) {
1772 result = ProbeResult::NoMatch;
1773 }
1774
1775 result
1781 })
1782 }
1783
1784 #[instrument(level = "debug", skip(self), ret)]
1799 fn should_reject_candidate_due_to_opaque_treated_as_rigid(
1800 &self,
1801 trait_predicate: Option<Predicate<'db>>,
1802 ) -> bool {
1803 if let Some(predicate) = trait_predicate {
1815 let goal = Goal { param_env: self.param_env(), predicate };
1816 if !self.infcx().goal_may_hold_opaque_types_jank(goal) {
1817 return true;
1818 }
1819 }
1820
1821 for step in self.steps {
1824 if step.self_ty_is_opaque {
1825 debug!(?step.autoderefs, ?step.self_ty, "self_type_is_opaque");
1826 let constrained_opaque = self.infcx().probe(|_| {
1827 let Ok(ok) = self.infcx().instantiate_query_response_and_region_obligations(
1832 &ObligationCause::new(self.ctx.receiver_span),
1833 self.param_env(),
1834 self.orig_steps_var_values,
1835 &step.self_ty,
1836 ) else {
1837 debug!("failed to instantiate self_ty");
1838 return false;
1839 };
1840 let mut ocx = ObligationCtxt::new(self.infcx());
1841 let self_ty = ocx.register_infer_ok_obligations(ok);
1842 if !ocx.try_evaluate_obligations().is_empty() {
1843 debug!("failed to prove instantiate self_ty obligations");
1844 return false;
1845 }
1846
1847 !self.infcx().resolve_vars_if_possible(self_ty).is_ty_var()
1848 });
1849 if constrained_opaque {
1850 debug!("opaque type has been constrained");
1851 return true;
1852 }
1853 }
1854 }
1855
1856 false
1857 }
1858
1859 fn collapse_candidates_to_trait_pick(
1877 &self,
1878 self_ty: Ty<'db>,
1879 probes: &[&Candidate<'db>],
1880 ) -> Option<Pick<'db>> {
1881 let ItemContainerId::TraitId(container) = probes[0].item.container(self.db()) else {
1883 return None;
1884 };
1885 for p in &probes[1..] {
1886 let ItemContainerId::TraitId(p_container) = p.item.container(self.db()) else {
1887 return None;
1888 };
1889 if p_container != container {
1890 return None;
1891 }
1892 }
1893
1894 Some(Pick {
1897 item: probes[0].item,
1898 kind: TraitPick(container),
1899 autoderefs: 0,
1900 autoref_or_ptr_adjustment: None,
1901 self_ty,
1902 receiver_steps: None,
1903 shadowed_candidates: vec![],
1904 })
1905 }
1906
1907 fn collapse_candidates_to_subtrait_pick(
1913 &self,
1914 self_ty: Ty<'db>,
1915 probes: &[&Candidate<'db>],
1916 ) -> Option<Pick<'db>> {
1917 let mut child_candidate = probes[0];
1918 let ItemContainerId::TraitId(mut child_trait) = child_candidate.item.container(self.db())
1919 else {
1920 return None;
1921 };
1922 let mut supertraits: FxHashSet<_> =
1923 supertrait_def_ids(self.interner(), child_trait.into()).collect();
1924
1925 let mut remaining_candidates: Vec<_> = probes[1..].to_vec();
1926 while !remaining_candidates.is_empty() {
1927 let mut made_progress = false;
1928 let mut next_round = vec![];
1929
1930 for remaining_candidate in remaining_candidates {
1931 let ItemContainerId::TraitId(remaining_trait) =
1932 remaining_candidate.item.container(self.db())
1933 else {
1934 return None;
1935 };
1936 if supertraits.contains(&remaining_trait.into()) {
1937 made_progress = true;
1938 continue;
1939 }
1940
1941 let remaining_trait_supertraits: FxHashSet<_> =
1947 supertrait_def_ids(self.interner(), remaining_trait.into()).collect();
1948 if remaining_trait_supertraits.contains(&child_trait.into()) {
1949 child_candidate = remaining_candidate;
1950 child_trait = remaining_trait;
1951 supertraits = remaining_trait_supertraits;
1952 made_progress = true;
1953 continue;
1954 }
1955
1956 next_round.push(remaining_candidate);
1962 }
1963
1964 if made_progress {
1965 remaining_candidates = next_round;
1967 } else {
1968 return None;
1971 }
1972 }
1973
1974 Some(Pick {
1975 item: child_candidate.item,
1976 kind: TraitPick(child_trait),
1977 autoderefs: 0,
1978 autoref_or_ptr_adjustment: None,
1979 self_ty,
1980 shadowed_candidates: probes
1981 .iter()
1982 .map(|c| c.item)
1983 .filter(|item| *item != child_candidate.item)
1984 .collect(),
1985 receiver_steps: None,
1986 })
1987 }
1988
1989 fn has_applicable_self(&self, item: CandidateId) -> bool {
1992 match item {
1998 CandidateId::FunctionId(id) if self.mode == Mode::MethodCall => {
1999 FunctionSignature::of(self.db(), id).has_self_param()
2000 }
2001 _ => true,
2002 }
2003 }
2010
2011 fn record_static_candidate(&mut self, source: CandidateSource) {
2012 self.static_candidates.push(source);
2013 }
2014
2015 #[instrument(level = "debug", skip(self))]
2016 fn xform_self_ty(
2017 &self,
2018 item: CandidateId,
2019 impl_ty: Ty<'db>,
2020 args: &[GenericArg<'db>],
2021 ) -> (Ty<'db>, Option<Ty<'db>>) {
2022 if let CandidateId::FunctionId(item) = item
2023 && self.mode == Mode::MethodCall
2024 {
2025 let sig = self.xform_method_sig(item, args);
2026 (sig.inputs()[0], Some(sig.output()))
2027 } else {
2028 (impl_ty, None)
2029 }
2030 }
2031
2032 #[instrument(level = "debug", skip(self))]
2033 fn xform_method_sig(&self, method: FunctionId, args: &[GenericArg<'db>]) -> FnSig<'db> {
2034 let fn_sig = self.db().callable_item_signature(method.into());
2035 debug!(?fn_sig);
2036
2037 assert!(!args.has_escaping_bound_vars());
2038
2039 let generics = GenericParams::of(self.db(), method.into());
2045
2046 let xform_fn_sig = if generics.is_empty() {
2047 fn_sig.instantiate(self.interner(), args)
2048 } else {
2049 let args = GenericArgs::for_item(
2050 self.interner(),
2051 method.into(),
2052 |param_index, param_id, _, _| {
2053 let i = param_index as usize;
2054 if i < args.len() {
2055 args[i]
2056 } else {
2057 match param_id {
2058 GenericParamId::LifetimeParamId(_) => {
2059 Region::new_erased(self.interner()).into()
2061 }
2062 GenericParamId::TypeParamId(_) => {
2063 self.infcx().next_ty_var(self.ctx.call_span).into()
2064 }
2065 GenericParamId::ConstParamId(_) => {
2066 self.infcx().next_const_var(self.ctx.call_span).into()
2067 }
2068 }
2069 }
2070 },
2071 );
2072 fn_sig.instantiate(self.interner(), args)
2073 };
2074
2075 self.interner().instantiate_bound_regions_with_erased(xform_fn_sig.skip_norm_wip())
2076 }
2077
2078 fn with_impl_item(&mut self, def_id: ImplId, callback: impl FnMut(&mut Self, CandidateId)) {
2079 Choice::with_impl_or_trait_item(self, &def_id.impl_items(self.db()).items, callback)
2080 }
2081
2082 fn with_trait_item(&mut self, def_id: TraitId, callback: impl FnMut(&mut Self, CandidateId)) {
2083 Choice::with_impl_or_trait_item(self, &def_id.trait_items(self.db()).items, callback)
2084 }
2085}
2086
2087fn is_relevant_kind_for_mode(mode: Mode, kind: AssocItemId) -> Option<CandidateId> {
2089 Some(match (mode, kind) {
2090 (Mode::MethodCall, AssocItemId::FunctionId(id)) => id.into(),
2091 (Mode::Path, AssocItemId::ConstId(id)) => id.into(),
2092 (Mode::Path, AssocItemId::FunctionId(id)) => id.into(),
2093 _ => return None,
2094 })
2095}
2096
2097impl<'db> Candidate<'db> {
2098 fn to_unadjusted_pick(&self, self_ty: Ty<'db>) -> Pick<'db> {
2099 Pick {
2100 item: self.item,
2101 kind: match self.kind {
2102 InherentImplCandidate { impl_def_id, .. } => InherentImplPick(impl_def_id),
2103 ObjectCandidate(trait_ref) => ObjectPick(trait_ref.skip_binder().def_id.0),
2104 TraitCandidate(trait_ref) => TraitPick(trait_ref.skip_binder().def_id.0),
2105 WhereClauseCandidate(trait_ref) => {
2106 assert!(
2112 !trait_ref.skip_binder().args.has_infer()
2113 && !trait_ref.skip_binder().args.has_placeholders()
2114 );
2115
2116 WhereClausePick(trait_ref)
2117 }
2118 },
2119 autoderefs: 0,
2120 autoref_or_ptr_adjustment: None,
2121 self_ty,
2122 receiver_steps: match self.kind {
2123 InherentImplCandidate { receiver_steps, .. } => Some(receiver_steps),
2124 _ => None,
2125 },
2126 shadowed_candidates: vec![],
2127 }
2128 }
2129}