Skip to main content

hir_ty/method_resolution/
probe.rs

1//! Candidate assembly and selection in method resolution - where we enumerate all candidates
2//! and choose the best one (or, in some IDE scenarios, just enumerate them all).
3
4use 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    /// This is the OriginalQueryValues for the steps queries
53    /// that are answered in steps.
54    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    /// List of potential private candidates. Will be trimmed to ones that
62    /// actually apply and then the result inserted into `private_candidate`
63    private_candidates: Vec<Candidate<'db>>,
64
65    /// Collects near misses when the candidate functions are missing a `self` keyword and is only
66    /// used for error reporting
67    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/// When adjusting a receiver we often want to do one of
99///
100/// - Add a `&` (or `&mut`), converting the receiver from `T` to `&T` (or `&mut T`)
101/// - If the receiver has type `*mut T`, convert it to `*const T`
102///
103/// This type tells us which one to do.
104///
105/// Note that in principle we could do both at the same time. For example, when the receiver has
106/// type `T`, we could autoref it to `&T`, then convert to `*const T`. Or, when it has type `*mut
107/// T`, we could convert it to `*const T`, then autoref to `&*const T`. However, currently we do
108/// (at most) one of these. Either the receiver has type `T` and we convert it to `&T` (or with
109/// `mut`), or it has type `*mut T` and we convert it to `*const T`.
110#[derive(Debug, PartialEq, Copy, Clone)]
111pub enum AutorefOrPtrAdjustment {
112    /// Receiver has type `T`, add `&` or `&mut` (if `T` is `mut`), and maybe also "unsize" it.
113    /// Unsizing is used to convert a `[T; N]` to `[T]`, which only makes sense when autorefing.
114    Autoref {
115        mutbl: Mutability,
116
117        /// Indicates that the source expression should be "unsized" to a target type.
118        /// This is special-cased for just arrays unsizing to slices.
119        unsize: bool,
120    },
121    /// Receiver has type `*mut T`, convert to `*const T`
122    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/// Criteria to apply when searching for a given Pick. This is used during
135/// the search for potentially shadowed methods to ensure we don't search
136/// more candidates than strictly necessary.
137#[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        // An item never shadows itself
151        candidate.item != self.def_id
152            // and we're only concerned about inherent impls doing the shadowing.
153            // Shadowing can only occur if the shadowed is further along
154            // the Receiver dereferencing chain than the shadowed.
155            && 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    /// Indicates that the source expression should be autoderef'd N times
171    /// ```ignore (not-rust)
172    /// A = expr | *expr | **expr | ...
173    /// ```
174    pub autoderefs: usize,
175
176    /// Indicates that we want to add an autoref (and maybe also unsize it), or if the receiver is
177    /// `*mut T`, convert it to `*const T`.
178    pub autoref_or_ptr_adjustment: Option<AutorefOrPtrAdjustment>,
179    pub self_ty: Ty<'db>,
180
181    /// Number of jumps along the `Receiver::Target` chain we followed
182    /// to identify this method. Used only for deshadowing errors.
183    /// Only applies for inherent impls.
184    pub receiver_steps: Option<usize>,
185
186    /// Candidates that were shadowed by supertraits.
187    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        // Trait
197        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    // An expression of the form `receiver.method_name(...)`.
206    // Autoderefs are performed on `receiver`, lookup is done based on the
207    // `self` argument of the method, and static methods aren't considered.
208    MethodCall,
209    // An expression of the form `Type::item` or `<T>::item`.
210    // No autoderefs are performed, lookup is done based on the type each
211    // implementation is for, and static methods are included.
212    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    /// `true` if the type results from a dereference of a raw pointer.
221    /// when assembling candidates, we include these steps, but not when
222    /// picking methods. This so that if we have `foo: *const Foo` and `Foo` has methods
223    /// `fn by_raw_ptr(self: *const Self)` and `fn by_ref(&self)`, then
224    /// `foo.by_raw_ptr()` will work and `foo.by_ref()` won't.
225    pub from_unsafe_deref: bool,
226    pub unsize: bool,
227    /// We will generate CandidateSteps which are reachable via a chain
228    /// of following `Receiver`. The first 'n' of those will be reachable
229    /// by following a chain of 'Deref' instead (since there's a blanket
230    /// implementation of Receiver for Deref).
231    /// We use the entire set of steps when identifying method candidates
232    /// (e.g. identifying relevant `impl` blocks) but only those that are
233    /// reachable via Deref when examining what the receiver type can
234    /// be converted into by autodereffing.
235    pub reachable_via_deref: bool,
236}
237
238#[derive(Clone, Debug)]
239struct MethodAutoderefStepsResult<'db> {
240    /// The valid autoderef steps that could be found by following a chain
241    /// of `Receiver<Target=T>` or `Deref<Target=T>` trait implementations.
242    pub steps: SmallVec<[CandidateStep<'db>; 3]>,
243    /// If Some(T), a type autoderef reported an error on.
244    pub opt_bad_ty: Option<MethodAutoderefBadTy<'db>>,
245    /// If `true`, `steps` has been truncated due to reaching the
246    /// recursion limit.
247    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                // Mode::Path - the deref steps is "trivial". This turns
283                // our CanonicalQuery into a "trivial" QueryResponse. This
284                // is a bit inefficient, but I don't think that writing
285                // special handling for this "trivial case" is a good idea.
286
287                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            // FIXME: Report an error.
314        }
315
316        // If we encountered an `_` type or an error type during autoderef, this is
317        // ambiguous.
318        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                // this case used to be allowed by the compiler,
324                // so we do a future-compat lint here for the 2015 edition
325                // (see https://github.com/rust-lang/rust/issues/46906)
326                // FIXME: Emit the lint.
327                // self.tcx.node_span_lint(
328                //     lint::builtin::TYVAR_BEHIND_RAW_POINTER,
329                //     scope_expr_id,
330                //     span,
331                //     |lint| {
332                //         lint.primary_message("type annotations needed");
333                //     },
334                // );
335            } else {
336                // Ended up encountering a type variable when doing autoderef,
337                // but it may not be a type variable after processing obligations
338                // in our local `FnCtxt`, so don't call `structurally_resolve_type`.
339                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                        // FIXME: Report "type annotations needed" error.
353                    }
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        // this creates one big transaction so that all type variables etc
364        // that we create during the probe process are removed later
365        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            // We accept not-yet-defined opaque types in the autoderef
382            // chain to support recursive calls. We do error if the final
383            // infer var is not an opaque.
384            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            // If arbitrary self types is not enabled, we follow the chain of
398            // `Deref<Target=T>`. If arbitrary self types is enabled, we instead
399            // follow the chain of `Receiver<Target=T>`, but we also record whether
400            // such types are reachable by following the (potentially shorter)
401            // chain of `Deref<Target=T>`. We will use the first list when finding
402            // potentially relevant function implementations (e.g. relevant impl blocks)
403            // but the second list when determining types that the receiver may be
404            // converted to, in order to find out which of those methods might actually
405            // be callable.
406            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                            // all the subsequent steps will be from_unsafe_deref
439                            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                            // all the subsequent steps will be from_unsafe_deref
463                            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                        // this could be from an unsafe deref if we had
501                        // a *mut/const [T; N]
502                        from_unsafe_deref: reached_raw_pointer,
503                        unsize: true,
504                        reachable_via_deref: true, // this is always the final type from
505                                                   // autoderef_via_deref
506                    });
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    /// Finds the method with the appropriate name (or return type, as the case may be).
524    // The length of the returned iterator is nearly always 0 or 1 and this
525    // method is fairly hot.
526    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    /// Some(candidate) if there is a private candidate
575    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            // We collapse to a subtrait pick *after* filtering unstable candidates
619            // to make sure we don't prefer a unstable subtrait method over a stable
620            // supertrait method.
621            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            // Check we're not shadowing others
697            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            // We should not override existing entries, because inherent methods of trait objects (from the principal)
758            // are also visited as trait methods, and we want to consider them inherent.
759            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    /// When we're looking up a method by path (UFCS), we relate the receiver
861    /// types invariantly. When we are looking up a method by the `.` operator,
862    /// we relate them covariantly.
863    fn variance(&self) -> Variance {
864        match self.mode {
865            Mode::MethodCall => Variance::Covariant,
866            Mode::Path => Variance::Invariant,
867        }
868    }
869
870    ///////////////////////////////////////////////////////////////////////////
871    // CANDIDATE ASSEMBLY
872
873    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                    // Subtle: we can't use `instantiate_query_response` here: using it will
912                    // commit to all of the type equalities assumed by inference going through
913                    // autoderef (see the `method-probe-no-guessing` test).
914                    //
915                    // However, in this code, it is OK if we end up with an object type that is
916                    // "more general" than the object type that we are evaluating. For *every*
917                    // object type `MY_OBJECT`, a function call that goes through a trait-ref
918                    // of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
919                    // `ObjectCandidate`, and it should be discoverable "exactly" through one
920                    // of the iterations in the autoderef loop, so there is no problem with it
921                    // being discoverable in another one of these iterations.
922                    //
923                    // Using `instantiate_canonical` on our
924                    // `Canonical<QueryResponse<Ty<'db>>>` and then *throwing away* the
925                    // `CanonicalVarValues` will exactly give us such a generalization - it
926                    // will still match the original object type, but it won't pollute our
927                    // type variables in any form, so just do that!
928                    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; // already visited
1018        }
1019
1020        self.with_impl_item(impl_def_id, |this, item| {
1021            if !this.has_applicable_self(item) {
1022                // No receiver declared. Not a candidate.
1023                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        // It is illegal to invoke a method on a trait instance that refers to
1045        // the `Self` type. An [`DynCompatibilityViolation::SupertraitSelf`] error
1046        // will be reported by `dyn_compatibility.rs` if the method refers to the
1047        // `Self` type anywhere other than the receiver. Here, we use a
1048        // instantiation that replaces `Self` with the object type itself. Hence,
1049        // a `&self` method will wind up with an argument type like `&dyn Trait`.
1050        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        // We use `DeepRejectCtxt` here which may return false positive on where clauses
1066        // with alias self types. We need to later on reject these as inherent candidates
1067        // in `consider_probe`.
1068        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    // Do a search through a list of bounds, using a callback to actually
1094    // create the candidates.
1095    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            // Check whether `trait_def_id` defines a method with suitable name.
1128            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
1146///////////////////////////////////////////////////////////////////////////
1147// THE ACTUAL SEARCH
1148impl<'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    /// Check for cases where arbitrary self types allows shadowing
1169    /// of methods that might be a compatibility break. Specifically,
1170    /// we have something like:
1171    /// ```ignore (illustrative)
1172    /// struct A;
1173    /// impl A {
1174    ///   fn foo(self: &NonNull<A>) {}
1175    ///      // note this is by reference
1176    /// }
1177    /// ```
1178    /// then we've come along and added this method to `NonNull`:
1179    /// ```ignore (illustrative)
1180    ///   fn foo(self)  // note this is by value
1181    /// ```
1182    /// Report an error in this case.
1183    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        // The errors emitted by this function are part of
1192        // the arbitrary self types work, and should not impact
1193        // other users.
1194        if !self.ctx.features.arbitrary_self_types
1195            && !self.ctx.features.arbitrary_self_types_pointers
1196        {
1197            return Ok(());
1198        }
1199
1200        // Set criteria for how we find methods possibly shadowed by 'possible_shadower'
1201        let pick_constraints = PickConstraintsForShadowed {
1202            // It's the same `self` type...
1203            autoderefs: possible_shadower.autoderefs,
1204            // ... but the method was found in an impl block determined
1205            // by searching further along the Receiver chain than the other,
1206            // showing that it's a smart pointer type causing the problem...
1207            receiver_steps: possible_shadower.receiver_steps,
1208            // ... and they don't end up pointing to the same item in the
1209            // first place (could happen with things like blanket impls for T)
1210            def_id: possible_shadower.item,
1211        };
1212        // A note on the autoderefs above. Within pick_by_value_method, an extra
1213        // autoderef may be applied in order to reborrow a reference with
1214        // a different lifetime. That seems as though it would break the
1215        // logic of these constraints, since the number of autoderefs could
1216        // no longer be used to identify the fundamental type of the receiver.
1217        // However, this extra autoderef is applied only to by-value calls
1218        // where the receiver is already a reference. So this situation would
1219        // only occur in cases where the shadowing looks like this:
1220        // ```
1221        // struct A;
1222        // impl A {
1223        //   fn foo(self: &&NonNull<A>) {}
1224        //      // note this is by DOUBLE reference
1225        // }
1226        // ```
1227        // then we've come along and added this method to `NonNull`:
1228        // ```
1229        //   fn foo(&self)  // note this is by single reference
1230        // ```
1231        // and the call is:
1232        // ```
1233        // let bar = NonNull<Foo>;
1234        // let bar = &foo;
1235        // bar.foo();
1236        // ```
1237        // In these circumstances, the logic is wrong, and we wouldn't spot
1238        // the shadowing, because the autoderef-based maths wouldn't line up.
1239        // This is a niche case and we can live without generating an error
1240        // in the case of such shadowing.
1241        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        // Look for actual pairs of shadower/shadowed which are
1249        // the sort of shadowing case we want to avoid. Specifically...
1250        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            // At this point we're considering the types to which the receiver can be converted,
1266            // so we want to follow the `Deref` chain not the `Receiver` chain. Filter out
1267            // steps which can only be reached by following the (longer) `Receiver` chain.
1268            .filter(|step| step.reachable_via_deref)
1269            .filter(|step| {
1270                debug!("pick_all_method: step={:?}", step);
1271                // Skip types with type errors (but not const/lifetime errors, which are
1272                // often spurious due to incomplete const evaluation) and raw pointer derefs.
1273                !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                // Check for shadowing of a by-reference method by a by-value method (see comments on check_for_shadowing)
1290                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                    // Don't autoref in path mode.
1303                    // rustc doesn't do that and it's not a big deal as non-autorefd methods take priority
1304                    // and if an autorefd one is selected, we'll register the `NonAutorefdT: Trait` obligation
1305                    // (which will fail) anyway. But it does have an impact when probing for all methods,
1306                    // which is something we need to stay accurate.
1307                    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                // Check for shadowing of a by-mut-ref method by a by-reference method (see comments on check_for_shadowing)
1318                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                // Note that no shadowing errors are produced from here on,
1330                // as we consider const ptr methods.
1331                // We allow new methods that take *mut T to shadow
1332                // methods which took *const T, so there is no entry in
1333                // this list for the results of `pick_const_ptr_method`.
1334                // The reason is that the standard pointer cast method
1335                // (on a mutable pointer) always already shadows the
1336                // cast method (on a const pointer). So, if we added
1337                // `pick_const_ptr_method` to this method, the anti-
1338                // shadowing algorithm would always complain about
1339                // the conflict between *const::cast and *mut::cast.
1340                // In practice therefore this does constrain us:
1341                // we cannot add new
1342                //   self: *mut Self
1343                // methods to types such as NonNull or anything else
1344                // which implements Receiver, because this might in future
1345                // shadow existing methods taking
1346                //   self: *const NonNull<Self>
1347                // in the pointee. In practice, methods taking raw pointers
1348                // are rare, and it seems that it should be easily possible
1349                // to avoid such compatibility breaks.
1350                // We also don't check for reborrowed pin methods which
1351                // may be shadowed; these also seem unlikely to occur.
1352                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    /// For each type `T` in the step list, this attempts to find a method where
1364    /// the (transformed) self type is exactly `T`. We do however do one
1365    /// transformation on the adjustment: if we are passing a region pointer in,
1366    /// we will potentially *reborrow* it to a shorter lifetime. This allows us
1367    /// to transparently pass `&mut` pointers, in particular, without consuming
1368    /// them for their entire lifetime.
1369    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                    // Insert a `&*` or `&mut *` if this is a reference type:
1385                    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        // In general, during probing we erase regions.
1418        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    /// If `self_ty` is `*mut T` then this picks `*const T` methods. The reason why we have a
1434    /// special case for this is because going from `*mut T` to `*const T` with autoderefs and
1435    /// autorefs would require dereferencing the pointer, which is not safe.
1436    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        // Don't convert an unsized reference to ptr
1443        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    /// Used for ambiguous method call error reporting. Uses probing that throws away the result internally,
1525    /// so do not use to make a decision that may lead to a successful compilation.
1526    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                // Guide the trait selection to show impls that have methods whose type matches
1544                // up with the `self` parameter of the method.
1545                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                        // If only a single impl matches, make the error message point
1552                        // to that impl.
1553                        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            // Subtle: we're not *really* instantiating the current self type while
1582            // probing, but instead fully recompute the autoderef steps once we've got
1583            // a final `Pick`. We can't nicely handle these obligations outside of a probe.
1584            //
1585            // We simply handle them for each candidate here for now. That's kinda scuffed
1586            // and ideally we just put them into the `FnCtxt` right away. We need to consider
1587            // them to deal with defining uses in `method_autoderef_steps`.
1588            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                    // Check whether the impl imposes obligations we have to worry about.
1622                    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                    // Convert the bounds into obligations.
1631                    ocx.register_obligations(impl_bounds);
1632                }
1633                TraitCandidate(poly_trait_ref) => {
1634                    // Some trait methods are excluded for arrays before 2021.
1635                    // (`array.into_iter()` wants a slice iterator for compatibility.)
1636                    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                    // Some trait methods are excluded for boxed slices before 2024.
1648                    // (`boxed_slice.into_iter()` wants a slice iterator for compatibility.)
1649                    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                    // We only need this hack to deal with fatal overflow in the old solver.
1693                    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                        // `WhereClauseCandidate` requires that the self type is a param,
1711                        // because it has special behavior with candidate preference as an
1712                        // inherent pick.
1713                        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            // See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/134>.
1748            //
1749            // In the new solver, check the well-formedness of the return type.
1750            // This emulates, in a way, the predicates that fall out of
1751            // normalizing the return type in the old solver.
1752            //
1753            // FIXME(-Znext-solver): We alternatively could check the predicates of
1754            // the method itself hold, but we intentionally do not do this in the old
1755            // solver b/c of cycles, and doing it in the new solver would be stronger.
1756            // This should be fixed in the future, since it likely leads to much better
1757            // method winnowing.
1758            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            // FIXME: Need to leak-check here.
1776            // if let Err(_) = self.leak_check(outer_universe, Some(snapshot)) {
1777            //     result = ProbeResult::NoMatch;
1778            // }
1779
1780            result
1781        })
1782    }
1783
1784    /// Trait candidates for not-yet-defined opaque types are a somewhat hacky.
1785    ///
1786    /// We want to only accept trait methods if they were hold even if the
1787    /// opaque types were rigid. To handle this, we both check that for trait
1788    /// candidates the goal were to hold even when treating opaques as rigid,
1789    /// see `rustc_trait_selection::solve::OpaqueTypesJank`.
1790    ///
1791    /// We also check that all opaque types encountered as self types in the
1792    /// autoderef chain don't get constrained when applying the candidate.
1793    /// Importantly, this also handles calling methods taking `&self` on
1794    /// `impl Trait` to reject the "by-self" candidate.
1795    ///
1796    /// This needs to happen at the end of `consider_probe` as we need to take
1797    /// all the constraints from that into account.
1798    #[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        // This function is what hacky and doesn't perfectly do what we want it to.
1804        // It's not soundness critical and we should be able to freely improve this
1805        // in the future.
1806        //
1807        // Some concrete edge cases include the fact that `goal_may_hold_opaque_types_jank`
1808        // also fails if there are any constraints opaques which are never used as a self
1809        // type. We also allow where-bounds which are currently ambiguous but end up
1810        // constraining an opaque later on.
1811
1812        // Check whether the trait candidate would not be applicable if the
1813        // opaque type were rigid.
1814        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        // Check whether any opaque types in the autoderef chain have been
1822        // constrained.
1823        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                    // If we fail to instantiate the self type of this
1828                    // step, this part of the deref-chain is no longer
1829                    // reachable. In this case we don't care about opaque
1830                    // types there.
1831                    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    /// Sometimes we get in a situation where we have multiple probes that are all impls of the
1860    /// same trait, but we don't know which impl to use. In this case, since in all cases the
1861    /// external interface of the method can be determined from the trait, it's ok not to decide.
1862    /// We can basically just collapse all of the probes for various impls into one where-clause
1863    /// probe. This will result in a pending obligation so when more type-info is available we can
1864    /// make the final decision.
1865    ///
1866    /// Example (`tests/ui/methods/method-two-trait-defer-resolution-1.rs`):
1867    ///
1868    /// ```ignore (illustrative)
1869    /// trait Foo { ... }
1870    /// impl Foo for Vec<i32> { ... }
1871    /// impl Foo for Vec<usize> { ... }
1872    /// ```
1873    ///
1874    /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
1875    /// use, so it's ok to just commit to "using the method from the trait Foo".
1876    fn collapse_candidates_to_trait_pick(
1877        &self,
1878        self_ty: Ty<'db>,
1879        probes: &[&Candidate<'db>],
1880    ) -> Option<Pick<'db>> {
1881        // Do all probes correspond to the same trait?
1882        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        // FIXME: check the return type here somehow.
1895        // If so, just use this trait and call it a day.
1896        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    /// Much like `collapse_candidates_to_trait_pick`, this method allows us to collapse
1908    /// multiple conflicting picks if there is one pick whose trait container is a subtrait
1909    /// of the trait containers of all of the other picks.
1910    ///
1911    /// This implements RFC #3624.
1912    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                // This pick is not a supertrait of the `child_pick`.
1942                // Check if it's a subtrait of the `child_pick`, instead.
1943                // If it is, then it must have been a subtrait of every
1944                // other pick we've eliminated at this point. It will
1945                // take over at this point.
1946                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                // `child_pick` is not a supertrait of this pick.
1957                // Don't bail here, since we may be comparing two supertraits
1958                // of a common subtrait. These two supertraits won't be related
1959                // at all, but we will pick them up next round when we find their
1960                // child as we continue iterating in this round.
1961                next_round.push(remaining_candidate);
1962            }
1963
1964            if made_progress {
1965                // If we've made progress, iterate again.
1966                remaining_candidates = next_round;
1967            } else {
1968                // Otherwise, we must have at least two candidates which
1969                // are not related to each other at all.
1970                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    ///////////////////////////////////////////////////////////////////////////
1990    // MISCELLANY
1991    fn has_applicable_self(&self, item: CandidateId) -> bool {
1992        // "Fast track" -- check for usage of sugar when in method call
1993        // mode.
1994        //
1995        // In Path mode (i.e., resolving a value like `T::next`), consider any
1996        // associated value (i.e., methods, constants).
1997        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        // FIXME -- check for types that deref to `Self`,
2004        // like `Rc<Self>` and so on.
2005        //
2006        // Note also that the current code will break if this type
2007        // includes any of the type parameters defined on the method
2008        // -- but this could be overcome.
2009    }
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        // It is possible for type parameters or early-bound lifetimes
2040        // to appear in the signature of `self`. The generic parameters
2041        // we are given do not include type/lifetime parameters for the
2042        // method yet. So create fresh variables here for those too,
2043        // if there are any.
2044        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                                // In general, during probe we erase regions.
2060                                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
2087/// Determine if the given associated item type is relevant in the current context.
2088fn 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                    // Only trait derived from where-clauses should
2107                    // appear here, so they should not contain any
2108                    // inference variables or other artifacts. This
2109                    // means they are safe to put into the
2110                    // `WhereClausePick`.
2111                    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}