1use std::assert_matches::debug_assert_matches;
2use std::cell::{Cell, RefCell};
3use std::cmp::max;
4use std::ops::Deref;
5
6use rustc_attr_parsing::is_doc_alias_attrs_contain_symbol;
7use rustc_data_structures::fx::FxHashSet;
8use rustc_data_structures::sso::SsoHashSet;
9use rustc_errors::Applicability;
10use rustc_hir::def::DefKind;
11use rustc_hir::{self as hir, ExprKind, HirId, Node};
12use rustc_hir_analysis::autoderef::{self, Autoderef};
13use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
14use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, TyCtxtInferExt};
15use rustc_infer::traits::{ObligationCauseCode, PredicateObligation, query};
16use rustc_middle::middle::stability;
17use rustc_middle::ty::elaborate::supertrait_def_ids;
18use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type};
19use rustc_middle::ty::{
20 self, AssocContainer, AssocItem, GenericArgs, GenericArgsRef, GenericParamDefKind, ParamEnvAnd,
21 Ty, TyCtxt, TypeVisitableExt, Upcast,
22};
23use rustc_middle::{bug, span_bug};
24use rustc_session::lint;
25use rustc_span::def_id::{DefId, LocalDefId};
26use rustc_span::edit_distance::{
27 edit_distance_with_substrings, find_best_match_for_name_with_substrings,
28};
29use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
30use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
31use rustc_trait_selection::infer::InferCtxtExt as _;
32use rustc_trait_selection::solve::Goal;
33use rustc_trait_selection::traits::query::CanonicalMethodAutoderefStepsGoal;
34use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
35use rustc_trait_selection::traits::query::method_autoderef::{
36 CandidateStep, MethodAutoderefBadTy, MethodAutoderefStepsResult,
37};
38use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt};
39use smallvec::{SmallVec, smallvec};
40use tracing::{debug, instrument};
41
42use self::CandidateKind::*;
43pub(crate) use self::PickKind::*;
44use super::{CandidateSource, MethodError, NoMatchData, suggest};
45use crate::FnCtxt;
46
47#[derive(Clone, Copy, Debug)]
50pub(crate) struct IsSuggestion(pub bool);
51
52pub(crate) struct ProbeContext<'a, 'tcx> {
53 fcx: &'a FnCtxt<'a, 'tcx>,
54 span: Span,
55 mode: Mode,
56 method_name: Option<Ident>,
57 return_type: Option<Ty<'tcx>>,
58
59 orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
62 steps: &'tcx [CandidateStep<'tcx>],
63
64 inherent_candidates: Vec<Candidate<'tcx>>,
65 extension_candidates: Vec<Candidate<'tcx>>,
66 impl_dups: FxHashSet<DefId>,
67
68 allow_similar_names: bool,
71
72 private_candidates: Vec<Candidate<'tcx>>,
75
76 private_candidate: Cell<Option<(DefKind, DefId)>>,
78
79 static_candidates: RefCell<Vec<CandidateSource>>,
82
83 scope_expr_id: HirId,
84
85 is_suggestion: IsSuggestion,
89}
90
91impl<'a, 'tcx> Deref for ProbeContext<'a, 'tcx> {
92 type Target = FnCtxt<'a, 'tcx>;
93 fn deref(&self) -> &Self::Target {
94 self.fcx
95 }
96}
97
98#[derive(Debug, Clone)]
99pub(crate) struct Candidate<'tcx> {
100 pub(crate) item: ty::AssocItem,
101 pub(crate) kind: CandidateKind<'tcx>,
102 pub(crate) import_ids: SmallVec<[LocalDefId; 1]>,
103}
104
105#[derive(Debug, Clone)]
106pub(crate) enum CandidateKind<'tcx> {
107 InherentImplCandidate { impl_def_id: DefId, receiver_steps: usize },
108 ObjectCandidate(ty::PolyTraitRef<'tcx>),
109 TraitCandidate(ty::PolyTraitRef<'tcx>),
110 WhereClauseCandidate(ty::PolyTraitRef<'tcx>),
111}
112
113#[derive(Debug, PartialEq, Eq, Copy, Clone)]
114enum ProbeResult {
115 NoMatch,
116 BadReturnType,
117 Match,
118}
119
120#[derive(Debug, PartialEq, Copy, Clone)]
133pub(crate) enum AutorefOrPtrAdjustment {
134 Autoref {
137 mutbl: hir::Mutability,
138
139 unsize: bool,
142 },
143 ToConstPtr,
145
146 ReborrowPin(hir::Mutability),
148}
149
150impl AutorefOrPtrAdjustment {
151 fn get_unsize(&self) -> bool {
152 match self {
153 AutorefOrPtrAdjustment::Autoref { mutbl: _, unsize } => *unsize,
154 AutorefOrPtrAdjustment::ToConstPtr => false,
155 AutorefOrPtrAdjustment::ReborrowPin(_) => false,
156 }
157 }
158}
159
160#[derive(Debug)]
162struct PickDiagHints<'a, 'tcx> {
163 unstable_candidates: Option<Vec<(Candidate<'tcx>, Symbol)>>,
165
166 unsatisfied_predicates: &'a mut Vec<(
169 ty::Predicate<'tcx>,
170 Option<ty::Predicate<'tcx>>,
171 Option<ObligationCause<'tcx>>,
172 )>,
173}
174
175#[derive(Debug)]
179struct PickConstraintsForShadowed {
180 autoderefs: usize,
181 receiver_steps: Option<usize>,
182 def_id: DefId,
183}
184
185impl PickConstraintsForShadowed {
186 fn may_shadow_based_on_autoderefs(&self, autoderefs: usize) -> bool {
187 autoderefs == self.autoderefs
188 }
189
190 fn candidate_may_shadow(&self, candidate: &Candidate<'_>) -> bool {
191 candidate.item.def_id != self.def_id
193 && match candidate.kind {
197 CandidateKind::InherentImplCandidate { receiver_steps, .. } => match self.receiver_steps {
198 Some(shadowed_receiver_steps) => receiver_steps > shadowed_receiver_steps,
199 _ => false
200 },
201 _ => false
202 }
203 }
204}
205
206#[derive(Debug, Clone)]
207pub(crate) struct Pick<'tcx> {
208 pub item: ty::AssocItem,
209 pub kind: PickKind<'tcx>,
210 pub import_ids: SmallVec<[LocalDefId; 1]>,
211
212 pub autoderefs: usize,
217
218 pub autoref_or_ptr_adjustment: Option<AutorefOrPtrAdjustment>,
221 pub self_ty: Ty<'tcx>,
222
223 unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
225
226 pub receiver_steps: Option<usize>,
230
231 pub shadowed_candidates: Vec<ty::AssocItem>,
233}
234
235#[derive(Clone, Debug, PartialEq, Eq)]
236pub(crate) enum PickKind<'tcx> {
237 InherentImplPick,
238 ObjectPick,
239 TraitPick,
240 WhereClausePick(
241 ty::PolyTraitRef<'tcx>,
243 ),
244}
245
246pub(crate) type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
247
248#[derive(PartialEq, Eq, Copy, Clone, Debug)]
249pub(crate) enum Mode {
250 MethodCall,
254 Path,
258}
259
260#[derive(PartialEq, Eq, Copy, Clone, Debug)]
261pub(crate) enum ProbeScope {
262 Single(DefId),
264
265 TraitsInScope,
267
268 AllTraits,
270}
271
272impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
273 #[instrument(level = "debug", skip(self, candidate_filter))]
280 pub(crate) fn probe_for_return_type_for_diagnostic(
281 &self,
282 span: Span,
283 mode: Mode,
284 return_type: Ty<'tcx>,
285 self_ty: Ty<'tcx>,
286 scope_expr_id: HirId,
287 candidate_filter: impl Fn(&ty::AssocItem) -> bool,
288 ) -> Vec<ty::AssocItem> {
289 let method_names = self
290 .probe_op(
291 span,
292 mode,
293 None,
294 Some(return_type),
295 IsSuggestion(true),
296 self_ty,
297 scope_expr_id,
298 ProbeScope::AllTraits,
299 |probe_cx| Ok(probe_cx.candidate_method_names(candidate_filter)),
300 )
301 .unwrap_or_default();
302 method_names
303 .iter()
304 .flat_map(|&method_name| {
305 self.probe_op(
306 span,
307 mode,
308 Some(method_name),
309 Some(return_type),
310 IsSuggestion(true),
311 self_ty,
312 scope_expr_id,
313 ProbeScope::AllTraits,
314 |probe_cx| probe_cx.pick(),
315 )
316 .ok()
317 .map(|pick| pick.item)
318 })
319 .collect()
320 }
321
322 #[instrument(level = "debug", skip(self))]
323 pub(crate) fn probe_for_name(
324 &self,
325 mode: Mode,
326 item_name: Ident,
327 return_type: Option<Ty<'tcx>>,
328 is_suggestion: IsSuggestion,
329 self_ty: Ty<'tcx>,
330 scope_expr_id: HirId,
331 scope: ProbeScope,
332 ) -> PickResult<'tcx> {
333 self.probe_op(
334 item_name.span,
335 mode,
336 Some(item_name),
337 return_type,
338 is_suggestion,
339 self_ty,
340 scope_expr_id,
341 scope,
342 |probe_cx| probe_cx.pick(),
343 )
344 }
345
346 #[instrument(level = "debug", skip(self))]
347 pub(crate) fn probe_for_name_many(
348 &self,
349 mode: Mode,
350 item_name: Ident,
351 return_type: Option<Ty<'tcx>>,
352 is_suggestion: IsSuggestion,
353 self_ty: Ty<'tcx>,
354 scope_expr_id: HirId,
355 scope: ProbeScope,
356 ) -> Result<Vec<Candidate<'tcx>>, MethodError<'tcx>> {
357 self.probe_op(
358 item_name.span,
359 mode,
360 Some(item_name),
361 return_type,
362 is_suggestion,
363 self_ty,
364 scope_expr_id,
365 scope,
366 |probe_cx| {
367 Ok(probe_cx
368 .inherent_candidates
369 .into_iter()
370 .chain(probe_cx.extension_candidates)
371 .collect())
372 },
373 )
374 }
375
376 pub(crate) fn probe_op<OP, R>(
377 &'a self,
378 span: Span,
379 mode: Mode,
380 method_name: Option<Ident>,
381 return_type: Option<Ty<'tcx>>,
382 is_suggestion: IsSuggestion,
383 self_ty: Ty<'tcx>,
384 scope_expr_id: HirId,
385 scope: ProbeScope,
386 op: OP,
387 ) -> Result<R, MethodError<'tcx>>
388 where
389 OP: FnOnce(ProbeContext<'_, 'tcx>) -> Result<R, MethodError<'tcx>>,
390 {
391 let mut orig_values = OriginalQueryValues::default();
392 let predefined_opaques_in_body = if self.next_trait_solver() {
393 self.tcx.mk_predefined_opaques_in_body_from_iter(
394 self.inner.borrow_mut().opaque_types().iter_opaque_types().map(|(k, v)| (k, v.ty)),
395 )
396 } else {
397 ty::List::empty()
398 };
399 let value = query::MethodAutoderefSteps { predefined_opaques_in_body, self_ty };
400 let query_input = self
401 .canonicalize_query(ParamEnvAnd { param_env: self.param_env, value }, &mut orig_values);
402
403 let steps = match mode {
404 Mode::MethodCall => self.tcx.method_autoderef_steps(query_input),
405 Mode::Path => self.probe(|_| {
406 let infcx = &self.infcx;
412 let (ParamEnvAnd { param_env: _, value }, var_values) =
413 infcx.instantiate_canonical(span, &query_input.canonical);
414 let query::MethodAutoderefSteps { predefined_opaques_in_body: _, self_ty } = value;
415 debug!(?self_ty, ?query_input, "probe_op: Mode::Path");
416 MethodAutoderefStepsResult {
417 steps: infcx.tcx.arena.alloc_from_iter([CandidateStep {
418 self_ty: self
419 .make_query_response_ignoring_pending_obligations(var_values, self_ty),
420 self_ty_is_opaque: false,
421 autoderefs: 0,
422 from_unsafe_deref: false,
423 unsize: false,
424 reachable_via_deref: true,
425 }]),
426 opt_bad_ty: None,
427 reached_recursion_limit: false,
428 }
429 }),
430 };
431
432 if steps.reached_recursion_limit && !is_suggestion.0 {
436 self.probe(|_| {
437 let ty = &steps
438 .steps
439 .last()
440 .unwrap_or_else(|| span_bug!(span, "reached the recursion limit in 0 steps?"))
441 .self_ty;
442 let ty = self
443 .probe_instantiate_query_response(span, &orig_values, ty)
444 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
445 autoderef::report_autoderef_recursion_limit_error(self.tcx, span, ty.value);
446 });
447 }
448
449 if let Some(bad_ty) = &steps.opt_bad_ty {
452 if is_suggestion.0 {
453 return Err(MethodError::NoMatch(NoMatchData {
456 static_candidates: Vec::new(),
457 unsatisfied_predicates: Vec::new(),
458 out_of_scope_traits: Vec::new(),
459 similar_candidate: None,
460 mode,
461 }));
462 } else if bad_ty.reached_raw_pointer
463 && !self.tcx.features().arbitrary_self_types_pointers()
464 && !self.tcx.sess.at_least_rust_2018()
465 {
466 self.tcx.node_span_lint(
470 lint::builtin::TYVAR_BEHIND_RAW_POINTER,
471 scope_expr_id,
472 span,
473 |lint| {
474 lint.primary_message("type annotations needed");
475 },
476 );
477 } else {
478 let ty = &bad_ty.ty;
482 let ty = self
483 .probe_instantiate_query_response(span, &orig_values, ty)
484 .unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
485 let ty = self.resolve_vars_if_possible(ty.value);
486 let guar = match *ty.kind() {
487 ty::Infer(ty::TyVar(_)) => {
488 let err_span = match (mode, self.tcx.hir_node(scope_expr_id)) {
491 (
492 Mode::MethodCall,
493 Node::Expr(hir::Expr {
494 kind: ExprKind::MethodCall(_, recv, ..),
495 ..
496 }),
497 ) => recv.span,
498 _ => span,
499 };
500
501 let raw_ptr_call = bad_ty.reached_raw_pointer
502 && !self.tcx.features().arbitrary_self_types();
503
504 let mut err = self.err_ctxt().emit_inference_failure_err(
505 self.body_id,
506 err_span,
507 ty.into(),
508 TypeAnnotationNeeded::E0282,
509 !raw_ptr_call,
510 );
511 if raw_ptr_call {
512 err.span_label(span, "cannot call a method on a raw pointer with an unknown pointee type");
513 }
514 err.emit()
515 }
516 ty::Error(guar) => guar,
517 _ => bug!("unexpected bad final type in method autoderef"),
518 };
519 self.demand_eqtype(span, ty, Ty::new_error(self.tcx, guar));
520 return Err(MethodError::ErrorReported(guar));
521 }
522 }
523
524 debug!("ProbeContext: steps for self_ty={:?} are {:?}", self_ty, steps);
525
526 self.probe(|_| {
529 let mut probe_cx = ProbeContext::new(
530 self,
531 span,
532 mode,
533 method_name,
534 return_type,
535 &orig_values,
536 steps.steps,
537 scope_expr_id,
538 is_suggestion,
539 );
540
541 match scope {
542 ProbeScope::TraitsInScope => {
543 probe_cx.assemble_inherent_candidates();
544 probe_cx.assemble_extension_candidates_for_traits_in_scope();
545 }
546 ProbeScope::AllTraits => {
547 probe_cx.assemble_inherent_candidates();
548 probe_cx.assemble_extension_candidates_for_all_traits();
549 }
550 ProbeScope::Single(def_id) => {
551 let item = self.tcx.associated_item(def_id);
552 assert_eq!(item.container, AssocContainer::Trait);
554
555 let trait_def_id = self.tcx.parent(def_id);
556 let trait_span = self.tcx.def_span(trait_def_id);
557
558 let trait_args = self.fresh_args_for_item(trait_span, trait_def_id);
559 let trait_ref = ty::TraitRef::new_from_args(self.tcx, trait_def_id, trait_args);
560
561 probe_cx.push_candidate(
562 Candidate {
563 item,
564 kind: CandidateKind::TraitCandidate(ty::Binder::dummy(trait_ref)),
565 import_ids: smallvec![],
566 },
567 false,
568 );
569 }
570 };
571 op(probe_cx)
572 })
573 }
574}
575
576pub(crate) fn method_autoderef_steps<'tcx>(
577 tcx: TyCtxt<'tcx>,
578 goal: CanonicalMethodAutoderefStepsGoal<'tcx>,
579) -> MethodAutoderefStepsResult<'tcx> {
580 debug!("method_autoderef_steps({:?})", goal);
581
582 let (ref infcx, goal, inference_vars) = tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &goal);
583 let ParamEnvAnd {
584 param_env,
585 value: query::MethodAutoderefSteps { predefined_opaques_in_body, self_ty },
586 } = goal;
587 for (key, ty) in predefined_opaques_in_body {
588 let prev =
589 infcx.register_hidden_type_in_storage(key, ty::OpaqueHiddenType { span: DUMMY_SP, ty });
590 if let Some(prev) = prev {
602 debug!(?key, ?ty, ?prev, "ignore duplicate in `opaque_types_storage`");
603 }
604 }
605
606 let self_ty_is_opaque = |ty: Ty<'_>| {
610 if let &ty::Infer(ty::TyVar(vid)) = ty.kind() {
611 infcx.has_opaques_with_sub_unified_hidden_type(vid)
612 } else {
613 false
614 }
615 };
616
617 let mut autoderef_via_deref =
627 Autoderef::new(infcx, param_env, hir::def_id::CRATE_DEF_ID, DUMMY_SP, self_ty)
628 .include_raw_pointers()
629 .silence_errors();
630
631 let mut reached_raw_pointer = false;
632 let arbitrary_self_types_enabled =
633 tcx.features().arbitrary_self_types() || tcx.features().arbitrary_self_types_pointers();
634 let (mut steps, reached_recursion_limit): (Vec<_>, bool) = if arbitrary_self_types_enabled {
635 let reachable_via_deref =
636 autoderef_via_deref.by_ref().map(|_| true).chain(std::iter::repeat(false));
637
638 let mut autoderef_via_receiver =
639 Autoderef::new(infcx, param_env, hir::def_id::CRATE_DEF_ID, DUMMY_SP, self_ty)
640 .include_raw_pointers()
641 .use_receiver_trait()
642 .silence_errors();
643 let steps = autoderef_via_receiver
644 .by_ref()
645 .zip(reachable_via_deref)
646 .map(|((ty, d), reachable_via_deref)| {
647 let step = CandidateStep {
648 self_ty: infcx
649 .make_query_response_ignoring_pending_obligations(inference_vars, ty),
650 self_ty_is_opaque: self_ty_is_opaque(ty),
651 autoderefs: d,
652 from_unsafe_deref: reached_raw_pointer,
653 unsize: false,
654 reachable_via_deref,
655 };
656 if ty.is_raw_ptr() {
657 reached_raw_pointer = true;
659 }
660 step
661 })
662 .collect();
663 (steps, autoderef_via_receiver.reached_recursion_limit())
664 } else {
665 let steps = autoderef_via_deref
666 .by_ref()
667 .map(|(ty, d)| {
668 let step = CandidateStep {
669 self_ty: infcx
670 .make_query_response_ignoring_pending_obligations(inference_vars, ty),
671 self_ty_is_opaque: self_ty_is_opaque(ty),
672 autoderefs: d,
673 from_unsafe_deref: reached_raw_pointer,
674 unsize: false,
675 reachable_via_deref: true,
676 };
677 if ty.is_raw_ptr() {
678 reached_raw_pointer = true;
680 }
681 step
682 })
683 .collect();
684 (steps, autoderef_via_deref.reached_recursion_limit())
685 };
686 let final_ty = autoderef_via_deref.final_ty();
687 let opt_bad_ty = match final_ty.kind() {
688 ty::Infer(ty::TyVar(_)) if !self_ty_is_opaque(final_ty) => Some(MethodAutoderefBadTy {
689 reached_raw_pointer,
690 ty: infcx.make_query_response_ignoring_pending_obligations(inference_vars, final_ty),
691 }),
692 ty::Error(_) => Some(MethodAutoderefBadTy {
693 reached_raw_pointer,
694 ty: infcx.make_query_response_ignoring_pending_obligations(inference_vars, final_ty),
695 }),
696 ty::Array(elem_ty, _) => {
697 let autoderefs = steps.iter().filter(|s| s.reachable_via_deref).count() - 1;
698 steps.push(CandidateStep {
699 self_ty: infcx.make_query_response_ignoring_pending_obligations(
700 inference_vars,
701 Ty::new_slice(infcx.tcx, *elem_ty),
702 ),
703 self_ty_is_opaque: false,
704 autoderefs,
705 from_unsafe_deref: reached_raw_pointer,
708 unsize: true,
709 reachable_via_deref: true, });
712
713 None
714 }
715 _ => None,
716 };
717
718 debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
719 let _ = infcx.take_opaque_types();
721 MethodAutoderefStepsResult {
722 steps: tcx.arena.alloc_from_iter(steps),
723 opt_bad_ty: opt_bad_ty.map(|ty| &*tcx.arena.alloc(ty)),
724 reached_recursion_limit,
725 }
726}
727
728impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
729 fn new(
730 fcx: &'a FnCtxt<'a, 'tcx>,
731 span: Span,
732 mode: Mode,
733 method_name: Option<Ident>,
734 return_type: Option<Ty<'tcx>>,
735 orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
736 steps: &'tcx [CandidateStep<'tcx>],
737 scope_expr_id: HirId,
738 is_suggestion: IsSuggestion,
739 ) -> ProbeContext<'a, 'tcx> {
740 ProbeContext {
741 fcx,
742 span,
743 mode,
744 method_name,
745 return_type,
746 inherent_candidates: Vec::new(),
747 extension_candidates: Vec::new(),
748 impl_dups: FxHashSet::default(),
749 orig_steps_var_values,
750 steps,
751 allow_similar_names: false,
752 private_candidates: Vec::new(),
753 private_candidate: Cell::new(None),
754 static_candidates: RefCell::new(Vec::new()),
755 scope_expr_id,
756 is_suggestion,
757 }
758 }
759
760 fn reset(&mut self) {
761 self.inherent_candidates.clear();
762 self.extension_candidates.clear();
763 self.impl_dups.clear();
764 self.private_candidates.clear();
765 self.private_candidate.set(None);
766 self.static_candidates.borrow_mut().clear();
767 }
768
769 fn variance(&self) -> ty::Variance {
773 match self.mode {
774 Mode::MethodCall => ty::Covariant,
775 Mode::Path => ty::Invariant,
776 }
777 }
778
779 fn push_candidate(&mut self, candidate: Candidate<'tcx>, is_inherent: bool) {
783 let is_accessible = if let Some(name) = self.method_name {
784 let item = candidate.item;
785 let hir_id = self.tcx.local_def_id_to_hir_id(self.body_id);
786 let def_scope =
787 self.tcx.adjust_ident_and_get_scope(name, item.container_id(self.tcx), hir_id).1;
788 item.visibility(self.tcx).is_accessible_from(def_scope, self.tcx)
789 } else {
790 true
791 };
792 if is_accessible {
793 if is_inherent {
794 self.inherent_candidates.push(candidate);
795 } else {
796 self.extension_candidates.push(candidate);
797 }
798 } else {
799 self.private_candidates.push(candidate);
800 }
801 }
802
803 fn assemble_inherent_candidates(&mut self) {
804 for step in self.steps.iter() {
805 self.assemble_probe(&step.self_ty, step.autoderefs);
806 }
807 }
808
809 #[instrument(level = "debug", skip(self))]
810 fn assemble_probe(
811 &mut self,
812 self_ty: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
813 receiver_steps: usize,
814 ) {
815 let raw_self_ty = self_ty.value.value;
816 match *raw_self_ty.kind() {
817 ty::Dynamic(data, ..) if let Some(p) = data.principal() => {
818 let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
836 self.fcx.instantiate_canonical(self.span, self_ty);
837
838 self.assemble_inherent_candidates_from_object(generalized_self_ty);
839 self.assemble_inherent_impl_candidates_for_type(p.def_id(), receiver_steps);
840 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
841 }
842 ty::Adt(def, _) => {
843 let def_id = def.did();
844 self.assemble_inherent_impl_candidates_for_type(def_id, receiver_steps);
845 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
846 }
847 ty::Foreign(did) => {
848 self.assemble_inherent_impl_candidates_for_type(did, receiver_steps);
849 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
850 }
851 ty::Param(_) => {
852 self.assemble_inherent_candidates_from_param(raw_self_ty);
853 }
854 ty::Bool
855 | ty::Char
856 | ty::Int(_)
857 | ty::Uint(_)
858 | ty::Float(_)
859 | ty::Str
860 | ty::Array(..)
861 | ty::Slice(_)
862 | ty::RawPtr(_, _)
863 | ty::Ref(..)
864 | ty::Never
865 | ty::Tuple(..) => {
866 self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps)
867 }
868 _ => {}
869 }
870 }
871
872 fn assemble_inherent_candidates_for_incoherent_ty(
873 &mut self,
874 self_ty: Ty<'tcx>,
875 receiver_steps: usize,
876 ) {
877 let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::InstantiateWithInfer) else {
878 bug!("unexpected incoherent type: {:?}", self_ty)
879 };
880 for &impl_def_id in self.tcx.incoherent_impls(simp).into_iter() {
881 self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
882 }
883 }
884
885 fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId, receiver_steps: usize) {
886 let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id).into_iter();
887 for &impl_def_id in impl_def_ids {
888 self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
889 }
890 }
891
892 #[instrument(level = "debug", skip(self))]
893 fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId, receiver_steps: usize) {
894 if !self.impl_dups.insert(impl_def_id) {
895 return; }
897
898 for item in self.impl_or_trait_item(impl_def_id) {
899 if !self.has_applicable_self(&item) {
900 self.record_static_candidate(CandidateSource::Impl(impl_def_id));
902 continue;
903 }
904 self.push_candidate(
905 Candidate {
906 item,
907 kind: InherentImplCandidate { impl_def_id, receiver_steps },
908 import_ids: smallvec![],
909 },
910 true,
911 );
912 }
913 }
914
915 #[instrument(level = "debug", skip(self))]
916 fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'tcx>) {
917 let principal = match self_ty.kind() {
918 ty::Dynamic(data, ..) => Some(data),
919 _ => None,
920 }
921 .and_then(|data| data.principal())
922 .unwrap_or_else(|| {
923 span_bug!(
924 self.span,
925 "non-object {:?} in assemble_inherent_candidates_from_object",
926 self_ty
927 )
928 });
929
930 let trait_ref = principal.with_self_ty(self.tcx, self_ty);
937 self.assemble_candidates_for_bounds(
938 traits::supertraits(self.tcx, trait_ref),
939 |this, new_trait_ref, item| {
940 this.push_candidate(
941 Candidate {
942 item,
943 kind: ObjectCandidate(new_trait_ref),
944 import_ids: smallvec![],
945 },
946 true,
947 );
948 },
949 );
950 }
951
952 #[instrument(level = "debug", skip(self))]
953 fn assemble_inherent_candidates_from_param(&mut self, param_ty: Ty<'tcx>) {
954 debug_assert_matches!(param_ty.kind(), ty::Param(_));
955
956 let tcx = self.tcx;
957
958 let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| {
962 let bound_predicate = predicate.kind();
963 match bound_predicate.skip_binder() {
964 ty::ClauseKind::Trait(trait_predicate) => DeepRejectCtxt::relate_rigid_rigid(tcx)
965 .types_may_unify(param_ty, trait_predicate.trait_ref.self_ty())
966 .then(|| bound_predicate.rebind(trait_predicate.trait_ref)),
967 ty::ClauseKind::RegionOutlives(_)
968 | ty::ClauseKind::TypeOutlives(_)
969 | ty::ClauseKind::Projection(_)
970 | ty::ClauseKind::ConstArgHasType(_, _)
971 | ty::ClauseKind::WellFormed(_)
972 | ty::ClauseKind::ConstEvaluatable(_)
973 | ty::ClauseKind::UnstableFeature(_)
974 | ty::ClauseKind::HostEffect(..) => None,
975 }
976 });
977
978 self.assemble_candidates_for_bounds(bounds, |this, poly_trait_ref, item| {
979 this.push_candidate(
980 Candidate {
981 item,
982 kind: WhereClauseCandidate(poly_trait_ref),
983 import_ids: smallvec![],
984 },
985 true,
986 );
987 });
988 }
989
990 fn assemble_candidates_for_bounds<F>(
993 &mut self,
994 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
995 mut mk_cand: F,
996 ) where
997 F: for<'b> FnMut(&mut ProbeContext<'b, 'tcx>, ty::PolyTraitRef<'tcx>, ty::AssocItem),
998 {
999 for bound_trait_ref in bounds {
1000 debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
1001 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
1002 if !self.has_applicable_self(&item) {
1003 self.record_static_candidate(CandidateSource::Trait(bound_trait_ref.def_id()));
1004 } else {
1005 mk_cand(self, bound_trait_ref, item);
1006 }
1007 }
1008 }
1009 }
1010
1011 #[instrument(level = "debug", skip(self))]
1012 fn assemble_extension_candidates_for_traits_in_scope(&mut self) {
1013 let mut duplicates = FxHashSet::default();
1014 let opt_applicable_traits = self.tcx.in_scope_traits(self.scope_expr_id);
1015 if let Some(applicable_traits) = opt_applicable_traits {
1016 for trait_candidate in applicable_traits.iter() {
1017 let trait_did = trait_candidate.def_id;
1018 if duplicates.insert(trait_did) {
1019 self.assemble_extension_candidates_for_trait(
1020 &trait_candidate.import_ids,
1021 trait_did,
1022 );
1023 }
1024 }
1025 }
1026 }
1027
1028 #[instrument(level = "debug", skip(self))]
1029 fn assemble_extension_candidates_for_all_traits(&mut self) {
1030 let mut duplicates = FxHashSet::default();
1031 for trait_info in suggest::all_traits(self.tcx) {
1032 if duplicates.insert(trait_info.def_id) {
1033 self.assemble_extension_candidates_for_trait(&smallvec![], trait_info.def_id);
1034 }
1035 }
1036 }
1037
1038 fn matches_return_type(&self, method: ty::AssocItem, expected: Ty<'tcx>) -> bool {
1039 match method.kind {
1040 ty::AssocKind::Fn { .. } => self.probe(|_| {
1041 let args = self.fresh_args_for_item(self.span, method.def_id);
1042 let fty = self.tcx.fn_sig(method.def_id).instantiate(self.tcx, args);
1043 let fty = self.instantiate_binder_with_fresh_vars(
1044 self.span,
1045 BoundRegionConversionTime::FnCall,
1046 fty,
1047 );
1048 self.can_eq(self.param_env, fty.output(), expected)
1049 }),
1050 _ => false,
1051 }
1052 }
1053
1054 #[instrument(level = "debug", skip(self))]
1055 fn assemble_extension_candidates_for_trait(
1056 &mut self,
1057 import_ids: &SmallVec<[LocalDefId; 1]>,
1058 trait_def_id: DefId,
1059 ) {
1060 let trait_args = self.fresh_args_for_item(self.span, trait_def_id);
1061 let trait_ref = ty::TraitRef::new_from_args(self.tcx, trait_def_id, trait_args);
1062
1063 if self.tcx.is_trait_alias(trait_def_id) {
1064 for (bound_trait_pred, _) in
1066 traits::expand_trait_aliases(self.tcx, [(trait_ref.upcast(self.tcx), self.span)]).0
1067 {
1068 assert_eq!(bound_trait_pred.polarity(), ty::PredicatePolarity::Positive);
1069 let bound_trait_ref = bound_trait_pred.map_bound(|pred| pred.trait_ref);
1070 for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
1071 if !self.has_applicable_self(&item) {
1072 self.record_static_candidate(CandidateSource::Trait(
1073 bound_trait_ref.def_id(),
1074 ));
1075 } else {
1076 self.push_candidate(
1077 Candidate {
1078 item,
1079 import_ids: import_ids.clone(),
1080 kind: TraitCandidate(bound_trait_ref),
1081 },
1082 false,
1083 );
1084 }
1085 }
1086 }
1087 } else {
1088 debug_assert!(self.tcx.is_trait(trait_def_id));
1089 if self.tcx.trait_is_auto(trait_def_id) {
1090 return;
1091 }
1092 for item in self.impl_or_trait_item(trait_def_id) {
1093 if !self.has_applicable_self(&item) {
1095 debug!("method has inapplicable self");
1096 self.record_static_candidate(CandidateSource::Trait(trait_def_id));
1097 continue;
1098 }
1099 self.push_candidate(
1100 Candidate {
1101 item,
1102 import_ids: import_ids.clone(),
1103 kind: TraitCandidate(ty::Binder::dummy(trait_ref)),
1104 },
1105 false,
1106 );
1107 }
1108 }
1109 }
1110
1111 fn candidate_method_names(
1112 &self,
1113 candidate_filter: impl Fn(&ty::AssocItem) -> bool,
1114 ) -> Vec<Ident> {
1115 let mut set = FxHashSet::default();
1116 let mut names: Vec<_> = self
1117 .inherent_candidates
1118 .iter()
1119 .chain(&self.extension_candidates)
1120 .filter(|candidate| candidate_filter(&candidate.item))
1121 .filter(|candidate| {
1122 if let Some(return_ty) = self.return_type {
1123 self.matches_return_type(candidate.item, return_ty)
1124 } else {
1125 true
1126 }
1127 })
1128 .filter(|candidate| {
1130 !matches!(
1133 self.tcx.eval_stability(candidate.item.def_id, None, DUMMY_SP, None),
1134 stability::EvalResult::Deny { .. }
1135 )
1136 })
1137 .map(|candidate| candidate.item.ident(self.tcx))
1138 .filter(|&name| set.insert(name))
1139 .collect();
1140
1141 names.sort_by(|a, b| a.as_str().cmp(b.as_str()));
1143 names
1144 }
1145
1146 #[instrument(level = "debug", skip(self))]
1150 fn pick(mut self) -> PickResult<'tcx> {
1151 assert!(self.method_name.is_some());
1152
1153 let mut unsatisfied_predicates = Vec::new();
1154
1155 if let Some(r) = self.pick_core(&mut unsatisfied_predicates) {
1156 return r;
1157 }
1158
1159 if self.is_suggestion.0 {
1162 return Err(MethodError::NoMatch(NoMatchData {
1163 static_candidates: vec![],
1164 unsatisfied_predicates: vec![],
1165 out_of_scope_traits: vec![],
1166 similar_candidate: None,
1167 mode: self.mode,
1168 }));
1169 }
1170
1171 debug!("pick: actual search failed, assemble diagnostics");
1172
1173 let static_candidates = std::mem::take(self.static_candidates.get_mut());
1174 let private_candidate = self.private_candidate.take();
1175
1176 self.reset();
1178
1179 let span = self.span;
1180 let tcx = self.tcx;
1181
1182 self.assemble_extension_candidates_for_all_traits();
1183
1184 let out_of_scope_traits = match self.pick_core(&mut Vec::new()) {
1185 Some(Ok(p)) => vec![p.item.container_id(self.tcx)],
1186 Some(Err(MethodError::Ambiguity(v))) => v
1187 .into_iter()
1188 .map(|source| match source {
1189 CandidateSource::Trait(id) => id,
1190 CandidateSource::Impl(impl_id) => match tcx.trait_id_of_impl(impl_id) {
1191 Some(id) => id,
1192 None => span_bug!(span, "found inherent method when looking at traits"),
1193 },
1194 })
1195 .collect(),
1196 Some(Err(MethodError::NoMatch(NoMatchData {
1197 out_of_scope_traits: others, ..
1198 }))) => {
1199 assert!(others.is_empty());
1200 vec![]
1201 }
1202 _ => vec![],
1203 };
1204
1205 if let Some((kind, def_id)) = private_candidate {
1206 return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits));
1207 }
1208 let similar_candidate = self.probe_for_similar_candidate()?;
1209
1210 Err(MethodError::NoMatch(NoMatchData {
1211 static_candidates,
1212 unsatisfied_predicates,
1213 out_of_scope_traits,
1214 similar_candidate,
1215 mode: self.mode,
1216 }))
1217 }
1218
1219 fn pick_core(
1220 &self,
1221 unsatisfied_predicates: &mut Vec<(
1222 ty::Predicate<'tcx>,
1223 Option<ty::Predicate<'tcx>>,
1224 Option<ObligationCause<'tcx>>,
1225 )>,
1226 ) -> Option<PickResult<'tcx>> {
1227 self.pick_all_method(&mut PickDiagHints {
1229 unstable_candidates: Some(Vec::new()),
1232 unsatisfied_predicates,
1235 })
1236 .or_else(|| {
1237 self.pick_all_method(&mut PickDiagHints {
1238 unstable_candidates: None,
1243 unsatisfied_predicates: &mut Vec::new(),
1246 })
1247 })
1248 }
1249
1250 fn pick_all_method<'b>(
1251 &self,
1252 pick_diag_hints: &mut PickDiagHints<'b, 'tcx>,
1253 ) -> Option<PickResult<'tcx>> {
1254 let track_unstable_candidates = pick_diag_hints.unstable_candidates.is_some();
1255 self.steps
1256 .iter()
1257 .filter(|step| step.reachable_via_deref)
1261 .filter(|step| {
1262 debug!("pick_all_method: step={:?}", step);
1263 !step.self_ty.value.references_error() && !step.from_unsafe_deref
1266 })
1267 .find_map(|step| {
1268 let InferOk { value: self_ty, obligations: instantiate_self_ty_obligations } = self
1269 .fcx
1270 .probe_instantiate_query_response(
1271 self.span,
1272 self.orig_steps_var_values,
1273 &step.self_ty,
1274 )
1275 .unwrap_or_else(|_| {
1276 span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
1277 });
1278
1279 let by_value_pick = self.pick_by_value_method(
1280 step,
1281 self_ty,
1282 &instantiate_self_ty_obligations,
1283 pick_diag_hints,
1284 );
1285
1286 if let Some(by_value_pick) = by_value_pick {
1288 if let Ok(by_value_pick) = by_value_pick.as_ref() {
1289 if by_value_pick.kind == PickKind::InherentImplPick {
1290 for mutbl in [hir::Mutability::Not, hir::Mutability::Mut] {
1291 if let Err(e) = self.check_for_shadowed_autorefd_method(
1292 by_value_pick,
1293 step,
1294 self_ty,
1295 &instantiate_self_ty_obligations,
1296 mutbl,
1297 track_unstable_candidates,
1298 ) {
1299 return Some(Err(e));
1300 }
1301 }
1302 }
1303 }
1304 return Some(by_value_pick);
1305 }
1306
1307 let autoref_pick = self.pick_autorefd_method(
1308 step,
1309 self_ty,
1310 &instantiate_self_ty_obligations,
1311 hir::Mutability::Not,
1312 pick_diag_hints,
1313 None,
1314 );
1315 if let Some(autoref_pick) = autoref_pick {
1317 if let Ok(autoref_pick) = autoref_pick.as_ref() {
1318 if autoref_pick.kind == PickKind::InherentImplPick {
1320 if let Err(e) = self.check_for_shadowed_autorefd_method(
1321 autoref_pick,
1322 step,
1323 self_ty,
1324 &instantiate_self_ty_obligations,
1325 hir::Mutability::Mut,
1326 track_unstable_candidates,
1327 ) {
1328 return Some(Err(e));
1329 }
1330 }
1331 }
1332 return Some(autoref_pick);
1333 }
1334
1335 self.pick_autorefd_method(
1359 step,
1360 self_ty,
1361 &instantiate_self_ty_obligations,
1362 hir::Mutability::Mut,
1363 pick_diag_hints,
1364 None,
1365 )
1366 .or_else(|| {
1367 self.pick_const_ptr_method(
1368 step,
1369 self_ty,
1370 &instantiate_self_ty_obligations,
1371 pick_diag_hints,
1372 )
1373 })
1374 .or_else(|| {
1375 self.pick_reborrow_pin_method(
1376 step,
1377 self_ty,
1378 &instantiate_self_ty_obligations,
1379 pick_diag_hints,
1380 )
1381 })
1382 })
1383 }
1384
1385 fn check_for_shadowed_autorefd_method(
1401 &self,
1402 possible_shadower: &Pick<'tcx>,
1403 step: &CandidateStep<'tcx>,
1404 self_ty: Ty<'tcx>,
1405 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1406 mutbl: hir::Mutability,
1407 track_unstable_candidates: bool,
1408 ) -> Result<(), MethodError<'tcx>> {
1409 if !self.tcx.features().arbitrary_self_types()
1413 && !self.tcx.features().arbitrary_self_types_pointers()
1414 {
1415 return Ok(());
1416 }
1417
1418 let mut pick_diag_hints = PickDiagHints {
1423 unstable_candidates: if track_unstable_candidates { Some(Vec::new()) } else { None },
1424 unsatisfied_predicates: &mut Vec::new(),
1425 };
1426 let pick_constraints = PickConstraintsForShadowed {
1428 autoderefs: possible_shadower.autoderefs,
1430 receiver_steps: possible_shadower.receiver_steps,
1434 def_id: possible_shadower.item.def_id,
1437 };
1438 let potentially_shadowed_pick = self.pick_autorefd_method(
1468 step,
1469 self_ty,
1470 instantiate_self_ty_obligations,
1471 mutbl,
1472 &mut pick_diag_hints,
1473 Some(&pick_constraints),
1474 );
1475 if let Some(Ok(possible_shadowed)) = potentially_shadowed_pick.as_ref() {
1478 let sources = [possible_shadower, possible_shadowed]
1479 .into_iter()
1480 .map(|p| self.candidate_source_from_pick(p))
1481 .collect();
1482 return Err(MethodError::Ambiguity(sources));
1483 }
1484 Ok(())
1485 }
1486
1487 fn pick_by_value_method(
1494 &self,
1495 step: &CandidateStep<'tcx>,
1496 self_ty: Ty<'tcx>,
1497 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1498 pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1499 ) -> Option<PickResult<'tcx>> {
1500 if step.unsize {
1501 return None;
1502 }
1503
1504 self.pick_method(self_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(|r| {
1505 r.map(|mut pick| {
1506 pick.autoderefs = step.autoderefs;
1507
1508 match *step.self_ty.value.value.kind() {
1509 ty::Ref(_, _, mutbl) => {
1511 pick.autoderefs += 1;
1512 pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::Autoref {
1513 mutbl,
1514 unsize: pick.autoref_or_ptr_adjustment.is_some_and(|a| a.get_unsize()),
1515 })
1516 }
1517
1518 ty::Adt(def, args)
1519 if self.tcx.features().pin_ergonomics()
1520 && self.tcx.is_lang_item(def.did(), hir::LangItem::Pin) =>
1521 {
1522 if let ty::Ref(_, _, mutbl) = args[0].expect_ty().kind() {
1524 pick.autoref_or_ptr_adjustment =
1525 Some(AutorefOrPtrAdjustment::ReborrowPin(*mutbl));
1526 }
1527 }
1528
1529 _ => (),
1530 }
1531
1532 pick
1533 })
1534 })
1535 }
1536
1537 fn pick_autorefd_method(
1538 &self,
1539 step: &CandidateStep<'tcx>,
1540 self_ty: Ty<'tcx>,
1541 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1542 mutbl: hir::Mutability,
1543 pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1544 pick_constraints: Option<&PickConstraintsForShadowed>,
1545 ) -> Option<PickResult<'tcx>> {
1546 let tcx = self.tcx;
1547
1548 if let Some(pick_constraints) = pick_constraints {
1549 if !pick_constraints.may_shadow_based_on_autoderefs(step.autoderefs) {
1550 return None;
1551 }
1552 }
1553
1554 let region = tcx.lifetimes.re_erased;
1556
1557 let autoref_ty = Ty::new_ref(tcx, region, self_ty, mutbl);
1558 self.pick_method(
1559 autoref_ty,
1560 instantiate_self_ty_obligations,
1561 pick_diag_hints,
1562 pick_constraints,
1563 )
1564 .map(|r| {
1565 r.map(|mut pick| {
1566 pick.autoderefs = step.autoderefs;
1567 pick.autoref_or_ptr_adjustment =
1568 Some(AutorefOrPtrAdjustment::Autoref { mutbl, unsize: step.unsize });
1569 pick
1570 })
1571 })
1572 }
1573
1574 #[instrument(level = "debug", skip(self, step, pick_diag_hints))]
1576 fn pick_reborrow_pin_method(
1577 &self,
1578 step: &CandidateStep<'tcx>,
1579 self_ty: Ty<'tcx>,
1580 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1581 pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1582 ) -> Option<PickResult<'tcx>> {
1583 if !self.tcx.features().pin_ergonomics() {
1584 return None;
1585 }
1586
1587 let inner_ty = match self_ty.kind() {
1589 ty::Adt(def, args) if self.tcx.is_lang_item(def.did(), hir::LangItem::Pin) => {
1590 match args[0].expect_ty().kind() {
1591 ty::Ref(_, ty, hir::Mutability::Mut) => *ty,
1592 _ => {
1593 return None;
1594 }
1595 }
1596 }
1597 _ => return None,
1598 };
1599
1600 let region = self.tcx.lifetimes.re_erased;
1601 let autopin_ty = Ty::new_pinned_ref(self.tcx, region, inner_ty, hir::Mutability::Not);
1602 self.pick_method(autopin_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1603 |r| {
1604 r.map(|mut pick| {
1605 pick.autoderefs = step.autoderefs;
1606 pick.autoref_or_ptr_adjustment =
1607 Some(AutorefOrPtrAdjustment::ReborrowPin(hir::Mutability::Not));
1608 pick
1609 })
1610 },
1611 )
1612 }
1613
1614 fn pick_const_ptr_method(
1618 &self,
1619 step: &CandidateStep<'tcx>,
1620 self_ty: Ty<'tcx>,
1621 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1622 pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1623 ) -> Option<PickResult<'tcx>> {
1624 if step.unsize {
1626 return None;
1627 }
1628
1629 let &ty::RawPtr(ty, hir::Mutability::Mut) = self_ty.kind() else {
1630 return None;
1631 };
1632
1633 let const_ptr_ty = Ty::new_imm_ptr(self.tcx, ty);
1634 self.pick_method(const_ptr_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1635 |r| {
1636 r.map(|mut pick| {
1637 pick.autoderefs = step.autoderefs;
1638 pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::ToConstPtr);
1639 pick
1640 })
1641 },
1642 )
1643 }
1644
1645 fn pick_method(
1646 &self,
1647 self_ty: Ty<'tcx>,
1648 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1649 pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1650 pick_constraints: Option<&PickConstraintsForShadowed>,
1651 ) -> Option<PickResult<'tcx>> {
1652 debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1653
1654 for (kind, candidates) in
1655 [("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1656 {
1657 debug!("searching {} candidates", kind);
1658 let res = self.consider_candidates(
1659 self_ty,
1660 instantiate_self_ty_obligations,
1661 candidates,
1662 pick_diag_hints,
1663 pick_constraints,
1664 );
1665 if let Some(pick) = res {
1666 return Some(pick);
1667 }
1668 }
1669
1670 if self.private_candidate.get().is_none() {
1671 if let Some(Ok(pick)) = self.consider_candidates(
1672 self_ty,
1673 instantiate_self_ty_obligations,
1674 &self.private_candidates,
1675 &mut PickDiagHints {
1676 unstable_candidates: None,
1677 unsatisfied_predicates: &mut vec![],
1678 },
1679 None,
1680 ) {
1681 self.private_candidate.set(Some((pick.item.as_def_kind(), pick.item.def_id)));
1682 }
1683 }
1684 None
1685 }
1686
1687 fn consider_candidates(
1688 &self,
1689 self_ty: Ty<'tcx>,
1690 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1691 candidates: &[Candidate<'tcx>],
1692 pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1693 pick_constraints: Option<&PickConstraintsForShadowed>,
1694 ) -> Option<PickResult<'tcx>> {
1695 let mut applicable_candidates: Vec<_> = candidates
1696 .iter()
1697 .filter(|candidate| {
1698 pick_constraints
1699 .map(|pick_constraints| pick_constraints.candidate_may_shadow(&candidate))
1700 .unwrap_or(true)
1701 })
1702 .map(|probe| {
1703 (
1704 probe,
1705 self.consider_probe(
1706 self_ty,
1707 instantiate_self_ty_obligations,
1708 probe,
1709 &mut pick_diag_hints.unsatisfied_predicates,
1710 ),
1711 )
1712 })
1713 .filter(|&(_, status)| status != ProbeResult::NoMatch)
1714 .collect();
1715
1716 debug!("applicable_candidates: {:?}", applicable_candidates);
1717
1718 if applicable_candidates.len() > 1 {
1719 if let Some(pick) =
1720 self.collapse_candidates_to_trait_pick(self_ty, &applicable_candidates)
1721 {
1722 return Some(Ok(pick));
1723 }
1724 }
1725
1726 if let Some(uc) = &mut pick_diag_hints.unstable_candidates {
1727 applicable_candidates.retain(|&(candidate, _)| {
1728 if let stability::EvalResult::Deny { feature, .. } =
1729 self.tcx.eval_stability(candidate.item.def_id, None, self.span, None)
1730 {
1731 uc.push((candidate.clone(), feature));
1732 return false;
1733 }
1734 true
1735 });
1736 }
1737
1738 if applicable_candidates.len() > 1 {
1739 if self.tcx.features().supertrait_item_shadowing() {
1743 if let Some(pick) =
1744 self.collapse_candidates_to_subtrait_pick(self_ty, &applicable_candidates)
1745 {
1746 return Some(Ok(pick));
1747 }
1748 }
1749
1750 let sources =
1751 applicable_candidates.iter().map(|p| self.candidate_source(p.0, self_ty)).collect();
1752 return Some(Err(MethodError::Ambiguity(sources)));
1753 }
1754
1755 applicable_candidates.pop().map(|(probe, status)| match status {
1756 ProbeResult::Match => Ok(probe.to_unadjusted_pick(
1757 self_ty,
1758 pick_diag_hints.unstable_candidates.clone().unwrap_or_default(),
1759 )),
1760 ProbeResult::NoMatch | ProbeResult::BadReturnType => Err(MethodError::BadReturnType),
1761 })
1762 }
1763}
1764
1765impl<'tcx> Pick<'tcx> {
1766 pub(crate) fn differs_from(&self, other: &Self) -> bool {
1771 let Self {
1772 item: AssocItem { def_id, kind: _, container: _ },
1773 kind: _,
1774 import_ids: _,
1775 autoderefs: _,
1776 autoref_or_ptr_adjustment: _,
1777 self_ty,
1778 unstable_candidates: _,
1779 receiver_steps: _,
1780 shadowed_candidates: _,
1781 } = *self;
1782 self_ty != other.self_ty || def_id != other.item.def_id
1783 }
1784
1785 pub(crate) fn maybe_emit_unstable_name_collision_hint(
1787 &self,
1788 tcx: TyCtxt<'tcx>,
1789 span: Span,
1790 scope_expr_id: HirId,
1791 ) {
1792 if self.unstable_candidates.is_empty() {
1793 return;
1794 }
1795 let def_kind = self.item.as_def_kind();
1796 tcx.node_span_lint(lint::builtin::UNSTABLE_NAME_COLLISIONS, scope_expr_id, span, |lint| {
1797 lint.primary_message(format!(
1798 "{} {} with this name may be added to the standard library in the future",
1799 tcx.def_kind_descr_article(def_kind, self.item.def_id),
1800 tcx.def_kind_descr(def_kind, self.item.def_id),
1801 ));
1802
1803 match (self.item.kind, self.item.container) {
1804 (ty::AssocKind::Fn { .. }, _) => {
1805 lint.help(format!(
1810 "call with fully qualified syntax `{}(...)` to keep using the current \
1811 method",
1812 tcx.def_path_str(self.item.def_id),
1813 ));
1814 }
1815 (ty::AssocKind::Const { name }, ty::AssocContainer::Trait) => {
1816 let def_id = self.item.container_id(tcx);
1817 lint.span_suggestion(
1818 span,
1819 "use the fully qualified path to the associated const",
1820 format!("<{} as {}>::{}", self.self_ty, tcx.def_path_str(def_id), name),
1821 Applicability::MachineApplicable,
1822 );
1823 }
1824 _ => {}
1825 }
1826 tcx.disabled_nightly_features(
1827 lint,
1828 self.unstable_candidates.iter().map(|(candidate, feature)| {
1829 (format!(" `{}`", tcx.def_path_str(candidate.item.def_id)), *feature)
1830 }),
1831 );
1832 });
1833 }
1834}
1835
1836impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
1837 fn select_trait_candidate(
1838 &self,
1839 trait_ref: ty::TraitRef<'tcx>,
1840 ) -> traits::SelectionResult<'tcx, traits::Selection<'tcx>> {
1841 let obligation =
1842 traits::Obligation::new(self.tcx, self.misc(self.span), self.param_env, trait_ref);
1843 traits::SelectionContext::new(self).select(&obligation)
1844 }
1845
1846 fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>) -> CandidateSource {
1849 match candidate.kind {
1850 InherentImplCandidate { .. } => {
1851 CandidateSource::Impl(candidate.item.container_id(self.tcx))
1852 }
1853 ObjectCandidate(_) | WhereClauseCandidate(_) => {
1854 CandidateSource::Trait(candidate.item.container_id(self.tcx))
1855 }
1856 TraitCandidate(trait_ref) => self.probe(|_| {
1857 let trait_ref = self.instantiate_binder_with_fresh_vars(
1858 self.span,
1859 BoundRegionConversionTime::FnCall,
1860 trait_ref,
1861 );
1862 let (xform_self_ty, _) =
1863 self.xform_self_ty(candidate.item, trait_ref.self_ty(), trait_ref.args);
1864 let _ = self.at(&ObligationCause::dummy(), self.param_env).sup(
1867 DefineOpaqueTypes::Yes,
1868 xform_self_ty,
1869 self_ty,
1870 );
1871 match self.select_trait_candidate(trait_ref) {
1872 Ok(Some(traits::ImplSource::UserDefined(ref impl_data))) => {
1873 CandidateSource::Impl(impl_data.impl_def_id)
1876 }
1877 _ => CandidateSource::Trait(candidate.item.container_id(self.tcx)),
1878 }
1879 }),
1880 }
1881 }
1882
1883 fn candidate_source_from_pick(&self, pick: &Pick<'tcx>) -> CandidateSource {
1884 match pick.kind {
1885 InherentImplPick => CandidateSource::Impl(pick.item.container_id(self.tcx)),
1886 ObjectPick | WhereClausePick(_) | TraitPick => {
1887 CandidateSource::Trait(pick.item.container_id(self.tcx))
1888 }
1889 }
1890 }
1891
1892 #[instrument(level = "debug", skip(self, possibly_unsatisfied_predicates), ret)]
1893 fn consider_probe(
1894 &self,
1895 self_ty: Ty<'tcx>,
1896 instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1897 probe: &Candidate<'tcx>,
1898 possibly_unsatisfied_predicates: &mut Vec<(
1899 ty::Predicate<'tcx>,
1900 Option<ty::Predicate<'tcx>>,
1901 Option<ObligationCause<'tcx>>,
1902 )>,
1903 ) -> ProbeResult {
1904 self.probe(|snapshot| {
1905 let outer_universe = self.universe();
1906
1907 let mut result = ProbeResult::Match;
1908 let cause = &self.misc(self.span);
1909 let ocx = ObligationCtxt::new_with_diagnostics(self);
1910
1911 if self.next_trait_solver() {
1919 ocx.register_obligations(instantiate_self_ty_obligations.iter().cloned());
1920 let errors = ocx.try_evaluate_obligations();
1921 if !errors.is_empty() {
1922 unreachable!("unexpected autoderef error {errors:?}");
1923 }
1924 }
1925
1926 let mut trait_predicate = None;
1927 let (mut xform_self_ty, mut xform_ret_ty);
1928
1929 match probe.kind {
1930 InherentImplCandidate { impl_def_id, .. } => {
1931 let impl_args = self.fresh_args_for_item(self.span, impl_def_id);
1932 let impl_ty = self.tcx.type_of(impl_def_id).instantiate(self.tcx, impl_args);
1933 (xform_self_ty, xform_ret_ty) =
1934 self.xform_self_ty(probe.item, impl_ty, impl_args);
1935 xform_self_ty = ocx.normalize(cause, self.param_env, xform_self_ty);
1936 match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
1937 {
1938 Ok(()) => {}
1939 Err(err) => {
1940 debug!("--> cannot relate self-types {:?}", err);
1941 return ProbeResult::NoMatch;
1942 }
1943 }
1944 xform_ret_ty = ocx.normalize(cause, self.param_env, xform_ret_ty);
1946 let impl_def_id = probe.item.container_id(self.tcx);
1948 let impl_bounds =
1949 self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_args);
1950 let impl_bounds = ocx.normalize(cause, self.param_env, impl_bounds);
1951 ocx.register_obligations(traits::predicates_for_generics(
1953 |idx, span| {
1954 let code = ObligationCauseCode::WhereClauseInExpr(
1955 impl_def_id,
1956 span,
1957 self.scope_expr_id,
1958 idx,
1959 );
1960 self.cause(self.span, code)
1961 },
1962 self.param_env,
1963 impl_bounds,
1964 ));
1965 }
1966 TraitCandidate(poly_trait_ref) => {
1967 if let Some(method_name) = self.method_name {
1970 if self_ty.is_array() && !method_name.span.at_least_rust_2021() {
1971 let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
1972 if trait_def.skip_array_during_method_dispatch {
1973 return ProbeResult::NoMatch;
1974 }
1975 }
1976
1977 if self_ty.boxed_ty().is_some_and(Ty::is_slice)
1980 && !method_name.span.at_least_rust_2024()
1981 {
1982 let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
1983 if trait_def.skip_boxed_slice_during_method_dispatch {
1984 return ProbeResult::NoMatch;
1985 }
1986 }
1987 }
1988
1989 let trait_ref = self.instantiate_binder_with_fresh_vars(
1990 self.span,
1991 BoundRegionConversionTime::FnCall,
1992 poly_trait_ref,
1993 );
1994 let trait_ref = ocx.normalize(cause, self.param_env, trait_ref);
1995 (xform_self_ty, xform_ret_ty) =
1996 self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
1997 xform_self_ty = ocx.normalize(cause, self.param_env, xform_self_ty);
1998 match self_ty.kind() {
1999 ty::Alias(ty::Opaque, alias_ty)
2003 if !self.next_trait_solver()
2004 && self.infcx.can_define_opaque_ty(alias_ty.def_id)
2005 && !xform_self_ty.is_ty_var() =>
2006 {
2007 return ProbeResult::NoMatch;
2008 }
2009 _ => match ocx.relate(
2010 cause,
2011 self.param_env,
2012 self.variance(),
2013 self_ty,
2014 xform_self_ty,
2015 ) {
2016 Ok(()) => {}
2017 Err(err) => {
2018 debug!("--> cannot relate self-types {:?}", err);
2019 return ProbeResult::NoMatch;
2020 }
2021 },
2022 }
2023 let obligation = traits::Obligation::new(
2024 self.tcx,
2025 cause.clone(),
2026 self.param_env,
2027 ty::Binder::dummy(trait_ref),
2028 );
2029
2030 if self.infcx.next_trait_solver() || self.infcx.predicate_may_hold(&obligation)
2032 {
2033 ocx.register_obligation(obligation);
2034 } else {
2035 result = ProbeResult::NoMatch;
2036 if let Ok(Some(candidate)) = self.select_trait_candidate(trait_ref) {
2037 for nested_obligation in candidate.nested_obligations() {
2038 if !self.infcx.predicate_may_hold(&nested_obligation) {
2039 possibly_unsatisfied_predicates.push((
2040 self.resolve_vars_if_possible(nested_obligation.predicate),
2041 Some(self.resolve_vars_if_possible(obligation.predicate)),
2042 Some(nested_obligation.cause),
2043 ));
2044 }
2045 }
2046 }
2047 }
2048
2049 trait_predicate = Some(trait_ref.upcast(self.tcx));
2050 }
2051 ObjectCandidate(poly_trait_ref) | WhereClauseCandidate(poly_trait_ref) => {
2052 let trait_ref = self.instantiate_binder_with_fresh_vars(
2053 self.span,
2054 BoundRegionConversionTime::FnCall,
2055 poly_trait_ref,
2056 );
2057 (xform_self_ty, xform_ret_ty) =
2058 self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
2059
2060 if matches!(probe.kind, WhereClauseCandidate(_)) {
2061 match ocx.structurally_normalize_ty(
2065 cause,
2066 self.param_env,
2067 trait_ref.self_ty(),
2068 ) {
2069 Ok(ty) => {
2070 if !matches!(ty.kind(), ty::Param(_)) {
2071 debug!("--> not a param ty: {xform_self_ty:?}");
2072 return ProbeResult::NoMatch;
2073 }
2074 }
2075 Err(errors) => {
2076 debug!("--> cannot relate self-types {:?}", errors);
2077 return ProbeResult::NoMatch;
2078 }
2079 }
2080 }
2081
2082 xform_self_ty = ocx.normalize(cause, self.param_env, xform_self_ty);
2083 match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
2084 {
2085 Ok(()) => {}
2086 Err(err) => {
2087 debug!("--> cannot relate self-types {:?}", err);
2088 return ProbeResult::NoMatch;
2089 }
2090 }
2091 }
2092 }
2093
2094 if let Some(xform_ret_ty) = xform_ret_ty
2106 && self.infcx.next_trait_solver()
2107 {
2108 ocx.register_obligation(traits::Obligation::new(
2109 self.tcx,
2110 cause.clone(),
2111 self.param_env,
2112 ty::ClauseKind::WellFormed(xform_ret_ty.into()),
2113 ));
2114 }
2115
2116 for error in ocx.try_evaluate_obligations() {
2118 result = ProbeResult::NoMatch;
2119 let nested_predicate = self.resolve_vars_if_possible(error.obligation.predicate);
2120 if let Some(trait_predicate) = trait_predicate
2121 && nested_predicate == self.resolve_vars_if_possible(trait_predicate)
2122 {
2123 } else {
2127 possibly_unsatisfied_predicates.push((
2128 nested_predicate,
2129 Some(self.resolve_vars_if_possible(error.root_obligation.predicate))
2130 .filter(|root_predicate| *root_predicate != nested_predicate),
2131 Some(error.obligation.cause),
2132 ));
2133 }
2134 }
2135
2136 if let ProbeResult::Match = result
2137 && let Some(return_ty) = self.return_type
2138 && let Some(mut xform_ret_ty) = xform_ret_ty
2139 {
2140 if !matches!(probe.kind, InherentImplCandidate { .. }) {
2145 xform_ret_ty = ocx.normalize(&cause, self.param_env, xform_ret_ty);
2146 }
2147
2148 debug!("comparing return_ty {:?} with xform ret ty {:?}", return_ty, xform_ret_ty);
2149 match ocx.relate(cause, self.param_env, self.variance(), xform_ret_ty, return_ty) {
2150 Ok(()) => {}
2151 Err(_) => {
2152 result = ProbeResult::BadReturnType;
2153 }
2154 }
2155
2156 for error in ocx.try_evaluate_obligations() {
2158 result = ProbeResult::NoMatch;
2159 possibly_unsatisfied_predicates.push((
2160 error.obligation.predicate,
2161 Some(error.root_obligation.predicate)
2162 .filter(|predicate| *predicate != error.obligation.predicate),
2163 Some(error.root_obligation.cause),
2164 ));
2165 }
2166 }
2167
2168 if self.infcx.next_trait_solver() {
2169 if self.should_reject_candidate_due_to_opaque_treated_as_rigid(trait_predicate) {
2170 result = ProbeResult::NoMatch;
2171 }
2172 }
2173
2174 if let Err(_) = self.leak_check(outer_universe, Some(snapshot)) {
2180 result = ProbeResult::NoMatch;
2181 }
2182
2183 result
2184 })
2185 }
2186
2187 #[instrument(level = "debug", skip(self), ret)]
2202 fn should_reject_candidate_due_to_opaque_treated_as_rigid(
2203 &self,
2204 trait_predicate: Option<ty::Predicate<'tcx>>,
2205 ) -> bool {
2206 if let Some(predicate) = trait_predicate {
2218 let goal = Goal { param_env: self.param_env, predicate };
2219 if !self.infcx.goal_may_hold_opaque_types_jank(goal) {
2220 return true;
2221 }
2222 }
2223
2224 for step in self.steps {
2227 if step.self_ty_is_opaque {
2228 debug!(?step.autoderefs, ?step.self_ty, "self_type_is_opaque");
2229 let constrained_opaque = self.probe(|_| {
2230 let Ok(ok) = self.fcx.probe_instantiate_query_response(
2235 self.span,
2236 self.orig_steps_var_values,
2237 &step.self_ty,
2238 ) else {
2239 debug!("failed to instantiate self_ty");
2240 return false;
2241 };
2242 let ocx = ObligationCtxt::new(self);
2243 let self_ty = ocx.register_infer_ok_obligations(ok);
2244 if !ocx.try_evaluate_obligations().is_empty() {
2245 debug!("failed to prove instantiate self_ty obligations");
2246 return false;
2247 }
2248
2249 !self.resolve_vars_if_possible(self_ty).is_ty_var()
2250 });
2251 if constrained_opaque {
2252 debug!("opaque type has been constrained");
2253 return true;
2254 }
2255 }
2256 }
2257
2258 false
2259 }
2260
2261 fn collapse_candidates_to_trait_pick(
2279 &self,
2280 self_ty: Ty<'tcx>,
2281 probes: &[(&Candidate<'tcx>, ProbeResult)],
2282 ) -> Option<Pick<'tcx>> {
2283 let container = probes[0].0.item.trait_container(self.tcx)?;
2285 for (p, _) in &probes[1..] {
2286 let p_container = p.item.trait_container(self.tcx)?;
2287 if p_container != container {
2288 return None;
2289 }
2290 }
2291
2292 Some(Pick {
2295 item: probes[0].0.item,
2296 kind: TraitPick,
2297 import_ids: probes[0].0.import_ids.clone(),
2298 autoderefs: 0,
2299 autoref_or_ptr_adjustment: None,
2300 self_ty,
2301 unstable_candidates: vec![],
2302 receiver_steps: None,
2303 shadowed_candidates: vec![],
2304 })
2305 }
2306
2307 fn collapse_candidates_to_subtrait_pick(
2313 &self,
2314 self_ty: Ty<'tcx>,
2315 probes: &[(&Candidate<'tcx>, ProbeResult)],
2316 ) -> Option<Pick<'tcx>> {
2317 let mut child_candidate = probes[0].0;
2318 let mut child_trait = child_candidate.item.trait_container(self.tcx)?;
2319 let mut supertraits: SsoHashSet<_> = supertrait_def_ids(self.tcx, child_trait).collect();
2320
2321 let mut remaining_candidates: Vec<_> = probes[1..].iter().map(|&(p, _)| p).collect();
2322 while !remaining_candidates.is_empty() {
2323 let mut made_progress = false;
2324 let mut next_round = vec![];
2325
2326 for remaining_candidate in remaining_candidates {
2327 let remaining_trait = remaining_candidate.item.trait_container(self.tcx)?;
2328 if supertraits.contains(&remaining_trait) {
2329 made_progress = true;
2330 continue;
2331 }
2332
2333 let remaining_trait_supertraits: SsoHashSet<_> =
2339 supertrait_def_ids(self.tcx, remaining_trait).collect();
2340 if remaining_trait_supertraits.contains(&child_trait) {
2341 child_candidate = remaining_candidate;
2342 child_trait = remaining_trait;
2343 supertraits = remaining_trait_supertraits;
2344 made_progress = true;
2345 continue;
2346 }
2347
2348 next_round.push(remaining_candidate);
2354 }
2355
2356 if made_progress {
2357 remaining_candidates = next_round;
2359 } else {
2360 return None;
2363 }
2364 }
2365
2366 Some(Pick {
2367 item: child_candidate.item,
2368 kind: TraitPick,
2369 import_ids: child_candidate.import_ids.clone(),
2370 autoderefs: 0,
2371 autoref_or_ptr_adjustment: None,
2372 self_ty,
2373 unstable_candidates: vec![],
2374 shadowed_candidates: probes
2375 .iter()
2376 .map(|(c, _)| c.item)
2377 .filter(|item| item.def_id != child_candidate.item.def_id)
2378 .collect(),
2379 receiver_steps: None,
2380 })
2381 }
2382
2383 #[instrument(level = "debug", skip(self))]
2387 pub(crate) fn probe_for_similar_candidate(
2388 &mut self,
2389 ) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
2390 debug!("probing for method names similar to {:?}", self.method_name);
2391
2392 self.probe(|_| {
2393 let mut pcx = ProbeContext::new(
2394 self.fcx,
2395 self.span,
2396 self.mode,
2397 self.method_name,
2398 self.return_type,
2399 self.orig_steps_var_values,
2400 self.steps,
2401 self.scope_expr_id,
2402 IsSuggestion(true),
2403 );
2404 pcx.allow_similar_names = true;
2405 pcx.assemble_inherent_candidates();
2406 pcx.assemble_extension_candidates_for_all_traits();
2407
2408 let method_names = pcx.candidate_method_names(|_| true);
2409 pcx.allow_similar_names = false;
2410 let applicable_close_candidates: Vec<ty::AssocItem> = method_names
2411 .iter()
2412 .filter_map(|&method_name| {
2413 pcx.reset();
2414 pcx.method_name = Some(method_name);
2415 pcx.assemble_inherent_candidates();
2416 pcx.assemble_extension_candidates_for_all_traits();
2417 pcx.pick_core(&mut Vec::new()).and_then(|pick| pick.ok()).map(|pick| pick.item)
2418 })
2419 .collect();
2420
2421 if applicable_close_candidates.is_empty() {
2422 Ok(None)
2423 } else {
2424 let best_name = {
2425 let names = applicable_close_candidates
2426 .iter()
2427 .map(|cand| cand.name())
2428 .collect::<Vec<Symbol>>();
2429 find_best_match_for_name_with_substrings(
2430 &names,
2431 self.method_name.unwrap().name,
2432 None,
2433 )
2434 }
2435 .or_else(|| {
2436 applicable_close_candidates
2437 .iter()
2438 .find(|cand| self.matches_by_doc_alias(cand.def_id))
2439 .map(|cand| cand.name())
2440 });
2441 Ok(best_name.and_then(|best_name| {
2442 applicable_close_candidates
2443 .into_iter()
2444 .find(|method| method.name() == best_name)
2445 }))
2446 }
2447 })
2448 }
2449
2450 fn has_applicable_self(&self, item: &ty::AssocItem) -> bool {
2453 match self.mode {
2459 Mode::MethodCall => item.is_method(),
2460 Mode::Path => match item.kind {
2461 ty::AssocKind::Type { .. } => false,
2462 ty::AssocKind::Fn { .. } | ty::AssocKind::Const { .. } => true,
2463 },
2464 }
2465 }
2472
2473 fn record_static_candidate(&self, source: CandidateSource) {
2474 self.static_candidates.borrow_mut().push(source);
2475 }
2476
2477 #[instrument(level = "debug", skip(self))]
2478 fn xform_self_ty(
2479 &self,
2480 item: ty::AssocItem,
2481 impl_ty: Ty<'tcx>,
2482 args: GenericArgsRef<'tcx>,
2483 ) -> (Ty<'tcx>, Option<Ty<'tcx>>) {
2484 if item.is_fn() && self.mode == Mode::MethodCall {
2485 let sig = self.xform_method_sig(item.def_id, args);
2486 (sig.inputs()[0], Some(sig.output()))
2487 } else {
2488 (impl_ty, None)
2489 }
2490 }
2491
2492 #[instrument(level = "debug", skip(self))]
2493 fn xform_method_sig(&self, method: DefId, args: GenericArgsRef<'tcx>) -> ty::FnSig<'tcx> {
2494 let fn_sig = self.tcx.fn_sig(method);
2495 debug!(?fn_sig);
2496
2497 assert!(!args.has_escaping_bound_vars());
2498
2499 let generics = self.tcx.generics_of(method);
2505 assert_eq!(args.len(), generics.parent_count);
2506
2507 let xform_fn_sig = if generics.is_own_empty() {
2508 fn_sig.instantiate(self.tcx, args)
2509 } else {
2510 let args = GenericArgs::for_item(self.tcx, method, |param, _| {
2511 let i = param.index as usize;
2512 if i < args.len() {
2513 args[i]
2514 } else {
2515 match param.kind {
2516 GenericParamDefKind::Lifetime => {
2517 self.tcx.lifetimes.re_erased.into()
2519 }
2520 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
2521 self.var_for_def(self.span, param)
2522 }
2523 }
2524 }
2525 });
2526 fn_sig.instantiate(self.tcx, args)
2527 };
2528
2529 self.tcx.instantiate_bound_regions_with_erased(xform_fn_sig)
2530 }
2531
2532 fn is_relevant_kind_for_mode(&self, kind: ty::AssocKind) -> bool {
2534 match (self.mode, kind) {
2535 (Mode::MethodCall, ty::AssocKind::Fn { .. }) => true,
2536 (Mode::Path, ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. }) => true,
2537 _ => false,
2538 }
2539 }
2540
2541 fn matches_by_doc_alias(&self, def_id: DefId) -> bool {
2544 let Some(method) = self.method_name else {
2545 return false;
2546 };
2547 let Some(local_def_id) = def_id.as_local() else {
2548 return false;
2549 };
2550 let hir_id = self.fcx.tcx.local_def_id_to_hir_id(local_def_id);
2551 let attrs = self.fcx.tcx.hir_attrs(hir_id);
2552
2553 if is_doc_alias_attrs_contain_symbol(attrs.into_iter(), method.name) {
2554 return true;
2555 }
2556
2557 for attr in attrs {
2558 if attr.has_name(sym::rustc_confusables) {
2559 let Some(confusables) = attr.meta_item_list() else {
2560 continue;
2561 };
2562 for n in confusables {
2564 if let Some(lit) = n.lit()
2565 && method.name == lit.symbol
2566 {
2567 return true;
2568 }
2569 }
2570 }
2571 }
2572 false
2573 }
2574
2575 fn impl_or_trait_item(&self, def_id: DefId) -> SmallVec<[ty::AssocItem; 1]> {
2580 if let Some(name) = self.method_name {
2581 if self.allow_similar_names {
2582 let max_dist = max(name.as_str().len(), 3) / 3;
2583 self.tcx
2584 .associated_items(def_id)
2585 .in_definition_order()
2586 .filter(|x| {
2587 if !self.is_relevant_kind_for_mode(x.kind) {
2588 return false;
2589 }
2590 if let Some(d) = edit_distance_with_substrings(
2591 name.as_str(),
2592 x.name().as_str(),
2593 max_dist,
2594 ) {
2595 return d > 0;
2596 }
2597 self.matches_by_doc_alias(x.def_id)
2598 })
2599 .copied()
2600 .collect()
2601 } else {
2602 self.fcx
2603 .associated_value(def_id, name)
2604 .filter(|x| self.is_relevant_kind_for_mode(x.kind))
2605 .map_or_else(SmallVec::new, |x| SmallVec::from_buf([x]))
2606 }
2607 } else {
2608 self.tcx
2609 .associated_items(def_id)
2610 .in_definition_order()
2611 .filter(|x| self.is_relevant_kind_for_mode(x.kind))
2612 .copied()
2613 .collect()
2614 }
2615 }
2616}
2617
2618impl<'tcx> Candidate<'tcx> {
2619 fn to_unadjusted_pick(
2620 &self,
2621 self_ty: Ty<'tcx>,
2622 unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
2623 ) -> Pick<'tcx> {
2624 Pick {
2625 item: self.item,
2626 kind: match self.kind {
2627 InherentImplCandidate { .. } => InherentImplPick,
2628 ObjectCandidate(_) => ObjectPick,
2629 TraitCandidate(_) => TraitPick,
2630 WhereClauseCandidate(trait_ref) => {
2631 assert!(
2637 !trait_ref.skip_binder().args.has_infer()
2638 && !trait_ref.skip_binder().args.has_placeholders()
2639 );
2640
2641 WhereClausePick(trait_ref)
2642 }
2643 },
2644 import_ids: self.import_ids.clone(),
2645 autoderefs: 0,
2646 autoref_or_ptr_adjustment: None,
2647 self_ty,
2648 unstable_candidates,
2649 receiver_steps: match self.kind {
2650 InherentImplCandidate { receiver_steps, .. } => Some(receiver_steps),
2651 _ => None,
2652 },
2653 shadowed_candidates: vec![],
2654 }
2655 }
2656}