Skip to main content

rustc_hir_typeck/method/
probe.rs

1use std::cell::{Cell, RefCell};
2use std::cmp::max;
3use std::debug_assert_matches;
4use std::ops::Deref;
5
6use rustc_data_structures::fx::FxHashSet;
7use rustc_data_structures::sso::SsoHashSet;
8use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level};
9use rustc_hir::attrs::lang_items::LangItem;
10use rustc_hir::def::DefKind;
11use rustc_hir::{self as hir, ExprKind, HirId, Node, find_attr};
12use rustc_hir_analysis::autoderef::{self, Autoderef};
13use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
14use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, TyCtxtInferExt};
15use rustc_infer::traits::{ObligationCauseCode, PredicateObligation, query};
16use rustc_lint_defs::builtin::{
17    METHOD_CALL_ON_DIVERGING_INFER_VAR, TYVAR_BEHIND_RAW_POINTER, UNSTABLE_NAME_COLLISIONS,
18};
19use rustc_macros::Diagnostic;
20use rustc_middle::middle::stability;
21use rustc_middle::ty::elaborate::supertrait_def_ids;
22use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type};
23use rustc_middle::ty::{
24    self, AssocContainer, AssocItem, GenericArgs, GenericArgsRef, GenericParamDefKind, ParamEnvAnd,
25    Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast,
26};
27use rustc_middle::{bug, span_bug};
28use rustc_span::def_id::{DefId, LocalDefId};
29use rustc_span::edit_distance::{
30    edit_distance_with_substrings, find_best_match_for_name_with_substrings,
31};
32use rustc_span::{DUMMY_SP, Ident, Span, Symbol};
33use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
34use rustc_trait_selection::infer::InferCtxtExt as _;
35use rustc_trait_selection::solve::Goal;
36use rustc_trait_selection::traits::query::CanonicalMethodAutoderefStepsGoal;
37use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
38use rustc_trait_selection::traits::query::method_autoderef::{
39    CandidateStep, MethodAutoderefBadTy, MethodAutoderefStepsResult,
40};
41use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt};
42use smallvec::SmallVec;
43use tracing::{debug, instrument};
44
45use self::CandidateKind::*;
46pub(crate) use self::PickKind::*;
47use super::{CandidateSource, MethodError, NoMatchData, suggest};
48use crate::FnCtxt;
49
50/// Boolean flag used to indicate if this search is for a suggestion
51/// or not. If true, we can allow ambiguity and so forth.
52#[derive(#[automatically_derived]
impl ::core::clone::Clone for IsSuggestion {
    #[inline]
    fn clone(&self) -> IsSuggestion {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for IsSuggestion { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for IsSuggestion {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "IsSuggestion",
            &&self.0)
    }
}Debug)]
53pub(crate) struct IsSuggestion(pub bool);
54
55pub(crate) struct ProbeContext<'a, 'tcx> {
56    fcx: &'a FnCtxt<'a, 'tcx>,
57    span: Span,
58    mode: Mode,
59    method_name: Option<Ident>,
60    return_type: Option<Ty<'tcx>>,
61
62    /// This is the OriginalQueryValues for the steps queries
63    /// that are answered in steps.
64    orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
65    steps: &'tcx [CandidateStep<'tcx>],
66
67    inherent_candidates: Vec<Candidate<'tcx>>,
68    extension_candidates: Vec<Candidate<'tcx>>,
69    impl_dups: FxHashSet<DefId>,
70
71    /// When probing for names, include names that are close to the
72    /// requested name (by edit distance)
73    allow_similar_names: bool,
74
75    /// List of potential private candidates. Will be trimmed to ones that
76    /// actually apply and then the result inserted into `private_candidate`
77    private_candidates: Vec<Candidate<'tcx>>,
78
79    /// Some(candidate) if there is a private candidate
80    private_candidate: Cell<Option<(DefKind, DefId)>>,
81
82    /// Collects near misses when the candidate functions are missing a `self` keyword and is only
83    /// used for error reporting
84    static_candidates: RefCell<Vec<CandidateSource>>,
85
86    scope_expr_id: HirId,
87
88    /// Is this probe being done for a diagnostic? This will skip some error reporting
89    /// machinery, since we don't particularly care about, for example, similarly named
90    /// candidates if we're *reporting* similarly named candidates.
91    is_suggestion: IsSuggestion,
92
93    /// Hack for applying method probing routine for arbitrary types
94    /// in order to get adjustments as if they were at receiver position.
95    /// Used only for delegation's `Self` arguments mapping.
96    /// FIXME(fn_delegation): now this hack is used, however in perfect world
97    /// we would like to separate adjustments finding logic from probe context,
98    /// if we do so we will be able to find wanted adjustments given only two
99    /// types without reusing the whole method probing routine
100    self_ty_override: Option<Ty<'tcx>>,
101}
102
103impl<'a, 'tcx> Deref for ProbeContext<'a, 'tcx> {
104    type Target = FnCtxt<'a, 'tcx>;
105    fn deref(&self) -> &Self::Target {
106        self.fcx
107    }
108}
109
110#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Candidate<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Candidate",
            "item", &self.item, "kind", &self.kind, "import_ids",
            &&self.import_ids)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for Candidate<'tcx> {
    #[inline]
    fn clone(&self) -> Candidate<'tcx> {
        Candidate {
            item: ::core::clone::Clone::clone(&self.item),
            kind: ::core::clone::Clone::clone(&self.kind),
            import_ids: ::core::clone::Clone::clone(&self.import_ids),
        }
    }
}Clone)]
111pub(crate) struct Candidate<'tcx> {
112    pub(crate) item: ty::AssocItem,
113    pub(crate) kind: CandidateKind<'tcx>,
114    pub(crate) import_ids: &'tcx [LocalDefId],
115}
116
117#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CandidateKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            CandidateKind::InherentImplCandidate {
                impl_def_id: __self_0, receiver_steps: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "InherentImplCandidate", "impl_def_id", __self_0,
                    "receiver_steps", &__self_1),
            CandidateKind::ObjectCandidate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ObjectCandidate", &__self_0),
            CandidateKind::TraitCandidate(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "TraitCandidate", __self_0, &__self_1),
            CandidateKind::WhereClauseCandidate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "WhereClauseCandidate", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for CandidateKind<'tcx> {
    #[inline]
    fn clone(&self) -> CandidateKind<'tcx> {
        match self {
            CandidateKind::InherentImplCandidate {
                impl_def_id: __self_0, receiver_steps: __self_1 } =>
                CandidateKind::InherentImplCandidate {
                    impl_def_id: ::core::clone::Clone::clone(__self_0),
                    receiver_steps: ::core::clone::Clone::clone(__self_1),
                },
            CandidateKind::ObjectCandidate(__self_0) =>
                CandidateKind::ObjectCandidate(::core::clone::Clone::clone(__self_0)),
            CandidateKind::TraitCandidate(__self_0, __self_1) =>
                CandidateKind::TraitCandidate(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            CandidateKind::WhereClauseCandidate(__self_0) =>
                CandidateKind::WhereClauseCandidate(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
118pub(crate) enum CandidateKind<'tcx> {
119    InherentImplCandidate { impl_def_id: DefId, receiver_steps: usize },
120    ObjectCandidate(ty::PolyTraitRef<'tcx>),
121    TraitCandidate(ty::PolyTraitRef<'tcx>, bool /* lint_ambiguous */),
122    WhereClauseCandidate(ty::PolyTraitRef<'tcx>),
123}
124
125#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ProbeResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ProbeResult::NoMatch => "NoMatch",
                ProbeResult::BadReturnType => "BadReturnType",
                ProbeResult::Match => "Match",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ProbeResult {
    #[inline]
    fn eq(&self, other: &ProbeResult) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ProbeResult {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::marker::Copy for ProbeResult { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ProbeResult {
    #[inline]
    fn clone(&self) -> ProbeResult { *self }
}Clone)]
126enum ProbeResult {
127    NoMatch,
128    BadReturnType,
129    Match,
130}
131
132/// When adjusting a receiver we often want to do one of
133///
134/// - Add a `&` (or `&mut`), converting the receiver from `T` to `&T` (or `&mut T`)
135/// - If the receiver has type `*mut T`, convert it to `*const T`
136///
137/// This type tells us which one to do.
138///
139/// Note that in principle we could do both at the same time. For example, when the receiver has
140/// type `T`, we could autoref it to `&T`, then convert to `*const T`. Or, when it has type `*mut
141/// T`, we could convert it to `*const T`, then autoref to `&*const T`. However, currently we do
142/// (at most) one of these. Either the receiver has type `T` and we convert it to `&T` (or with
143/// `mut`), or it has type `*mut T` and we convert it to `*const T`.
144#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AutorefOrPtrAdjustment {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            AutorefOrPtrAdjustment::Autoref {
                mutbl: __self_0, unsize: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Autoref", "mutbl", __self_0, "unsize", &__self_1),
            AutorefOrPtrAdjustment::ToConstPtr =>
                ::core::fmt::Formatter::write_str(f, "ToConstPtr"),
            AutorefOrPtrAdjustment::ReborrowPin(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ReborrowPin", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AutorefOrPtrAdjustment {
    #[inline]
    fn eq(&self, other: &AutorefOrPtrAdjustment) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (AutorefOrPtrAdjustment::Autoref {
                    mutbl: __self_0, unsize: __self_1 },
                    AutorefOrPtrAdjustment::Autoref {
                    mutbl: __arg1_0, unsize: __arg1_1 }) =>
                    __self_1 == __arg1_1 && __self_0 == __arg1_0,
                (AutorefOrPtrAdjustment::ReborrowPin(__self_0),
                    AutorefOrPtrAdjustment::ReborrowPin(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::marker::Copy for AutorefOrPtrAdjustment { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AutorefOrPtrAdjustment {
    #[inline]
    fn clone(&self) -> AutorefOrPtrAdjustment {
        let _: ::core::clone::AssertParamIsClone<hir::Mutability>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<hir::Mutability>;
        *self
    }
}Clone)]
145pub(crate) enum AutorefOrPtrAdjustment {
146    /// Receiver has type `T`, add `&` or `&mut` (if `T` is `mut`), and maybe also "unsize" it.
147    /// Unsizing is used to convert a `[T; N]` to `[T]`, which only makes sense when autorefing.
148    Autoref {
149        mutbl: hir::Mutability,
150
151        /// Indicates that the source expression should be "unsized" to a target type.
152        /// This is special-cased for just arrays unsizing to slices.
153        unsize: bool,
154    },
155    /// Receiver has type `*mut T`, convert to `*const T`
156    ToConstPtr,
157
158    /// Reborrow a `Pin<&mut T>` or `Pin<&T>`.
159    ReborrowPin(hir::Mutability),
160}
161
162impl AutorefOrPtrAdjustment {
163    fn get_unsize(&self) -> bool {
164        match self {
165            AutorefOrPtrAdjustment::Autoref { mutbl: _, unsize } => *unsize,
166            AutorefOrPtrAdjustment::ToConstPtr => false,
167            AutorefOrPtrAdjustment::ReborrowPin(_) => false,
168        }
169    }
170}
171
172/// Extra information required only for error reporting.
173#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::fmt::Debug for PickDiagHints<'a, 'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "PickDiagHints",
            "unstable_candidates", &self.unstable_candidates,
            "unsatisfied_predicates", &&self.unsatisfied_predicates)
    }
}Debug)]
174struct PickDiagHints<'a, 'tcx> {
175    /// Unstable candidates alongside the stable ones.
176    unstable_candidates: Option<Vec<(Candidate<'tcx>, Symbol)>>,
177
178    /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
179    /// for error reporting
180    unsatisfied_predicates: &'a mut UnsatisfiedPredicates<'tcx>,
181}
182
183pub(crate) type UnsatisfiedPredicates<'tcx> =
184    Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>;
185
186/// Criteria to apply when searching for a given Pick. This is used during
187/// the search for potentially shadowed methods to ensure we don't search
188/// more candidates than strictly necessary.
189#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PickConstraintsForShadowed {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "PickConstraintsForShadowed", "autoderefs", &self.autoderefs,
            "receiver_steps", &self.receiver_steps, "def_id", &&self.def_id)
    }
}Debug)]
190struct PickConstraintsForShadowed {
191    autoderefs: usize,
192    receiver_steps: Option<usize>,
193    def_id: DefId,
194}
195
196impl PickConstraintsForShadowed {
197    fn may_shadow_based_on_autoderefs(&self, autoderefs: usize) -> bool {
198        autoderefs == self.autoderefs
199    }
200
201    fn candidate_may_shadow(&self, candidate: &Candidate<'_>) -> bool {
202        // An item never shadows itself
203        candidate.item.def_id != self.def_id
204            // and we're only concerned about inherent impls doing the shadowing.
205            // Shadowing can only occur if the impl being shadowed is further along
206            // the Receiver dereferencing chain than the impl doing the shadowing.
207            && match candidate.kind {
208                CandidateKind::InherentImplCandidate { receiver_steps, .. } => match self.receiver_steps {
209                    Some(shadowed_receiver_steps) => receiver_steps > shadowed_receiver_steps,
210                    _ => false
211                },
212                _ => false
213            }
214    }
215}
216
217#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Pick<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["item", "kind", "import_ids", "autoderefs",
                        "autoref_or_ptr_adjustment", "self_ty",
                        "unstable_candidates", "receiver_steps",
                        "shadowed_candidates"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.item, &self.kind, &self.import_ids, &self.autoderefs,
                        &self.autoref_or_ptr_adjustment, &self.self_ty,
                        &self.unstable_candidates, &self.receiver_steps,
                        &&self.shadowed_candidates];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "Pick", names,
            values)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for Pick<'tcx> {
    #[inline]
    fn clone(&self) -> Pick<'tcx> {
        Pick {
            item: ::core::clone::Clone::clone(&self.item),
            kind: ::core::clone::Clone::clone(&self.kind),
            import_ids: ::core::clone::Clone::clone(&self.import_ids),
            autoderefs: ::core::clone::Clone::clone(&self.autoderefs),
            autoref_or_ptr_adjustment: ::core::clone::Clone::clone(&self.autoref_or_ptr_adjustment),
            self_ty: ::core::clone::Clone::clone(&self.self_ty),
            unstable_candidates: ::core::clone::Clone::clone(&self.unstable_candidates),
            receiver_steps: ::core::clone::Clone::clone(&self.receiver_steps),
            shadowed_candidates: ::core::clone::Clone::clone(&self.shadowed_candidates),
        }
    }
}Clone)]
218pub(crate) struct Pick<'tcx> {
219    pub item: ty::AssocItem,
220    pub kind: PickKind<'tcx>,
221    pub import_ids: &'tcx [LocalDefId],
222
223    /// Indicates that the source expression should be autoderef'd N times
224    /// ```ignore (not-rust)
225    /// A = expr | *expr | **expr | ...
226    /// ```
227    pub autoderefs: usize,
228
229    /// Indicates that we want to add an autoref (and maybe also unsize it), or if the receiver is
230    /// `*mut T`, convert it to `*const T`.
231    pub autoref_or_ptr_adjustment: Option<AutorefOrPtrAdjustment>,
232    pub self_ty: Ty<'tcx>,
233
234    /// Unstable candidates alongside the stable ones.
235    unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
236
237    /// Number of jumps along the `Receiver::Target` chain we followed
238    /// to identify this method. Used only for deshadowing errors.
239    /// Only applies for inherent impls.
240    pub receiver_steps: Option<usize>,
241
242    /// Candidates that were shadowed by supertraits.
243    pub shadowed_candidates: Vec<ty::AssocItem>,
244}
245
246#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PickKind<'tcx> {
    #[inline]
    fn clone(&self) -> PickKind<'tcx> {
        match self {
            PickKind::InherentImplPick => PickKind::InherentImplPick,
            PickKind::ObjectPick => PickKind::ObjectPick,
            PickKind::TraitPick(__self_0) =>
                PickKind::TraitPick(::core::clone::Clone::clone(__self_0)),
            PickKind::WhereClausePick(__self_0) =>
                PickKind::WhereClausePick(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PickKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PickKind::InherentImplPick =>
                ::core::fmt::Formatter::write_str(f, "InherentImplPick"),
            PickKind::ObjectPick =>
                ::core::fmt::Formatter::write_str(f, "ObjectPick"),
            PickKind::TraitPick(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TraitPick", &__self_0),
            PickKind::WhereClausePick(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "WhereClausePick", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for PickKind<'tcx> {
    #[inline]
    fn eq(&self, other: &PickKind<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (PickKind::TraitPick(__self_0), PickKind::TraitPick(__arg1_0))
                    => __self_0 == __arg1_0,
                (PickKind::WhereClausePick(__self_0),
                    PickKind::WhereClausePick(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for PickKind<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<ty::PolyTraitRef<'tcx>>;
    }
}Eq)]
247pub(crate) enum PickKind<'tcx> {
248    InherentImplPick,
249    ObjectPick,
250    TraitPick(
251        // Is Ambiguously Imported
252        bool,
253    ),
254    WhereClausePick(
255        // Trait
256        ty::PolyTraitRef<'tcx>,
257    ),
258}
259
260pub(crate) type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
261
262#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for Mode {
    #[inline]
    fn eq(&self, other: &Mode) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Mode {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::marker::Copy for Mode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Mode {
    #[inline]
    fn clone(&self) -> Mode { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Mode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Mode::MethodCall => "MethodCall",
                Mode::Path => "Path",
            })
    }
}Debug)]
263pub(crate) enum Mode {
264    // An expression of the form `receiver.method_name(...)`.
265    // Autoderefs are performed on `receiver`, lookup is done based on the
266    // `self` argument of the method, and static methods aren't considered.
267    MethodCall,
268    // An expression of the form `Type::item` or `<T>::item`.
269    // No autoderefs are performed, lookup is done based on the type each
270    // implementation is for, and static methods are included.
271    Path,
272}
273
274#[derive(#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ProbeScope<'tcx> {
    #[inline]
    fn eq(&self, other: &ProbeScope<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ProbeScope::Single(__self_0, __self_1),
                    ProbeScope::Single(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for ProbeScope<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefId>;
        let _: ::core::cmp::AssertParamIsEq<Option<Ty<'tcx>>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ProbeScope<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ProbeScope::Single(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Single",
                    __self_0, &__self_1),
            ProbeScope::TraitsInScope =>
                ::core::fmt::Formatter::write_str(f, "TraitsInScope"),
            ProbeScope::AllTraits =>
                ::core::fmt::Formatter::write_str(f, "AllTraits"),
        }
    }
}Debug)]
275pub(crate) enum ProbeScope<'tcx> {
276    // Single candidate coming from pre-resolved delegation method.
277    Single(DefId, Option<Ty<'tcx>> /* self_ty override */),
278
279    // Assemble candidates coming only from traits in scope.
280    TraitsInScope,
281
282    // Assemble candidates coming from all traits.
283    AllTraits,
284}
285
286impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
287    /// This is used to offer suggestions to users. It returns methods
288    /// that could have been called which have the desired return
289    /// type. Some effort is made to rule out methods that, if called,
290    /// would result in an error (basically, the same criteria we
291    /// would use to decide if a method is a plausible fit for
292    /// ambiguity purposes).
293    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("probe_for_return_type_for_diagnostic",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(293u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("mode")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("mode");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("return_type")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("return_type");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scope_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scope_expr_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&return_type)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope_expr_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Vec<ty::AssocItem> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let method_names =
                self.probe_op(span, mode, None, Some(return_type),
                        IsSuggestion(true), self_ty, scope_expr_id,
                        ProbeScope::AllTraits,
                        |probe_cx|
                            Ok(probe_cx.candidate_method_names(candidate_filter))).unwrap_or_default();
            method_names.iter().flat_map(|&method_name|
                        {
                            self.probe_op(span, mode, Some(method_name),
                                        Some(return_type), IsSuggestion(true), self_ty,
                                        scope_expr_id, ProbeScope::AllTraits,
                                        |probe_cx| probe_cx.pick()).ok().map(|pick| pick.item)
                        }).collect()
        }
    }
}#[instrument(level = "debug", skip(self, candidate_filter))]
294    pub(crate) fn probe_for_return_type_for_diagnostic(
295        &self,
296        span: Span,
297        mode: Mode,
298        return_type: Ty<'tcx>,
299        self_ty: Ty<'tcx>,
300        scope_expr_id: HirId,
301        candidate_filter: impl Fn(&ty::AssocItem) -> bool,
302    ) -> Vec<ty::AssocItem> {
303        let method_names = self
304            .probe_op(
305                span,
306                mode,
307                None,
308                Some(return_type),
309                IsSuggestion(true),
310                self_ty,
311                scope_expr_id,
312                ProbeScope::AllTraits,
313                |probe_cx| Ok(probe_cx.candidate_method_names(candidate_filter)),
314            )
315            .unwrap_or_default();
316        method_names
317            .iter()
318            .flat_map(|&method_name| {
319                self.probe_op(
320                    span,
321                    mode,
322                    Some(method_name),
323                    Some(return_type),
324                    IsSuggestion(true),
325                    self_ty,
326                    scope_expr_id,
327                    ProbeScope::AllTraits,
328                    |probe_cx| probe_cx.pick(),
329                )
330                .ok()
331                .map(|pick| pick.item)
332            })
333            .collect()
334    }
335
336    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("probe_for_name",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(336u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("mode")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("mode");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("return_type")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("return_type");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_suggestion")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_suggestion");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scope_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scope_expr_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scope");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&return_type)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_suggestion)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope_expr_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PickResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.probe_op(item_name.span, mode, Some(item_name), return_type,
                is_suggestion, self_ty, scope_expr_id, scope,
                |probe_cx| probe_cx.pick())
        }
    }
}#[instrument(level = "debug", skip(self))]
337    pub(crate) fn probe_for_name(
338        &self,
339        mode: Mode,
340        item_name: Ident,
341        return_type: Option<Ty<'tcx>>,
342        is_suggestion: IsSuggestion,
343        self_ty: Ty<'tcx>,
344        scope_expr_id: HirId,
345        scope: ProbeScope<'tcx>,
346    ) -> PickResult<'tcx> {
347        self.probe_op(
348            item_name.span,
349            mode,
350            Some(item_name),
351            return_type,
352            is_suggestion,
353            self_ty,
354            scope_expr_id,
355            scope,
356            |probe_cx| probe_cx.pick(),
357        )
358    }
359
360    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("probe_for_name_many",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(360u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("mode")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("mode");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("return_type")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("return_type");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_suggestion")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_suggestion");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scope_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scope_expr_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scope");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&return_type)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_suggestion)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope_expr_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Vec<Candidate<'tcx>>, MethodError<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.probe_op(item_name.span, mode, Some(item_name), return_type,
                is_suggestion, self_ty, scope_expr_id, scope,
                |probe_cx|
                    {
                        Ok(probe_cx.inherent_candidates.into_iter().chain(probe_cx.extension_candidates).collect())
                    })
        }
    }
}#[instrument(level = "debug", skip(self))]
361    pub(crate) fn probe_for_name_many(
362        &self,
363        mode: Mode,
364        item_name: Ident,
365        return_type: Option<Ty<'tcx>>,
366        is_suggestion: IsSuggestion,
367        self_ty: Ty<'tcx>,
368        scope_expr_id: HirId,
369        scope: ProbeScope<'tcx>,
370    ) -> Result<Vec<Candidate<'tcx>>, MethodError<'tcx>> {
371        self.probe_op(
372            item_name.span,
373            mode,
374            Some(item_name),
375            return_type,
376            is_suggestion,
377            self_ty,
378            scope_expr_id,
379            scope,
380            |probe_cx| {
381                Ok(probe_cx
382                    .inherent_candidates
383                    .into_iter()
384                    .chain(probe_cx.extension_candidates)
385                    .collect())
386            },
387        )
388    }
389
390    pub(crate) fn probe_op<OP, R>(
391        &'a self,
392        span: Span,
393        mode: Mode,
394        method_name: Option<Ident>,
395        return_type: Option<Ty<'tcx>>,
396        is_suggestion: IsSuggestion,
397        self_ty: Ty<'tcx>,
398        scope_expr_id: HirId,
399        scope: ProbeScope<'tcx>,
400        op: OP,
401    ) -> Result<R, MethodError<'tcx>>
402    where
403        OP: FnOnce(ProbeContext<'_, 'tcx>) -> Result<R, MethodError<'tcx>>,
404    {
405        #[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            MissingTypeAnnot where G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    MissingTypeAnnot => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("type annotations needed")));
                        ;
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
406        #[diag("type annotations needed")]
407        struct MissingTypeAnnot;
408
409        #[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            MethodCallOnDivergingInferenceVariable where
            G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    MethodCallOnDivergingInferenceVariable => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("method call on a diverging inference variable")));
                        diag.help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider providing a type annotation")));
                        ;
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
410        #[diag("method call on a diverging inference variable")]
411        #[help("consider providing a type annotation")]
412        struct MethodCallOnDivergingInferenceVariable;
413
414        let mut orig_values = OriginalQueryValues::default();
415        let predefined_opaques_in_body = if self.next_trait_solver() {
416            self.tcx.mk_predefined_opaques_in_body_from_iter(
417                self.inner.borrow_mut().opaque_types().iter_opaque_types().map(|(k, v)| (k, v.ty)),
418            )
419        } else {
420            ty::List::empty()
421        };
422        let value = query::MethodAutoderefSteps { predefined_opaques_in_body, self_ty };
423        let query_input = self
424            .canonicalize_query(ParamEnvAnd { param_env: self.param_env, value }, &mut orig_values);
425
426        let steps = match mode {
427            Mode::MethodCall => self.tcx.method_autoderef_steps(query_input),
428            Mode::Path => self.probe(|_| {
429                // Mode::Path - the deref steps is "trivial". This turns
430                // our CanonicalQuery into a "trivial" QueryResponse. This
431                // is a bit inefficient, but I don't think that writing
432                // special handling for this "trivial case" is a good idea.
433
434                let infcx = &self.infcx;
435                let (ParamEnvAnd { param_env: _, value }, var_values) =
436                    infcx.instantiate_canonical(span, &query_input.canonical);
437                let query::MethodAutoderefSteps { predefined_opaques_in_body: _, self_ty } = value;
438                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:438",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(438u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self_ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self_ty");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("query_input")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("query_input");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("probe_op: Mode::Path")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&query_input)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?self_ty, ?query_input, "probe_op: Mode::Path");
439                let prev_opaque_entries = self.inner.borrow_mut().opaque_types().num_entries();
440                MethodAutoderefStepsResult {
441                    steps: infcx.tcx.arena.alloc_from_iter([CandidateStep {
442                        self_ty: self.make_query_response_ignoring_pending_obligations(
443                            var_values,
444                            self_ty,
445                            prev_opaque_entries,
446                        ),
447                        self_ty_is_opaque: false,
448                        autoderefs: 0,
449                        from_unsafe_deref: false,
450                        unsize: false,
451                        reachable_via_deref: true,
452                    }]),
453                    opt_bad_ty: None,
454                    reached_recursion_limit: false,
455                }
456            }),
457        };
458
459        // If our autoderef loop had reached the recursion limit,
460        // report an overflow error, but continue going on with
461        // the truncated autoderef list.
462        if steps.reached_recursion_limit && !is_suggestion.0 {
463            self.probe(|_| {
464                let ty = &steps
465                    .steps
466                    .last()
467                    .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("reached the recursion limit in 0 steps?"))span_bug!(span, "reached the recursion limit in 0 steps?"))
468                    .self_ty;
469                let ty = self
470                    .probe_instantiate_query_response(span, &orig_values, ty)
471                    .unwrap_or_else(|_| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("instantiating {0:?} failed?", ty))span_bug!(span, "instantiating {:?} failed?", ty));
472                autoderef::report_autoderef_recursion_limit_error(self.tcx, span, ty.value);
473            });
474        }
475
476        // If we encountered an `_` type or an error type during autoderef, this is
477        // ambiguous.
478        if let Some(bad_ty) = &steps.opt_bad_ty {
479            // We care about the opt_bad_ty given the inference state at the point of computing the auto deref chain,
480            // so we don't call structurally_resolve_type as it processes obligations in our local FnCtxt,
481            // potentially making inference progress.
482            let ty = &bad_ty.ty;
483            let ty = self
484                .probe_instantiate_query_response(span, &orig_values, ty)
485                .unwrap_or_else(|_| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("instantiating {0:?} failed?", ty))span_bug!(span, "instantiating {:?} failed?", ty));
486            let ty = ty.value;
487
488            if is_suggestion.0 {
489                // Ambiguity was encountered during a suggestion. There's really
490                // not much use in suggesting methods in this case.
491                return Err(MethodError::NoMatch(NoMatchData {
492                    static_candidates: Vec::new(),
493                    unsatisfied_predicates: Vec::new(),
494                    out_of_scope_traits: Vec::new(),
495                    similar_candidate: None,
496                    mode,
497                }));
498            } else if bad_ty.reached_raw_pointer
499                && !self.tcx.features().arbitrary_self_types_pointers()
500                && !self.tcx.sess.at_least_rust_2018()
501            {
502                // this case used to be allowed by the compiler,
503                // so we do a future-compat lint here for the 2015 edition
504                // (see https://github.com/rust-lang/rust/issues/46906)
505                self.tcx.emit_node_span_lint(
506                    TYVAR_BEHIND_RAW_POINTER,
507                    scope_expr_id,
508                    span,
509                    MissingTypeAnnot,
510                );
511            // If `ty` is an inference variable that was created by being adjusted from the never type,
512            // We demand the type to be equal to the never type, so we can probe the never type for methods
513            // (see https://github.com/rust-lang/rust/issues/143349)
514            } else if let ty::Infer(ty::TyVar(ty_id)) = *ty.kind()
515                && let ty_id = self.sub_unification_table_root_var(ty_id)
516                && self
517                    .diverging_type_vars
518                    .borrow()
519                    .iter()
520                    .any(|&candidate_id| self.sub_unification_table_root_var(candidate_id) == ty_id)
521            {
522                self.tcx.emit_node_span_lint(
523                    METHOD_CALL_ON_DIVERGING_INFER_VAR,
524                    scope_expr_id,
525                    span,
526                    MethodCallOnDivergingInferenceVariable,
527                );
528                let root_ty = Ty::new_var(self.tcx, ty_id);
529                self.demand_eqtype(span, root_ty, self.tcx.types.never);
530            } else {
531                let guar = match *ty.kind() {
532                    _ if let Some(guar) = self.tainted_by_errors() => guar,
533                    ty::Infer(ty::TyVar(_)) => {
534                        // We want to get the variable name that the method
535                        // is being called on. If it is a method call.
536                        let err_span = match (mode, self.tcx.hir_node(scope_expr_id)) {
537                            (
538                                Mode::MethodCall,
539                                Node::Expr(hir::Expr {
540                                    kind: ExprKind::MethodCall(_, recv, ..),
541                                    ..
542                                }),
543                            ) => recv.span,
544                            _ => span,
545                        };
546
547                        let raw_ptr_call = bad_ty.reached_raw_pointer
548                            && !self.tcx.features().arbitrary_self_types();
549
550                        let mut err = self.err_ctxt().emit_inference_failure_err(
551                            self.body_def_id,
552                            err_span,
553                            ty.into(),
554                            TypeAnnotationNeeded::E0282,
555                            !raw_ptr_call,
556                        );
557                        if raw_ptr_call {
558                            err.span_label(span, "cannot call a method on a raw pointer with an unknown pointee type");
559                        }
560                        err.emit()
561                    }
562                    ty::Error(guar) => guar,
563                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bad final type in method autoderef"))bug!("unexpected bad final type in method autoderef"),
564                };
565                self.demand_eqtype(span, ty, Ty::new_error(self.tcx, guar));
566                return Err(MethodError::ErrorReported(guar));
567            }
568        }
569
570        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:570",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(570u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ProbeContext: steps for self_ty={0:?} are {1:?}",
                                                    self_ty, steps) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("ProbeContext: steps for self_ty={:?} are {:?}", self_ty, steps);
571
572        // this creates one big transaction so that all type variables etc
573        // that we create during the probe process are removed later
574        self.probe(|_| {
575            let mut probe_cx = ProbeContext::new(
576                self,
577                span,
578                mode,
579                method_name,
580                return_type,
581                &orig_values,
582                steps.steps,
583                scope_expr_id,
584                is_suggestion,
585            );
586
587            match scope {
588                ProbeScope::TraitsInScope => {
589                    probe_cx.assemble_inherent_candidates();
590                    probe_cx.assemble_extension_candidates_for_traits_in_scope();
591                }
592                ProbeScope::AllTraits => {
593                    probe_cx.assemble_inherent_candidates();
594                    probe_cx.assemble_extension_candidates_for_all_traits();
595                }
596                ProbeScope::Single(def_id, self_ty_override) => {
597                    let item = self.tcx.associated_item(def_id);
598                    // FIXME(fn_delegation): Delegation to inherent methods is not yet supported.
599                    {
    match (&item.container, &AssocContainer::Trait) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(item.container, AssocContainer::Trait);
600
601                    let trait_def_id = self.tcx.parent(def_id);
602                    let trait_span = self.tcx.def_span(trait_def_id);
603
604                    let trait_args = self.fresh_args_for_item(trait_span, trait_def_id);
605                    let trait_ref = ty::TraitRef::new_from_args(self.tcx, trait_def_id, trait_args);
606
607                    probe_cx.self_ty_override = self_ty_override;
608                    probe_cx.push_candidate(
609                        Candidate {
610                            item,
611                            kind: CandidateKind::TraitCandidate(
612                                ty::Binder::dummy(trait_ref),
613                                false,
614                            ),
615                            import_ids: &[],
616                        },
617                        false,
618                    );
619                }
620            };
621            op(probe_cx)
622        })
623    }
624}
625
626pub(crate) fn method_autoderef_steps<'tcx>(
627    tcx: TyCtxt<'tcx>,
628    goal: CanonicalMethodAutoderefStepsGoal<'tcx>,
629) -> MethodAutoderefStepsResult<'tcx> {
630    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:630",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(630u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("method_autoderef_steps({0:?})",
                                                    goal) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("method_autoderef_steps({:?})", goal);
631
632    let (ref infcx, goal, inference_vars) = tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &goal);
633    let ParamEnvAnd {
634        param_env,
635        value: query::MethodAutoderefSteps { predefined_opaques_in_body, self_ty },
636    } = goal;
637    for (key, ty) in predefined_opaques_in_body {
638        let prev = infcx
639            .register_hidden_type_in_storage(key, ty::ProvisionalHiddenType { span: DUMMY_SP, ty });
640        // It may be possible that two entries in the opaque type storage end up
641        // with the same key after resolving contained inference variables.
642        //
643        // We could put them in the duplicate list but don't have to. The opaques we
644        // encounter here are already tracked in the caller, so there's no need to
645        // also store them here. We'd take them out when computing the query response
646        // and then discard them, as they're already present in the input.
647        //
648        // Ideally we'd drop duplicate opaque type definitions when computing
649        // the canonical input. This is more annoying to implement and may cause a
650        // perf regression, so we do it inside of the query for now.
651        if let Some(prev) = prev {
652            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:652",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(652u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("key")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("key");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("ty");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("prev")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("prev");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ignore duplicate in `opaque_types_storage`")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&key)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&prev)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?key, ?ty, ?prev, "ignore duplicate in `opaque_types_storage`");
653        }
654    }
655    let prev_opaque_entries = infcx.inner.borrow_mut().opaque_types().num_entries();
656
657    // We accept not-yet-defined opaque types in the autoderef
658    // chain to support recursive calls. We do error if the final
659    // infer var is not an opaque.
660    let self_ty_is_opaque = |ty: Ty<'_>| {
661        if let &ty::Infer(ty::TyVar(vid)) = ty.kind() {
662            infcx.has_opaques_with_sub_unified_hidden_type(vid)
663        } else {
664            false
665        }
666    };
667
668    // If arbitrary self types is not enabled, we follow the chain of
669    // `Deref<Target=T>`. If arbitrary self types is enabled, we instead
670    // follow the chain of `Receiver<Target=T>`, but we also record whether
671    // such types are reachable by following the (potentially shorter)
672    // chain of `Deref<Target=T>`. We will use the first list when finding
673    // potentially relevant function implementations (e.g. relevant impl blocks)
674    // but the second list when determining types that the receiver may be
675    // converted to, in order to find out which of those methods might actually
676    // be callable.
677    let mut autoderef_via_deref =
678        Autoderef::new(infcx, param_env, hir::def_id::CRATE_DEF_ID, DUMMY_SP, self_ty)
679            .include_raw_pointers()
680            .silence_errors();
681
682    let mut reached_raw_pointer = false;
683    let arbitrary_self_types_enabled =
684        tcx.features().arbitrary_self_types() || tcx.features().arbitrary_self_types_pointers();
685    let (mut steps, reached_recursion_limit): (Vec<_>, bool) = if arbitrary_self_types_enabled {
686        let reachable_via_deref =
687            autoderef_via_deref.by_ref().map(|_| true).chain(std::iter::repeat(false));
688
689        let mut autoderef_via_receiver =
690            Autoderef::new(infcx, param_env, hir::def_id::CRATE_DEF_ID, DUMMY_SP, self_ty)
691                .include_raw_pointers()
692                .use_receiver_trait()
693                .silence_errors();
694        let steps = autoderef_via_receiver
695            .by_ref()
696            .zip(reachable_via_deref)
697            .map(|((ty, d), reachable_via_deref)| {
698                let step = CandidateStep {
699                    self_ty: infcx.make_query_response_ignoring_pending_obligations(
700                        inference_vars,
701                        ty,
702                        prev_opaque_entries,
703                    ),
704                    self_ty_is_opaque: self_ty_is_opaque(ty),
705                    autoderefs: d,
706                    from_unsafe_deref: reached_raw_pointer,
707                    unsize: false,
708                    reachable_via_deref,
709                };
710                if ty.is_raw_ptr() {
711                    // all the subsequent steps will be from_unsafe_deref
712                    reached_raw_pointer = true;
713                }
714                step
715            })
716            .collect();
717        (steps, autoderef_via_receiver.reached_recursion_limit())
718    } else {
719        let steps = autoderef_via_deref
720            .by_ref()
721            .map(|(ty, d)| {
722                let step = CandidateStep {
723                    self_ty: infcx.make_query_response_ignoring_pending_obligations(
724                        inference_vars,
725                        ty,
726                        prev_opaque_entries,
727                    ),
728                    self_ty_is_opaque: self_ty_is_opaque(ty),
729                    autoderefs: d,
730                    from_unsafe_deref: reached_raw_pointer,
731                    unsize: false,
732                    reachable_via_deref: true,
733                };
734                if ty.is_raw_ptr() {
735                    // all the subsequent steps will be from_unsafe_deref
736                    reached_raw_pointer = true;
737                }
738                step
739            })
740            .collect();
741        (steps, autoderef_via_deref.reached_recursion_limit())
742    };
743    let final_ty = autoderef_via_deref.final_ty();
744    let opt_bad_ty = match final_ty.kind() {
745        ty::Infer(ty::TyVar(_)) if !self_ty_is_opaque(final_ty) => Some(MethodAutoderefBadTy {
746            reached_raw_pointer,
747            ty: infcx.make_query_response_ignoring_pending_obligations(
748                inference_vars,
749                final_ty,
750                prev_opaque_entries,
751            ),
752        }),
753        ty::Error(_) => Some(MethodAutoderefBadTy {
754            reached_raw_pointer,
755            ty: infcx.make_query_response_ignoring_pending_obligations(
756                inference_vars,
757                final_ty,
758                prev_opaque_entries,
759            ),
760        }),
761        ty::Array(elem_ty, _) => {
762            let autoderefs = steps.iter().filter(|s| s.reachable_via_deref).count() - 1;
763            steps.push(CandidateStep {
764                self_ty: infcx.make_query_response_ignoring_pending_obligations(
765                    inference_vars,
766                    Ty::new_slice(infcx.tcx, *elem_ty),
767                    prev_opaque_entries,
768                ),
769                self_ty_is_opaque: false,
770                autoderefs,
771                // this could be from an unsafe deref if we had
772                // a *mut/const [T; N]
773                from_unsafe_deref: reached_raw_pointer,
774                unsize: true,
775                reachable_via_deref: true, // this is always the final type from
776                                           // autoderef_via_deref
777            });
778
779            None
780        }
781        _ => None,
782    };
783
784    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:784",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(784u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("method_autoderef_steps: steps={0:?} opt_bad_ty={1:?}",
                                                    steps, opt_bad_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
785    // Need to empty the opaque types storage before it gets dropped.
786    let _ = infcx.take_opaque_types();
787    MethodAutoderefStepsResult {
788        steps: tcx.arena.alloc_from_iter(steps),
789        opt_bad_ty: opt_bad_ty.map(|ty| &*tcx.arena.alloc(ty)),
790        reached_recursion_limit,
791    }
792}
793
794impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
795    fn new(
796        fcx: &'a FnCtxt<'a, 'tcx>,
797        span: Span,
798        mode: Mode,
799        method_name: Option<Ident>,
800        return_type: Option<Ty<'tcx>>,
801        orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
802        steps: &'tcx [CandidateStep<'tcx>],
803        scope_expr_id: HirId,
804        is_suggestion: IsSuggestion,
805    ) -> ProbeContext<'a, 'tcx> {
806        ProbeContext {
807            fcx,
808            span,
809            mode,
810            method_name,
811            return_type,
812            inherent_candidates: Vec::new(),
813            extension_candidates: Vec::new(),
814            impl_dups: FxHashSet::default(),
815            orig_steps_var_values,
816            steps,
817            allow_similar_names: false,
818            private_candidates: Vec::new(),
819            private_candidate: Cell::new(None),
820            static_candidates: RefCell::new(Vec::new()),
821            scope_expr_id,
822            is_suggestion,
823            self_ty_override: None,
824        }
825    }
826
827    fn reset(&mut self) {
828        self.inherent_candidates.clear();
829        self.extension_candidates.clear();
830        self.impl_dups.clear();
831        self.private_candidates.clear();
832        self.private_candidate.set(None);
833        self.static_candidates.borrow_mut().clear();
834    }
835
836    /// When we're looking up a method by path (UFCS), we relate the receiver
837    /// types invariantly. When we are looking up a method by the `.` operator,
838    /// we relate them covariantly.
839    fn variance(&self) -> ty::Variance {
840        match self.mode {
841            Mode::MethodCall => ty::Covariant,
842            Mode::Path => ty::Invariant,
843        }
844    }
845
846    ///////////////////////////////////////////////////////////////////////////
847    // CANDIDATE ASSEMBLY
848
849    fn push_candidate(&mut self, candidate: Candidate<'tcx>, is_inherent: bool) {
850        let is_accessible = if let Some(name) = self.method_name {
851            let item = candidate.item;
852            let container_id = item.container_id(self.tcx);
853            let def_scope =
854                self.tcx.adjust_ident_and_get_scope(name, container_id, self.body_def_id).1;
855            item.visibility(self.tcx).is_accessible_from(def_scope, self.tcx)
856        } else {
857            true
858        };
859        if is_accessible {
860            if is_inherent {
861                self.inherent_candidates.push(candidate);
862            } else {
863                self.extension_candidates.push(candidate);
864            }
865        } else {
866            self.private_candidates.push(candidate);
867        }
868    }
869
870    fn assemble_inherent_candidates(&mut self) {
871        for step in self.steps.iter() {
872            self.assemble_probe(&step.self_ty, step.autoderefs);
873        }
874    }
875
876    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_probe",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(876u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("receiver_steps")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("receiver_steps");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&receiver_steps as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let raw_self_ty = self_ty.value.value;
            match *raw_self_ty.kind() {
                ty::Dynamic(data, ..) if let Some(p) = data.principal() => {
                    let (QueryResponse { value: generalized_self_ty, .. },
                            _ignored_var_values) =
                        self.fcx.instantiate_canonical(self.span, self_ty);
                    self.assemble_inherent_candidates_from_object(generalized_self_ty);
                    self.assemble_inherent_impl_candidates_for_type(p.def_id(),
                        receiver_steps);
                    self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty,
                        receiver_steps);
                }
                ty::Adt(def, _) => {
                    let def_id = def.did();
                    self.assemble_inherent_impl_candidates_for_type(def_id,
                        receiver_steps);
                    self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty,
                        receiver_steps);
                }
                ty::Foreign(did) => {
                    self.assemble_inherent_impl_candidates_for_type(did,
                        receiver_steps);
                    self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty,
                        receiver_steps);
                }
                ty::Param(_) => {
                    self.assemble_inherent_candidates_from_param(raw_self_ty);
                }
                ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_)
                    | ty::Str | ty::Array(..) | ty::Slice(_) | ty::RawPtr(_, _)
                    | ty::Ref(..) | ty::Never | ty::Tuple(..) => {
                    self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty,
                        receiver_steps)
                }
                ty::Alias(..) | ty::Bound(..) | ty::Closure(..) |
                    ty::Coroutine(..) | ty::CoroutineClosure(..) |
                    ty::CoroutineWitness(..) | ty::Dynamic(..) | ty::Error(..) |
                    ty::FnDef(..) | ty::FnPtr(..) | ty::Infer(..) | ty::Pat(..)
                    | ty::Placeholder(..) | ty::UnsafeBinder(..) => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
877    fn assemble_probe(
878        &mut self,
879        self_ty: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
880        receiver_steps: usize,
881    ) {
882        let raw_self_ty = self_ty.value.value;
883        match *raw_self_ty.kind() {
884            ty::Dynamic(data, ..) if let Some(p) = data.principal() => {
885                // Subtle: we can't use `instantiate_query_response` here: using it will
886                // commit to all of the type equalities assumed by inference going through
887                // autoderef (see the `method-probe-no-guessing` test).
888                //
889                // However, in this code, it is OK if we end up with an object type that is
890                // "more general" than the object type that we are evaluating. For *every*
891                // object type `MY_OBJECT`, a function call that goes through a trait-ref
892                // of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
893                // `ObjectCandidate`, and it should be discoverable "exactly" through one
894                // of the iterations in the autoderef loop, so there is no problem with it
895                // being discoverable in another one of these iterations.
896                //
897                // Using `instantiate_canonical` on our
898                // `Canonical<QueryResponse<Ty<'tcx>>>` and then *throwing away* the
899                // `CanonicalVarValues` will exactly give us such a generalization - it
900                // will still match the original object type, but it won't pollute our
901                // type variables in any form, so just do that!
902                let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
903                    self.fcx.instantiate_canonical(self.span, self_ty);
904
905                self.assemble_inherent_candidates_from_object(generalized_self_ty);
906                self.assemble_inherent_impl_candidates_for_type(p.def_id(), receiver_steps);
907                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
908            }
909            ty::Adt(def, _) => {
910                let def_id = def.did();
911                self.assemble_inherent_impl_candidates_for_type(def_id, receiver_steps);
912                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
913            }
914            ty::Foreign(did) => {
915                self.assemble_inherent_impl_candidates_for_type(did, receiver_steps);
916                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
917            }
918            ty::Param(_) => {
919                self.assemble_inherent_candidates_from_param(raw_self_ty);
920            }
921            ty::Bool
922            | ty::Char
923            | ty::Int(_)
924            | ty::Uint(_)
925            | ty::Float(_)
926            | ty::Str
927            | ty::Array(..)
928            | ty::Slice(_)
929            | ty::RawPtr(_, _)
930            | ty::Ref(..)
931            | ty::Never
932            | ty::Tuple(..) => {
933                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps)
934            }
935            ty::Alias(..)
936            | ty::Bound(..)
937            | ty::Closure(..)
938            | ty::Coroutine(..)
939            | ty::CoroutineClosure(..)
940            | ty::CoroutineWitness(..)
941            | ty::Dynamic(..)
942            | ty::Error(..)
943            | ty::FnDef(..)
944            | ty::FnPtr(..)
945            | ty::Infer(..)
946            | ty::Pat(..)
947            | ty::Placeholder(..)
948            | ty::UnsafeBinder(..) => {}
949        }
950    }
951
952    fn assemble_inherent_candidates_for_incoherent_ty(
953        &mut self,
954        self_ty: Ty<'tcx>,
955        receiver_steps: usize,
956    ) {
957        let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::InstantiateWithInfer) else {
958            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected incoherent type: {0:?}",
        self_ty))bug!("unexpected incoherent type: {:?}", self_ty)
959        };
960        for &impl_def_id in self.tcx.incoherent_impls(simp).into_iter() {
961            self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
962        }
963    }
964
965    fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId, receiver_steps: usize) {
966        let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id).into_iter();
967        for &impl_def_id in impl_def_ids {
968            self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
969        }
970    }
971
972    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_inherent_impl_probe",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(972u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("receiver_steps")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("receiver_steps");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&receiver_steps as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.impl_dups.insert(impl_def_id) { return; }
            for item in self.impl_or_trait_item(impl_def_id) {
                if !self.has_applicable_self(&item) {
                    self.record_static_candidate(CandidateSource::Impl(impl_def_id));
                    continue;
                }
                self.push_candidate(Candidate {
                        item,
                        kind: InherentImplCandidate { impl_def_id, receiver_steps },
                        import_ids: &[],
                    }, true);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
973    fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId, receiver_steps: usize) {
974        if !self.impl_dups.insert(impl_def_id) {
975            return; // already visited
976        }
977
978        for item in self.impl_or_trait_item(impl_def_id) {
979            if !self.has_applicable_self(&item) {
980                // No receiver declared. Not a candidate.
981                self.record_static_candidate(CandidateSource::Impl(impl_def_id));
982                continue;
983            }
984            self.push_candidate(
985                Candidate {
986                    item,
987                    kind: InherentImplCandidate { impl_def_id, receiver_steps },
988                    import_ids: &[],
989                },
990                true,
991            );
992        }
993    }
994
995    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_inherent_candidates_from_object",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(995u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let principal =
                match self_ty.kind() {
                            ty::Dynamic(data, ..) => Some(data),
                            _ => None,
                        }.and_then(|data|
                            data.principal()).unwrap_or_else(||
                        {
                            ::rustc_middle::util::bug::span_bug_fmt(self.span,
                                format_args!("non-object {0:?} in assemble_inherent_candidates_from_object",
                                    self_ty))
                        });
            let trait_ref = principal.with_self_ty(self.tcx, self_ty);
            self.assemble_candidates_for_bounds(traits::supertraits(self.tcx,
                    trait_ref),
                |this, new_trait_ref, item|
                    {
                        this.push_candidate(Candidate {
                                item,
                                kind: ObjectCandidate(new_trait_ref),
                                import_ids: &[],
                            }, true);
                    });
        }
    }
}#[instrument(level = "debug", skip(self))]
996    fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'tcx>) {
997        let principal = match self_ty.kind() {
998            ty::Dynamic(data, ..) => Some(data),
999            _ => None,
1000        }
1001        .and_then(|data| data.principal())
1002        .unwrap_or_else(|| {
1003            span_bug!(
1004                self.span,
1005                "non-object {:?} in assemble_inherent_candidates_from_object",
1006                self_ty
1007            )
1008        });
1009
1010        // It is illegal to invoke a method on a trait instance that refers to
1011        // the `Self` type. An [`DynCompatibilityViolation::SupertraitSelf`] error
1012        // will be reported by `dyn_compatibility.rs` if the method refers to the
1013        // `Self` type anywhere other than the receiver. Here, we use a
1014        // instantiation that replaces `Self` with the object type itself. Hence,
1015        // a `&self` method will wind up with an argument type like `&dyn Trait`.
1016        let trait_ref = principal.with_self_ty(self.tcx, self_ty);
1017        self.assemble_candidates_for_bounds(
1018            traits::supertraits(self.tcx, trait_ref),
1019            |this, new_trait_ref, item| {
1020                this.push_candidate(
1021                    Candidate { item, kind: ObjectCandidate(new_trait_ref), import_ids: &[] },
1022                    true,
1023                );
1024            },
1025        );
1026    }
1027
1028    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_inherent_candidates_from_param",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1028u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_ty)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                {
                    match param_ty.kind() {
                        ty::Param(_) => {}
                        ref left_val => {
                            ::core::panicking::assert_matches_failed(left_val,
                                "ty::Param(_)", ::core::option::Option::None);
                        }
                    }
                };
            };
            let tcx = self.tcx;
            let bounds =
                self.param_env.caller_bounds().iter().filter_map(|clause|
                        {
                            let bound_clause = clause.kind();
                            match bound_clause.skip_binder() {
                                ty::ClauseKind::Trait(trait_predicate) =>
                                    DeepRejectCtxt::relate_rigid_rigid(tcx).types_may_unify(param_ty,
                                            trait_predicate.trait_ref.self_ty()).then(||
                                            bound_clause.rebind(trait_predicate.trait_ref)),
                                ty::ClauseKind::RegionOutlives(_) |
                                    ty::ClauseKind::TypeOutlives(_) |
                                    ty::ClauseKind::Projection(_) |
                                    ty::ClauseKind::ConstArgHasType(_, _) |
                                    ty::ClauseKind::WellFormed(_) |
                                    ty::ClauseKind::ConstEvaluatable(_) |
                                    ty::ClauseKind::UnstableFeature(_) |
                                    ty::ClauseKind::HostEffect(..) => None,
                            }
                        });
            self.assemble_candidates_for_bounds(bounds,
                |this, poly_trait_ref, item|
                    {
                        this.push_candidate(Candidate {
                                item,
                                kind: WhereClauseCandidate(poly_trait_ref),
                                import_ids: &[],
                            }, true);
                    });
        }
    }
}#[instrument(level = "debug", skip(self))]
1029    fn assemble_inherent_candidates_from_param(&mut self, param_ty: Ty<'tcx>) {
1030        debug_assert_matches!(param_ty.kind(), ty::Param(_));
1031
1032        let tcx = self.tcx;
1033
1034        // We use `DeepRejectCtxt` here which may return false positive on where clauses
1035        // with alias self types. We need to later on reject these as inherent candidates
1036        // in `consider_probe`.
1037        let bounds = self.param_env.caller_bounds().iter().filter_map(|clause| {
1038            let bound_clause = clause.kind();
1039            match bound_clause.skip_binder() {
1040                ty::ClauseKind::Trait(trait_predicate) => DeepRejectCtxt::relate_rigid_rigid(tcx)
1041                    .types_may_unify(param_ty, trait_predicate.trait_ref.self_ty())
1042                    .then(|| bound_clause.rebind(trait_predicate.trait_ref)),
1043                ty::ClauseKind::RegionOutlives(_)
1044                | ty::ClauseKind::TypeOutlives(_)
1045                | ty::ClauseKind::Projection(_)
1046                | ty::ClauseKind::ConstArgHasType(_, _)
1047                | ty::ClauseKind::WellFormed(_)
1048                | ty::ClauseKind::ConstEvaluatable(_)
1049                | ty::ClauseKind::UnstableFeature(_)
1050                | ty::ClauseKind::HostEffect(..) => None,
1051            }
1052        });
1053
1054        self.assemble_candidates_for_bounds(bounds, |this, poly_trait_ref, item| {
1055            this.push_candidate(
1056                Candidate { item, kind: WhereClauseCandidate(poly_trait_ref), import_ids: &[] },
1057                true,
1058            );
1059        });
1060    }
1061
1062    // Do a search through a list of bounds, using a callback to actually
1063    // create the candidates.
1064    fn assemble_candidates_for_bounds<F>(
1065        &mut self,
1066        bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
1067        mut mk_cand: F,
1068    ) where
1069        F: for<'b> FnMut(&mut ProbeContext<'b, 'tcx>, ty::PolyTraitRef<'tcx>, ty::AssocItem),
1070    {
1071        for bound_trait_ref in bounds {
1072            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:1072",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1072u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("elaborate_bounds(bound_trait_ref={0:?})",
                                                    bound_trait_ref) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
1073            for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
1074                if !self.has_applicable_self(&item) {
1075                    self.record_static_candidate(CandidateSource::Trait(bound_trait_ref.def_id()));
1076                } else {
1077                    mk_cand(self, bound_trait_ref, item);
1078                }
1079            }
1080        }
1081    }
1082
1083    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_extension_candidates_for_traits_in_scope",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1083u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut duplicates = FxHashSet::default();
            let opt_applicable_traits =
                self.tcx.in_scope_traits(self.scope_expr_id);
            if let Some(applicable_traits) = opt_applicable_traits {
                for trait_candidate in applicable_traits.iter() {
                    let trait_did = trait_candidate.def_id;
                    if duplicates.insert(trait_did) {
                        self.assemble_extension_candidates_for_trait(&trait_candidate.import_ids,
                            trait_did, trait_candidate.lint_ambiguous);
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1084    fn assemble_extension_candidates_for_traits_in_scope(&mut self) {
1085        let mut duplicates = FxHashSet::default();
1086        let opt_applicable_traits = self.tcx.in_scope_traits(self.scope_expr_id);
1087        if let Some(applicable_traits) = opt_applicable_traits {
1088            for trait_candidate in applicable_traits.iter() {
1089                let trait_did = trait_candidate.def_id;
1090                if duplicates.insert(trait_did) {
1091                    self.assemble_extension_candidates_for_trait(
1092                        &trait_candidate.import_ids,
1093                        trait_did,
1094                        trait_candidate.lint_ambiguous,
1095                    );
1096                }
1097            }
1098        }
1099    }
1100
1101    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_extension_candidates_for_all_traits",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1101u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut duplicates = FxHashSet::default();
            for trait_info in suggest::all_traits(self.tcx) {
                if duplicates.insert(trait_info.def_id) {
                    self.assemble_extension_candidates_for_trait(&[],
                        trait_info.def_id, false);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1102    fn assemble_extension_candidates_for_all_traits(&mut self) {
1103        let mut duplicates = FxHashSet::default();
1104        for trait_info in suggest::all_traits(self.tcx) {
1105            if duplicates.insert(trait_info.def_id) {
1106                self.assemble_extension_candidates_for_trait(&[], trait_info.def_id, false);
1107            }
1108        }
1109    }
1110
1111    fn matches_return_type(&self, method: ty::AssocItem, expected: Ty<'tcx>) -> bool {
1112        match method.kind {
1113            ty::AssocKind::Fn { .. } => self.probe(|_| {
1114                let args = self.fresh_args_for_item(self.span, method.def_id);
1115                let fty =
1116                    self.tcx.fn_sig(method.def_id).instantiate(self.tcx, args).skip_norm_wip();
1117                let fty = self.instantiate_binder_with_fresh_vars(
1118                    self.span,
1119                    BoundRegionConversionTime::FnCall,
1120                    fty,
1121                );
1122                self.can_eq(self.param_env, fty.output(), expected)
1123            }),
1124            _ => false,
1125        }
1126    }
1127
1128    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("assemble_extension_candidates_for_trait",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1128u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("import_ids")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("import_ids");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lint_ambiguous")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lint_ambiguous");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&import_ids)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&lint_ambiguous as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let trait_args =
                self.fresh_args_for_item(self.span, trait_def_id);
            let trait_ref =
                ty::TraitRef::new_from_args(self.tcx, trait_def_id,
                    trait_args);
            if self.tcx.is_trait_alias(trait_def_id) {
                for (bound_trait_pred, _) in
                    traits::expand_trait_aliases(self.tcx,
                            [(trait_ref.upcast(self.tcx), self.span)]).0 {
                    {
                        match (&bound_trait_pred.polarity(),
                                &ty::ClausePolarity::Positive) {
                            (left_val, right_val) => {
                                if !(*left_val == *right_val) {
                                    let kind = ::core::panicking::AssertKind::Eq;
                                    ::core::panicking::assert_failed(kind, &*left_val,
                                        &*right_val, ::core::option::Option::None);
                                }
                            }
                        }
                    };
                    let bound_trait_ref =
                        bound_trait_pred.map_bound(|pred| pred.trait_ref);
                    for item in
                        self.impl_or_trait_item(bound_trait_ref.def_id()) {
                        if !self.has_applicable_self(&item) {
                            self.record_static_candidate(CandidateSource::Trait(bound_trait_ref.def_id()));
                        } else {
                            self.push_candidate(Candidate {
                                    item,
                                    import_ids,
                                    kind: TraitCandidate(bound_trait_ref, lint_ambiguous),
                                }, false);
                        }
                    }
                }
            } else {
                if true {
                    if !self.tcx.is_trait(trait_def_id) {
                        ::core::panicking::panic("assertion failed: self.tcx.is_trait(trait_def_id)")
                    };
                };
                if self.tcx.trait_is_auto(trait_def_id) { return; }
                for item in self.impl_or_trait_item(trait_def_id) {
                    if !self.has_applicable_self(&item) {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:1170",
                                                "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                                ::tracing_core::__macro_support::Option::Some(1170u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("method has inapplicable self")
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        self.record_static_candidate(CandidateSource::Trait(trait_def_id));
                        continue;
                    }
                    self.push_candidate(Candidate {
                            item,
                            import_ids,
                            kind: TraitCandidate(ty::Binder::dummy(trait_ref),
                                lint_ambiguous),
                        }, false);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1129    fn assemble_extension_candidates_for_trait(
1130        &mut self,
1131        import_ids: &'tcx [LocalDefId],
1132        trait_def_id: DefId,
1133        lint_ambiguous: bool,
1134    ) {
1135        let trait_args = self.fresh_args_for_item(self.span, trait_def_id);
1136        let trait_ref = ty::TraitRef::new_from_args(self.tcx, trait_def_id, trait_args);
1137
1138        if self.tcx.is_trait_alias(trait_def_id) {
1139            // For trait aliases, recursively assume all explicitly named traits are relevant
1140            for (bound_trait_pred, _) in
1141                traits::expand_trait_aliases(self.tcx, [(trait_ref.upcast(self.tcx), self.span)]).0
1142            {
1143                assert_eq!(bound_trait_pred.polarity(), ty::ClausePolarity::Positive);
1144                let bound_trait_ref = bound_trait_pred.map_bound(|pred| pred.trait_ref);
1145                for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
1146                    if !self.has_applicable_self(&item) {
1147                        self.record_static_candidate(CandidateSource::Trait(
1148                            bound_trait_ref.def_id(),
1149                        ));
1150                    } else {
1151                        self.push_candidate(
1152                            Candidate {
1153                                item,
1154                                import_ids,
1155                                kind: TraitCandidate(bound_trait_ref, lint_ambiguous),
1156                            },
1157                            false,
1158                        );
1159                    }
1160                }
1161            }
1162        } else {
1163            debug_assert!(self.tcx.is_trait(trait_def_id));
1164            if self.tcx.trait_is_auto(trait_def_id) {
1165                return;
1166            }
1167            for item in self.impl_or_trait_item(trait_def_id) {
1168                // Check whether `trait_def_id` defines a method with suitable name.
1169                if !self.has_applicable_self(&item) {
1170                    debug!("method has inapplicable self");
1171                    self.record_static_candidate(CandidateSource::Trait(trait_def_id));
1172                    continue;
1173                }
1174                self.push_candidate(
1175                    Candidate {
1176                        item,
1177                        import_ids,
1178                        kind: TraitCandidate(ty::Binder::dummy(trait_ref), lint_ambiguous),
1179                    },
1180                    false,
1181                );
1182            }
1183        }
1184    }
1185
1186    fn candidate_method_names(
1187        &self,
1188        candidate_filter: impl Fn(&ty::AssocItem) -> bool,
1189    ) -> Vec<Ident> {
1190        let mut set = FxHashSet::default();
1191        let mut names: Vec<_> = self
1192            .inherent_candidates
1193            .iter()
1194            .chain(&self.extension_candidates)
1195            .filter(|candidate| candidate_filter(&candidate.item))
1196            .filter(|candidate| {
1197                if let Some(return_ty) = self.return_type {
1198                    self.matches_return_type(candidate.item, return_ty)
1199                } else {
1200                    true
1201                }
1202            })
1203            // ensure that we don't suggest unstable methods
1204            .filter(|candidate| {
1205                // note that `DUMMY_SP` is ok here because it is only used for
1206                // suggestions and macro stuff which isn't applicable here.
1207                !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.eval_stability(candidate.item.def_id,
        None, DUMMY_SP, None) {
    stability::EvalResult::Deny { .. } => true,
    _ => false,
}matches!(
1208                    self.tcx.eval_stability(candidate.item.def_id, None, DUMMY_SP, None),
1209                    stability::EvalResult::Deny { .. }
1210                )
1211            })
1212            .map(|candidate| candidate.item.ident(self.tcx))
1213            .filter(|&name| set.insert(name))
1214            .collect();
1215
1216        // Sort them by the name so we have a stable result.
1217        names.sort_by(|a, b| a.as_str().cmp(b.as_str()));
1218        names
1219    }
1220
1221    ///////////////////////////////////////////////////////////////////////////
1222    // THE ACTUAL SEARCH
1223
1224    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("pick",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1224u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PickResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.method_name.is_some() {
                ::core::panicking::panic("assertion failed: self.method_name.is_some()")
            };
            let mut unsatisfied_predicates = Vec::new();
            if let Some(r) = self.pick_core(&mut unsatisfied_predicates) {
                return r;
            }
            if self.is_suggestion.0 {
                return Err(MethodError::NoMatch(NoMatchData {
                                static_candidates: ::alloc::vec::Vec::new(),
                                unsatisfied_predicates: ::alloc::vec::Vec::new(),
                                out_of_scope_traits: ::alloc::vec::Vec::new(),
                                similar_candidate: None,
                                mode: self.mode,
                            }));
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:1246",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1246u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pick: actual search failed, assemble diagnostics")
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let static_candidates =
                std::mem::take(self.static_candidates.get_mut());
            let private_candidate = self.private_candidate.take();
            self.reset();
            self.assemble_extension_candidates_for_all_traits();
            let out_of_scope_traits =
                match self.pick_core(&mut Vec::new()) {
                    Some(Ok(p)) =>
                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                [p.item.container_id(self.tcx)])),
                    Some(Err(MethodError::Ambiguity(v))) =>
                        v.into_iter().map(|source|
                                    match source {
                                        CandidateSource::Trait(id) => id,
                                        CandidateSource::Impl(impl_id) =>
                                            self.tcx.impl_trait_id(impl_id),
                                    }).collect(),
                    Some(Err(MethodError::NoMatch(NoMatchData {
                        out_of_scope_traits: others, .. }))) => {
                        if !others.is_empty() {
                            ::core::panicking::panic("assertion failed: others.is_empty()")
                        };
                        ::alloc::vec::Vec::new()
                    }
                    _ => ::alloc::vec::Vec::new(),
                };
            if let Some((kind, def_id)) = private_candidate {
                return Err(MethodError::PrivateMatch(kind, def_id,
                            out_of_scope_traits));
            }
            let similar_candidate = self.probe_for_similar_candidate()?;
            Err(MethodError::NoMatch(NoMatchData {
                        static_candidates,
                        unsatisfied_predicates,
                        out_of_scope_traits,
                        similar_candidate,
                        mode: self.mode,
                    }))
        }
    }
}#[instrument(level = "debug", skip(self))]
1225    fn pick(mut self) -> PickResult<'tcx> {
1226        assert!(self.method_name.is_some());
1227
1228        let mut unsatisfied_predicates = Vec::new();
1229
1230        if let Some(r) = self.pick_core(&mut unsatisfied_predicates) {
1231            return r;
1232        }
1233
1234        // If it's a `lookup_probe_for_diagnostic`, then quit early. No need to
1235        // probe for other candidates.
1236        if self.is_suggestion.0 {
1237            return Err(MethodError::NoMatch(NoMatchData {
1238                static_candidates: vec![],
1239                unsatisfied_predicates: vec![],
1240                out_of_scope_traits: vec![],
1241                similar_candidate: None,
1242                mode: self.mode,
1243            }));
1244        }
1245
1246        debug!("pick: actual search failed, assemble diagnostics");
1247
1248        let static_candidates = std::mem::take(self.static_candidates.get_mut());
1249        let private_candidate = self.private_candidate.take();
1250
1251        // things failed, so lets look at all traits, for diagnostic purposes now:
1252        self.reset();
1253
1254        self.assemble_extension_candidates_for_all_traits();
1255
1256        let out_of_scope_traits = match self.pick_core(&mut Vec::new()) {
1257            Some(Ok(p)) => vec![p.item.container_id(self.tcx)],
1258            Some(Err(MethodError::Ambiguity(v))) => v
1259                .into_iter()
1260                .map(|source| match source {
1261                    CandidateSource::Trait(id) => id,
1262                    CandidateSource::Impl(impl_id) => self.tcx.impl_trait_id(impl_id),
1263                })
1264                .collect(),
1265            Some(Err(MethodError::NoMatch(NoMatchData {
1266                out_of_scope_traits: others, ..
1267            }))) => {
1268                assert!(others.is_empty());
1269                vec![]
1270            }
1271            _ => vec![],
1272        };
1273
1274        if let Some((kind, def_id)) = private_candidate {
1275            return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits));
1276        }
1277        let similar_candidate = self.probe_for_similar_candidate()?;
1278
1279        Err(MethodError::NoMatch(NoMatchData {
1280            static_candidates,
1281            unsatisfied_predicates,
1282            out_of_scope_traits,
1283            similar_candidate,
1284            mode: self.mode,
1285        }))
1286    }
1287
1288    fn pick_core(
1289        &self,
1290        unsatisfied_predicates: &mut UnsatisfiedPredicates<'tcx>,
1291    ) -> Option<PickResult<'tcx>> {
1292        // Pick stable methods only first, and consider unstable candidates if not found.
1293        self.pick_all_method(&mut PickDiagHints {
1294            // This first cycle, maintain a list of unstable candidates which
1295            // we encounter. This will end up in the Pick for diagnostics.
1296            unstable_candidates: Some(Vec::new()),
1297            // Contribute to the list of unsatisfied predicates which may
1298            // also be used for diagnostics.
1299            unsatisfied_predicates,
1300        })
1301        .or_else(|| {
1302            self.pick_all_method(&mut PickDiagHints {
1303                // On the second search, don't provide a special list of unstable
1304                // candidates. This indicates to the picking code that it should
1305                // in fact include such unstable candidates in the actual
1306                // search.
1307                unstable_candidates: None,
1308                // And there's no need to duplicate ourselves in the
1309                // unsatisifed predicates list. Provide a throwaway list.
1310                unsatisfied_predicates: &mut Vec::new(),
1311            })
1312        })
1313    }
1314
1315    fn pick_all_method<'b>(
1316        &self,
1317        pick_diag_hints: &mut PickDiagHints<'b, 'tcx>,
1318    ) -> Option<PickResult<'tcx>> {
1319        let track_unstable_candidates = pick_diag_hints.unstable_candidates.is_some();
1320        self.steps
1321            .iter()
1322            // At this point we're considering the types to which the receiver can be converted,
1323            // so we want to follow the `Deref` chain not the `Receiver` chain. Filter out
1324            // steps which can only be reached by following the (longer) `Receiver` chain.
1325            .filter(|step| step.reachable_via_deref)
1326            .filter(|step| {
1327                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:1327",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1327u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pick_all_method: step={0:?}",
                                                    step) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("pick_all_method: step={:?}", step);
1328                // skip types that are from a type error or that would require dereferencing
1329                // a raw pointer
1330                !step.self_ty.value.references_error() && !step.from_unsafe_deref
1331            })
1332            .find_map(|step| {
1333                let InferOk { value: self_ty, obligations: instantiate_self_ty_obligations } = self
1334                    .fcx
1335                    .probe_instantiate_query_response(
1336                        self.span,
1337                        self.orig_steps_var_values,
1338                        &step.self_ty,
1339                    )
1340                    .unwrap_or_else(|_| {
1341                        ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("{0:?} was applicable but now isn\'t?", step.self_ty))span_bug!(self.span, "{:?} was applicable but now isn't?", step.self_ty)
1342                    });
1343
1344                let by_value_pick = self.pick_by_value_method(
1345                    step,
1346                    self_ty,
1347                    &instantiate_self_ty_obligations,
1348                    pick_diag_hints,
1349                );
1350
1351                // Check for shadowing of a by-reference method by a by-value method (see comments on check_for_shadowing)
1352                if let Some(by_value_pick) = by_value_pick {
1353                    if let Ok(by_value_pick) = by_value_pick.as_ref() {
1354                        if by_value_pick.kind == PickKind::InherentImplPick {
1355                            for mutbl in [hir::Mutability::Not, hir::Mutability::Mut] {
1356                                if let Err(e) = self.check_for_shadowed_autorefd_method(
1357                                    by_value_pick,
1358                                    step,
1359                                    self_ty,
1360                                    &instantiate_self_ty_obligations,
1361                                    mutbl,
1362                                    track_unstable_candidates,
1363                                ) {
1364                                    return Some(Err(e));
1365                                }
1366                            }
1367                        }
1368                    }
1369                    return Some(by_value_pick);
1370                }
1371
1372                let autoref_pick = self.pick_autorefd_method(
1373                    step,
1374                    self_ty,
1375                    &instantiate_self_ty_obligations,
1376                    hir::Mutability::Not,
1377                    pick_diag_hints,
1378                    None,
1379                );
1380                // Check for shadowing of a by-mut-ref method by a by-reference method (see comments on check_for_shadowing)
1381                if let Some(autoref_pick) = autoref_pick {
1382                    if let Ok(autoref_pick) = autoref_pick.as_ref() {
1383                        // Check we're not shadowing others
1384                        if autoref_pick.kind == PickKind::InherentImplPick {
1385                            if let Err(e) = self.check_for_shadowed_autorefd_method(
1386                                autoref_pick,
1387                                step,
1388                                self_ty,
1389                                &instantiate_self_ty_obligations,
1390                                hir::Mutability::Mut,
1391                                track_unstable_candidates,
1392                            ) {
1393                                return Some(Err(e));
1394                            }
1395                        }
1396                    }
1397                    return Some(autoref_pick);
1398                }
1399
1400                // Note that no shadowing errors are produced from here on,
1401                // as we consider const ptr methods.
1402                // We allow new methods that take *mut T to shadow
1403                // methods which took *const T, so there is no entry in
1404                // this list for the results of `pick_const_ptr_method`.
1405                // The reason is that the standard pointer cast method
1406                // (on a mutable pointer) always already shadows the
1407                // cast method (on a const pointer). So, if we added
1408                // `pick_const_ptr_method` to this method, the anti-
1409                // shadowing algorithm would always complain about
1410                // the conflict between *const::cast and *mut::cast.
1411                // In practice therefore this does constrain us:
1412                // we cannot add new
1413                //   self: *mut Self
1414                // methods to types such as NonNull or anything else
1415                // which implements Receiver, because this might in future
1416                // shadow existing methods taking
1417                //   self: *const NonNull<Self>
1418                // in the pointee. In practice, methods taking raw pointers
1419                // are rare, and it seems that it should be easily possible
1420                // to avoid such compatibility breaks.
1421                // We also don't check for reborrowed pin methods which
1422                // may be shadowed; these also seem unlikely to occur.
1423                self.pick_autorefd_method(
1424                    step,
1425                    self_ty,
1426                    &instantiate_self_ty_obligations,
1427                    hir::Mutability::Mut,
1428                    pick_diag_hints,
1429                    None,
1430                )
1431                .or_else(|| {
1432                    self.pick_const_ptr_method(
1433                        step,
1434                        self_ty,
1435                        &instantiate_self_ty_obligations,
1436                        pick_diag_hints,
1437                    )
1438                })
1439                .or_else(|| {
1440                    self.pick_reborrow_pin_method(
1441                        step,
1442                        self_ty,
1443                        &instantiate_self_ty_obligations,
1444                        pick_diag_hints,
1445                    )
1446                })
1447            })
1448    }
1449
1450    /// Check for cases where arbitrary self types allows shadowing
1451    /// of methods that might be a compatibility break. Specifically,
1452    /// we have something like:
1453    /// ```ignore (illustrative)
1454    /// struct A;
1455    /// impl A {
1456    ///   fn foo(self: &NonNull<A>) {}
1457    ///      // note this is by reference
1458    /// }
1459    /// ```
1460    /// then we've come along and added this method to `NonNull`:
1461    /// ```ignore (illustrative)
1462    ///   fn foo(self)  // note this is by value
1463    /// ```
1464    /// Report an error in this case.
1465    fn check_for_shadowed_autorefd_method(
1466        &self,
1467        possible_shadower: &Pick<'tcx>,
1468        step: &CandidateStep<'tcx>,
1469        self_ty: Ty<'tcx>,
1470        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1471        mutbl: hir::Mutability,
1472        track_unstable_candidates: bool,
1473    ) -> Result<(), MethodError<'tcx>> {
1474        // The errors emitted by this function are part of
1475        // the arbitrary self types work, and should not impact
1476        // other users.
1477        if !self.tcx.features().arbitrary_self_types()
1478            && !self.tcx.features().arbitrary_self_types_pointers()
1479        {
1480            return Ok(());
1481        }
1482
1483        // We don't want to remember any of the diagnostic hints from this
1484        // shadow search, but we do need to provide Some/None for the
1485        // unstable_candidates in order to reflect the behavior of the
1486        // main search.
1487        let mut pick_diag_hints = PickDiagHints {
1488            unstable_candidates: if track_unstable_candidates { Some(Vec::new()) } else { None },
1489            unsatisfied_predicates: &mut Vec::new(),
1490        };
1491        // Set criteria for how we find methods possibly shadowed by 'possible_shadower'
1492        let pick_constraints = PickConstraintsForShadowed {
1493            // It's the same `self` type...
1494            autoderefs: possible_shadower.autoderefs,
1495            // ... but the method was found in an impl block determined
1496            // by searching further along the Receiver chain than the other,
1497            // showing that it's a smart pointer type causing the problem...
1498            receiver_steps: possible_shadower.receiver_steps,
1499            // ... and they don't end up pointing to the same item in the
1500            // first place (could happen with things like blanket impls for T)
1501            def_id: possible_shadower.item.def_id,
1502        };
1503        // A note on the autoderefs above. Within pick_by_value_method, an extra
1504        // autoderef may be applied in order to reborrow a reference with
1505        // a different lifetime. That seems as though it would break the
1506        // logic of these constraints, since the number of autoderefs could
1507        // no longer be used to identify the fundamental type of the receiver.
1508        // However, this extra autoderef is applied only to by-value calls
1509        // where the receiver is already a reference. So this situation would
1510        // only occur in cases where the shadowing looks like this:
1511        // ```
1512        // struct A;
1513        // impl A {
1514        //   fn foo(self: &&NonNull<A>) {}
1515        //      // note this is by DOUBLE reference
1516        // }
1517        // ```
1518        // then we've come along and added this method to `NonNull`:
1519        // ```
1520        //   fn foo(&self)  // note this is by single reference
1521        // ```
1522        // and the call is:
1523        // ```
1524        // let bar = NonNull<Foo>;
1525        // let bar = &foo;
1526        // bar.foo();
1527        // ```
1528        // In these circumstances, the logic is wrong, and we wouldn't spot
1529        // the shadowing, because the autoderef-based maths wouldn't line up.
1530        // This is a niche case and we can live without generating an error
1531        // in the case of such shadowing.
1532        let potentially_shadowed_pick = self.pick_autorefd_method(
1533            step,
1534            self_ty,
1535            instantiate_self_ty_obligations,
1536            mutbl,
1537            &mut pick_diag_hints,
1538            Some(&pick_constraints),
1539        );
1540        // Look for actual pairs of shadower/shadowed which are
1541        // the sort of shadowing case we want to avoid. Specifically...
1542        if let Some(Ok(possible_shadowed)) = potentially_shadowed_pick.as_ref() {
1543            let sources = [possible_shadower, possible_shadowed]
1544                .into_iter()
1545                .map(|p| self.candidate_source_from_pick(p))
1546                .collect();
1547            return Err(MethodError::Ambiguity(sources));
1548        }
1549        Ok(())
1550    }
1551
1552    /// For each type `T` in the step list, this attempts to find a method where
1553    /// the (transformed) self type is exactly `T`. We do however do one
1554    /// transformation on the adjustment: if we are passing a region pointer in,
1555    /// we will potentially *reborrow* it to a shorter lifetime. This allows us
1556    /// to transparently pass `&mut` pointers, in particular, without consuming
1557    /// them for their entire lifetime.
1558    fn pick_by_value_method(
1559        &self,
1560        step: &CandidateStep<'tcx>,
1561        self_ty: Ty<'tcx>,
1562        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1563        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1564    ) -> Option<PickResult<'tcx>> {
1565        if step.unsize {
1566            return None;
1567        }
1568
1569        self.pick_method(self_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(|r| {
1570            r.map(|mut pick| {
1571                pick.autoderefs = step.autoderefs;
1572
1573                match *step.self_ty.value.value.kind() {
1574                    // Insert a `&*` or `&mut *` if this is a reference type:
1575                    ty::Ref(_, _, mutbl) => {
1576                        pick.autoderefs += 1;
1577                        pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::Autoref {
1578                            mutbl,
1579                            unsize: pick.autoref_or_ptr_adjustment.is_some_and(|a| a.get_unsize()),
1580                        })
1581                    }
1582
1583                    ty::Adt(def, args)
1584                        if self.tcx.features().pin_ergonomics()
1585                            && self.tcx.is_lang_item(def.did(), LangItem::Pin) =>
1586                    {
1587                        // make sure this is a pinned reference (and not a `Pin<Box>` or something)
1588                        if let ty::Ref(_, _, mutbl) = args[0].expect_ty().kind() {
1589                            pick.autoref_or_ptr_adjustment =
1590                                Some(AutorefOrPtrAdjustment::ReborrowPin(*mutbl));
1591                        }
1592                    }
1593
1594                    _ => (),
1595                }
1596
1597                pick
1598            })
1599        })
1600    }
1601
1602    fn pick_autorefd_method(
1603        &self,
1604        step: &CandidateStep<'tcx>,
1605        self_ty: Ty<'tcx>,
1606        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1607        mutbl: hir::Mutability,
1608        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1609        pick_constraints: Option<&PickConstraintsForShadowed>,
1610    ) -> Option<PickResult<'tcx>> {
1611        let tcx = self.tcx;
1612
1613        if let Some(pick_constraints) = pick_constraints {
1614            if !pick_constraints.may_shadow_based_on_autoderefs(step.autoderefs) {
1615                return None;
1616            }
1617        }
1618
1619        // In general, during probing we erase regions.
1620        let region = tcx.lifetimes.re_erased;
1621
1622        let autoref_ty = Ty::new_ref(tcx, region, self_ty, mutbl);
1623        self.pick_method(
1624            autoref_ty,
1625            instantiate_self_ty_obligations,
1626            pick_diag_hints,
1627            pick_constraints,
1628        )
1629        .map(|r| {
1630            r.map(|mut pick| {
1631                pick.autoderefs = step.autoderefs;
1632                pick.autoref_or_ptr_adjustment =
1633                    Some(AutorefOrPtrAdjustment::Autoref { mutbl, unsize: step.unsize });
1634                pick
1635            })
1636        })
1637    }
1638
1639    /// Looks for applicable methods if we reborrow a `Pin<&mut T>` as a `Pin<&T>`.
1640    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("pick_reborrow_pin_method",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1640u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instantiate_self_ty_obligations")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instantiate_self_ty_obligations");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instantiate_self_ty_obligations)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<PickResult<'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.tcx.features().pin_ergonomics() { return None; }
            let inner_ty =
                match self_ty.kind() {
                    ty::Adt(def, args) if
                        self.tcx.is_lang_item(def.did(), LangItem::Pin) => {
                        match args[0].expect_ty().kind() {
                            ty::Ref(_, ty, hir::Mutability::Mut) => *ty,
                            _ => { return None; }
                        }
                    }
                    _ => return None,
                };
            let region = self.tcx.lifetimes.re_erased;
            let autopin_ty =
                Ty::new_pinned_ref(self.tcx, region, inner_ty,
                    hir::Mutability::Not);
            self.pick_method(autopin_ty, instantiate_self_ty_obligations,
                    pick_diag_hints,
                    None).map(|r|
                    {
                        r.map(|mut pick|
                                {
                                    pick.autoderefs = step.autoderefs;
                                    pick.autoref_or_ptr_adjustment =
                                        Some(AutorefOrPtrAdjustment::ReborrowPin(hir::Mutability::Not));
                                    pick
                                })
                    })
        }
    }
}#[instrument(level = "debug", skip(self, step, pick_diag_hints))]
1641    fn pick_reborrow_pin_method(
1642        &self,
1643        step: &CandidateStep<'tcx>,
1644        self_ty: Ty<'tcx>,
1645        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1646        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1647    ) -> Option<PickResult<'tcx>> {
1648        if !self.tcx.features().pin_ergonomics() {
1649            return None;
1650        }
1651
1652        // make sure self is a Pin<&mut T>
1653        let inner_ty = match self_ty.kind() {
1654            ty::Adt(def, args) if self.tcx.is_lang_item(def.did(), LangItem::Pin) => {
1655                match args[0].expect_ty().kind() {
1656                    ty::Ref(_, ty, hir::Mutability::Mut) => *ty,
1657                    _ => {
1658                        return None;
1659                    }
1660                }
1661            }
1662            _ => return None,
1663        };
1664
1665        let region = self.tcx.lifetimes.re_erased;
1666        let autopin_ty = Ty::new_pinned_ref(self.tcx, region, inner_ty, hir::Mutability::Not);
1667        self.pick_method(autopin_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1668            |r| {
1669                r.map(|mut pick| {
1670                    pick.autoderefs = step.autoderefs;
1671                    pick.autoref_or_ptr_adjustment =
1672                        Some(AutorefOrPtrAdjustment::ReborrowPin(hir::Mutability::Not));
1673                    pick
1674                })
1675            },
1676        )
1677    }
1678
1679    /// If `self_ty` is `*mut T` then this picks `*const T` methods. The reason why we have a
1680    /// special case for this is because going from `*mut T` to `*const T` with autoderefs and
1681    /// autorefs would require dereferencing the pointer, which is not safe.
1682    fn pick_const_ptr_method(
1683        &self,
1684        step: &CandidateStep<'tcx>,
1685        self_ty: Ty<'tcx>,
1686        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1687        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1688    ) -> Option<PickResult<'tcx>> {
1689        // Don't convert an unsized reference to ptr
1690        if step.unsize {
1691            return None;
1692        }
1693
1694        let &ty::RawPtr(ty, hir::Mutability::Mut) = self_ty.kind() else {
1695            return None;
1696        };
1697
1698        let const_ptr_ty = Ty::new_imm_ptr(self.tcx, ty);
1699        self.pick_method(const_ptr_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1700            |r| {
1701                r.map(|mut pick| {
1702                    pick.autoderefs = step.autoderefs;
1703                    pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::ToConstPtr);
1704                    pick
1705                })
1706            },
1707        )
1708    }
1709
1710    fn pick_method(
1711        &self,
1712        self_ty: Ty<'tcx>,
1713        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1714        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1715        pick_constraints: Option<&PickConstraintsForShadowed>,
1716    ) -> Option<PickResult<'tcx>> {
1717        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:1717",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1717u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pick_method(self_ty={0})",
                                                    self.ty_to_string(self_ty)) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1718
1719        for (kind, candidates) in
1720            [("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1721        {
1722            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:1722",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1722u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("searching {0} candidates",
                                                    kind) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("searching {} candidates", kind);
1723            let res = self.consider_candidates(
1724                self_ty,
1725                instantiate_self_ty_obligations,
1726                candidates,
1727                pick_diag_hints,
1728                pick_constraints,
1729            );
1730            if let Some(pick) = res {
1731                return Some(pick);
1732            }
1733        }
1734
1735        if self.private_candidate.get().is_none() {
1736            if let Some(Ok(pick)) = self.consider_candidates(
1737                self_ty,
1738                instantiate_self_ty_obligations,
1739                &self.private_candidates,
1740                &mut PickDiagHints {
1741                    unstable_candidates: None,
1742                    unsatisfied_predicates: &mut ::alloc::vec::Vec::new()vec![],
1743                },
1744                None,
1745            ) {
1746                self.private_candidate.set(Some((pick.item.as_def_kind(), pick.item.def_id)));
1747            }
1748        }
1749        None
1750    }
1751
1752    fn consider_candidates(
1753        &self,
1754        self_ty: Ty<'tcx>,
1755        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1756        candidates: &[Candidate<'tcx>],
1757        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1758        pick_constraints: Option<&PickConstraintsForShadowed>,
1759    ) -> Option<PickResult<'tcx>> {
1760        let mut applicable_candidates: Vec<_> = candidates
1761            .iter()
1762            .filter(|candidate| {
1763                pick_constraints
1764                    .map(|pick_constraints| pick_constraints.candidate_may_shadow(&candidate))
1765                    .unwrap_or(true)
1766            })
1767            .map(|probe| {
1768                (
1769                    probe,
1770                    self.consider_probe(
1771                        self_ty,
1772                        instantiate_self_ty_obligations,
1773                        probe,
1774                        &mut pick_diag_hints.unsatisfied_predicates,
1775                    ),
1776                )
1777            })
1778            .filter(|&(_, status)| status != ProbeResult::NoMatch)
1779            .collect();
1780
1781        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:1781",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1781u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("applicable_candidates: {0:?}",
                                                    applicable_candidates) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("applicable_candidates: {:?}", applicable_candidates);
1782
1783        if applicable_candidates.len() > 1 {
1784            if let Some(pick) =
1785                self.collapse_candidates_to_trait_pick(self_ty, &applicable_candidates)
1786            {
1787                return Some(Ok(pick));
1788            }
1789        }
1790
1791        if let Some(uc) = &mut pick_diag_hints.unstable_candidates {
1792            applicable_candidates.retain(|&(candidate, _)| {
1793                if let stability::EvalResult::Deny { feature, .. } =
1794                    self.tcx.eval_stability(candidate.item.def_id, None, self.span, None)
1795                {
1796                    uc.push((candidate.clone(), feature));
1797                    return false;
1798                }
1799                true
1800            });
1801        }
1802
1803        if applicable_candidates.len() > 1 {
1804            // We collapse to a subtrait pick *after* filtering unstable candidates
1805            // to make sure we don't prefer a unstable subtrait method over a stable
1806            // supertrait method.
1807            if self.tcx.features().supertrait_item_shadowing() {
1808                if let Some(pick) =
1809                    self.collapse_candidates_to_subtrait_pick(self_ty, &applicable_candidates)
1810                {
1811                    return Some(Ok(pick));
1812                }
1813            }
1814
1815            let sources =
1816                applicable_candidates.iter().map(|p| self.candidate_source(p.0, self_ty)).collect();
1817            return Some(Err(MethodError::Ambiguity(sources)));
1818        }
1819
1820        applicable_candidates.pop().map(|(probe, status)| match status {
1821            ProbeResult::Match => Ok(probe.to_unadjusted_pick(
1822                self_ty,
1823                pick_diag_hints.unstable_candidates.clone().unwrap_or_default(),
1824            )),
1825            ProbeResult::NoMatch | ProbeResult::BadReturnType => Err(MethodError::BadReturnType),
1826        })
1827    }
1828}
1829
1830impl<'tcx> Pick<'tcx> {
1831    /// In case there were unstable name collisions, emit them as a lint.
1832    /// Checks whether two picks do not refer to the same trait item for the same `Self` type.
1833    /// Only useful for comparisons of picks in order to improve diagnostics.
1834    /// Do not use for type checking.
1835    pub(crate) fn differs_from(&self, other: &Self) -> bool {
1836        let Self {
1837            item: AssocItem { def_id, kind: _, container: _ },
1838            kind: _,
1839            import_ids: _,
1840            autoderefs: _,
1841            autoref_or_ptr_adjustment: _,
1842            self_ty,
1843            unstable_candidates: _,
1844            receiver_steps: _,
1845            shadowed_candidates: _,
1846        } = *self;
1847        self_ty != other.self_ty || def_id != other.item.def_id
1848    }
1849
1850    /// In case there were unstable name collisions, emit them as a lint.
1851    pub(crate) fn maybe_emit_unstable_name_collision_hint(
1852        &self,
1853        tcx: TyCtxt<'tcx>,
1854        span: Span,
1855        scope_expr_id: HirId,
1856    ) {
1857        struct ItemMaybeBeAddedToStd<'a, 'tcx> {
1858            this: &'a Pick<'tcx>,
1859            tcx: TyCtxt<'tcx>,
1860            span: Span,
1861        }
1862
1863        impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for ItemMaybeBeAddedToStd<'b, 'tcx> {
1864            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1865                let Self { this, tcx, span } = self;
1866                let def_kind = this.item.as_def_kind();
1867                let mut lint = Diag::new(
1868                    dcx,
1869                    level,
1870                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1} with this name may be added to the standard library in the future",
                tcx.def_kind_descr_article(def_kind, this.item.def_id),
                tcx.def_kind_descr(def_kind, this.item.def_id)))
    })format!(
1871                        "{} {} with this name may be added to the standard library in the future",
1872                        tcx.def_kind_descr_article(def_kind, this.item.def_id),
1873                        tcx.def_kind_descr(def_kind, this.item.def_id),
1874                    ),
1875                );
1876
1877                match (this.item.kind, this.item.container) {
1878                    (ty::AssocKind::Fn { .. }, _) => {
1879                        // FIXME: This should be a `span_suggestion` instead of `help`
1880                        // However `this.span` only
1881                        // highlights the method name, so we can't use it. Also consider reusing
1882                        // the code from `report_method_error()`.
1883                        lint.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("call with fully qualified syntax `{0}(...)` to keep using the current method",
                tcx.def_path_str(this.item.def_id)))
    })format!(
1884                            "call with fully qualified syntax `{}(...)` to keep using the current \
1885                                 method",
1886                            tcx.def_path_str(this.item.def_id),
1887                        ));
1888                    }
1889                    (ty::AssocKind::Const { name, .. }, ty::AssocContainer::Trait) => {
1890                        let def_id = this.item.container_id(tcx);
1891                        lint.span_suggestion(
1892                            span,
1893                            "use the fully qualified path to the associated const",
1894                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", this.self_ty,
                tcx.def_path_str(def_id), name))
    })format!("<{} as {}>::{}", this.self_ty, tcx.def_path_str(def_id), name),
1895                            Applicability::MachineApplicable,
1896                        );
1897                    }
1898                    _ => {}
1899                }
1900                tcx.disabled_nightly_features(
1901                    &mut lint,
1902                    this.unstable_candidates.iter().map(|(candidate, feature)| {
1903                        (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" `{0}`",
                tcx.def_path_str(candidate.item.def_id)))
    })format!(" `{}`", tcx.def_path_str(candidate.item.def_id)), *feature)
1904                    }),
1905                );
1906                lint
1907            }
1908        }
1909
1910        if self.unstable_candidates.is_empty() {
1911            return;
1912        }
1913        tcx.emit_node_span_lint(
1914            UNSTABLE_NAME_COLLISIONS,
1915            scope_expr_id,
1916            span,
1917            ItemMaybeBeAddedToStd { this: self, tcx, span },
1918        );
1919    }
1920}
1921
1922impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
1923    fn select_trait_candidate_for_diagnostics(
1924        &self,
1925        trait_ref: ty::TraitRef<'tcx>,
1926    ) -> traits::SelectionResult<'tcx, traits::Selection<'tcx>> {
1927        let obligation =
1928            traits::Obligation::new(self.tcx, self.misc(self.span), self.param_env, trait_ref);
1929        let candidate = traits::SelectionContext::new(self).select(&obligation);
1930        if let Ok(Some(traits::ImplSource::UserDefined(impl_source_user_defined_data))) = &candidate
1931            && self.infcx.tcx.do_not_recommend_impl(impl_source_user_defined_data.impl_def_id)
1932        {
1933            return Err(traits::SelectionError::Unimplemented);
1934        }
1935        candidate
1936    }
1937
1938    /// Used for ambiguous method call error reporting. Uses probing that throws away the result internally,
1939    /// so do not use to make a decision that may lead to a successful compilation.
1940    fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>) -> CandidateSource {
1941        match candidate.kind {
1942            InherentImplCandidate { .. } => {
1943                CandidateSource::Impl(candidate.item.container_id(self.tcx))
1944            }
1945            ObjectCandidate(_) | WhereClauseCandidate(_) => {
1946                CandidateSource::Trait(candidate.item.container_id(self.tcx))
1947            }
1948            TraitCandidate(trait_ref, _) => self.probe(|_| {
1949                let trait_ref = self.instantiate_binder_with_fresh_vars(
1950                    self.span,
1951                    BoundRegionConversionTime::FnCall,
1952                    trait_ref,
1953                );
1954                let (xform_self_ty, _) =
1955                    self.xform_self_ty(candidate.item, trait_ref.self_ty(), trait_ref.args);
1956                // Guide the trait selection to show impls that have methods whose type matches
1957                // up with the `self` parameter of the method.
1958                let _ = self.at(&ObligationCause::dummy(), self.param_env).sup(
1959                    DefineOpaqueTypes::Yes,
1960                    xform_self_ty,
1961                    self_ty,
1962                );
1963                match self.select_trait_candidate_for_diagnostics(trait_ref) {
1964                    Ok(Some(traits::ImplSource::UserDefined(ref impl_data))) => {
1965                        // If only a single impl matches, make the error message point
1966                        // to that impl.
1967                        CandidateSource::Impl(impl_data.impl_def_id)
1968                    }
1969                    _ => CandidateSource::Trait(candidate.item.container_id(self.tcx)),
1970                }
1971            }),
1972        }
1973    }
1974
1975    fn candidate_source_from_pick(&self, pick: &Pick<'tcx>) -> CandidateSource {
1976        match pick.kind {
1977            InherentImplPick => CandidateSource::Impl(pick.item.container_id(self.tcx)),
1978            ObjectPick | WhereClausePick(_) | TraitPick(_) => {
1979                CandidateSource::Trait(pick.item.container_id(self.tcx))
1980            }
1981        }
1982    }
1983
1984    fn consider_probe(
1985        &self,
1986        self_ty: Ty<'tcx>,
1987        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1988        probe: &Candidate<'tcx>,
1989        possibly_unsatisfied_predicates: &mut UnsatisfiedPredicates<'tcx>,
1990    ) -> ProbeResult {
1991        self.probe(|snapshot| {
1992            let outer_universe = self.universe();
1993
1994            let mut result = ProbeResult::Match;
1995            let cause = &self.misc(self.span);
1996            let ocx = ObligationCtxt::new_with_diagnostics(self);
1997
1998            // Subtle: we're not *really* instantiating the current self type while
1999            // probing, but instead fully recompute the autoderef steps once we've got
2000            // a final `Pick`. We can't nicely handle these obligations outside of a probe.
2001            //
2002            // We simply handle them for each candidate here for now. That's kinda scuffed
2003            // and ideally we just put them into the `FnCtxt` right away. We need to consider
2004            // them to deal with defining uses in `method_autoderef_steps`.
2005            if self.next_trait_solver() {
2006                ocx.register_obligations(instantiate_self_ty_obligations.iter().cloned());
2007                let errors = ocx.try_evaluate_obligations();
2008                if !errors.no_errors() {
2009                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected autoderef error {0:?}", errors)));
};unreachable!("unexpected autoderef error {errors:?}");
2010                }
2011            }
2012
2013            let mut trait_predicate = None;
2014            let (mut xform_self_ty, mut xform_ret_ty);
2015
2016            match probe.kind {
2017                InherentImplCandidate { impl_def_id, .. } => {
2018                    let impl_args = self.fresh_args_for_item(self.span, impl_def_id);
2019                    let impl_ty = self
2020                        .tcx
2021                        .type_of(impl_def_id)
2022                        .instantiate(self.tcx, impl_args)
2023                        .skip_norm_wip();
2024                    (xform_self_ty, xform_ret_ty) =
2025                        self.xform_self_ty(probe.item, impl_ty, impl_args);
2026                    xform_self_ty =
2027                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_self_ty));
2028                    match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
2029                    {
2030                        Ok(()) => {}
2031                        Err(err) => {
2032                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:2032",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2032u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> cannot relate self-types {0:?}",
                                                    err) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> cannot relate self-types {:?}", err);
2033                            return ProbeResult::NoMatch;
2034                        }
2035                    }
2036                    // FIXME: Weirdly, we normalize the ret ty in this candidate, but no other candidates.
2037                    xform_ret_ty =
2038                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_ret_ty));
2039                    // Check whether the impl imposes obligations we have to worry about.
2040                    let impl_def_id = probe.item.container_id(self.tcx);
2041                    let impl_bounds =
2042                        self.tcx.clauses_of(impl_def_id).instantiate(self.tcx, impl_args);
2043                    // Convert the bounds into obligations.
2044                    ocx.register_obligations(traits::predicates_for_generics(
2045                        |idx, span| {
2046                            let code = ObligationCauseCode::WhereClauseInExpr(
2047                                impl_def_id,
2048                                span,
2049                                self.scope_expr_id,
2050                                idx,
2051                            );
2052                            self.cause(self.span, code)
2053                        },
2054                        |clause| ocx.normalize(cause, self.param_env, clause),
2055                        self.param_env,
2056                        impl_bounds,
2057                    ));
2058                }
2059                TraitCandidate(poly_trait_ref, _) => {
2060                    // Some trait methods are excluded for arrays before 2021.
2061                    // (`array.into_iter()` wants a slice iterator for compatibility.)
2062                    if let Some(method_name) = self.method_name {
2063                        if self_ty.is_array() && !method_name.span.at_least_rust_2021() {
2064                            let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
2065                            if trait_def.skip_array_during_method_dispatch {
2066                                return ProbeResult::NoMatch;
2067                            }
2068                        }
2069
2070                        // Some trait methods are excluded for boxed slices before 2024.
2071                        // (`boxed_slice.into_iter()` wants a slice iterator for compatibility.)
2072                        if self_ty.boxed_ty().is_some_and(Ty::is_slice)
2073                            && !method_name.span.at_least_rust_2024()
2074                        {
2075                            let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
2076                            if trait_def.skip_boxed_slice_during_method_dispatch {
2077                                return ProbeResult::NoMatch;
2078                            }
2079                        }
2080                    }
2081
2082                    let trait_ref = self.instantiate_binder_with_fresh_vars(
2083                        self.span,
2084                        BoundRegionConversionTime::FnCall,
2085                        poly_trait_ref,
2086                    );
2087                    let trait_ref =
2088                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(trait_ref));
2089                    (xform_self_ty, xform_ret_ty) =
2090                        self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
2091                    xform_self_ty =
2092                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_self_ty));
2093                    match self_ty.kind() {
2094                        // HACK: opaque types will match anything for which their bounds hold.
2095                        // Thus we need to prevent them from trying to match the `&_` autoref
2096                        // candidates that get created for `&self` trait methods.
2097                        &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. })
2098                            if !self.next_trait_solver()
2099                                && self.infcx.can_define_opaque_ty(def_id)
2100                                && !xform_self_ty.is_ty_var() =>
2101                        {
2102                            return ProbeResult::NoMatch;
2103                        }
2104                        _ => match ocx.relate(
2105                            cause,
2106                            self.param_env,
2107                            self.variance(),
2108                            self_ty,
2109                            xform_self_ty,
2110                        ) {
2111                            Ok(()) => {}
2112                            Err(err) => {
2113                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:2113",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2113u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> cannot relate self-types {0:?}",
                                                    err) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> cannot relate self-types {:?}", err);
2114                                return ProbeResult::NoMatch;
2115                            }
2116                        },
2117                    }
2118                    let obligation = traits::Obligation::new(
2119                        self.tcx,
2120                        cause.clone(),
2121                        self.param_env,
2122                        ty::Binder::dummy(trait_ref),
2123                    );
2124
2125                    // We only need this hack to deal with fatal overflow in the old solver.
2126                    if self.infcx.next_trait_solver() || self.infcx.predicate_may_hold(&obligation)
2127                    {
2128                        ocx.register_obligation(obligation);
2129                    } else {
2130                        result = ProbeResult::NoMatch;
2131                        if let Ok(Some(candidate)) =
2132                            self.select_trait_candidate_for_diagnostics(trait_ref)
2133                        {
2134                            for nested_obligation in candidate.nested_obligations() {
2135                                if !self.infcx.predicate_may_hold(&nested_obligation) {
2136                                    possibly_unsatisfied_predicates.push((
2137                                        self.resolve_vars_if_possible(nested_obligation.predicate),
2138                                        Some(self.resolve_vars_if_possible(obligation.predicate)),
2139                                        Some(nested_obligation.cause),
2140                                    ));
2141                                }
2142                            }
2143                        }
2144                    }
2145
2146                    trait_predicate = Some(trait_ref.upcast(self.tcx));
2147                }
2148                ObjectCandidate(poly_trait_ref) | WhereClauseCandidate(poly_trait_ref) => {
2149                    let trait_ref = self.instantiate_binder_with_fresh_vars(
2150                        self.span,
2151                        BoundRegionConversionTime::FnCall,
2152                        poly_trait_ref,
2153                    );
2154                    (xform_self_ty, xform_ret_ty) =
2155                        self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
2156
2157                    if #[allow(non_exhaustive_omitted_patterns)] match probe.kind {
    WhereClauseCandidate(_) => true,
    _ => false,
}matches!(probe.kind, WhereClauseCandidate(_)) {
2158                        // `WhereClauseCandidate` requires that the self type is a param,
2159                        // because it has special behavior with candidate preference as an
2160                        // inherent pick.
2161                        let ty = ocx.normalize(
2162                            cause,
2163                            self.param_env,
2164                            Unnormalized::new_wip(trait_ref.self_ty()),
2165                        );
2166                        if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Param(_) => true,
    _ => false,
}matches!(ty.kind(), ty::Param(_)) {
2167                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:2167",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2167u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> not a param ty: {0:?}",
                                                    xform_self_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> not a param ty: {xform_self_ty:?}");
2168                            return ProbeResult::NoMatch;
2169                        }
2170                    }
2171
2172                    xform_self_ty =
2173                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_self_ty));
2174                    match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
2175                    {
2176                        Ok(()) => {}
2177                        Err(err) => {
2178                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:2178",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2178u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> cannot relate self-types {0:?}",
                                                    err) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> cannot relate self-types {:?}", err);
2179                            return ProbeResult::NoMatch;
2180                        }
2181                    }
2182                }
2183            }
2184
2185            // See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/134>.
2186            //
2187            // In the new solver, check the well-formedness of the return type.
2188            // This emulates, in a way, the predicates that fall out of
2189            // normalizing the return type in the old solver.
2190            //
2191            // FIXME(-Znext-solver): We alternatively could check the predicates of
2192            // the method itself hold, but we intentionally do not do this in the old
2193            // solver b/c of cycles, and doing it in the new solver would be stronger.
2194            // This should be fixed in the future, since it likely leads to much better
2195            // method winnowing.
2196            if let Some(xform_ret_ty) = xform_ret_ty
2197                && self.infcx.next_trait_solver()
2198            {
2199                ocx.register_obligation(traits::Obligation::new(
2200                    self.tcx,
2201                    cause.clone(),
2202                    self.param_env,
2203                    ty::ClauseKind::WellFormed(xform_ret_ty.into()),
2204                ));
2205            }
2206
2207            // Evaluate those obligations to see if they might possibly hold.
2208            for error in ocx.try_evaluate_obligations() {
2209                result = ProbeResult::NoMatch;
2210                let nested_predicate = self.resolve_vars_if_possible(error.obligation.predicate);
2211                if let Some(trait_predicate) = trait_predicate
2212                    && nested_predicate == self.resolve_vars_if_possible(trait_predicate)
2213                {
2214                    // Don't report possibly unsatisfied predicates if the root
2215                    // trait obligation from a `TraitCandidate` is unsatisfied.
2216                    // That just means the candidate doesn't hold.
2217                } else {
2218                    possibly_unsatisfied_predicates.push((
2219                        nested_predicate,
2220                        Some(self.resolve_vars_if_possible(error.root_obligation.predicate))
2221                            .filter(|root_predicate| *root_predicate != nested_predicate),
2222                        Some(error.obligation.cause),
2223                    ));
2224                }
2225            }
2226
2227            if let ProbeResult::Match = result
2228                && let Some(return_ty) = self.return_type
2229                && let Some(mut xform_ret_ty) = xform_ret_ty
2230            {
2231                // `xform_ret_ty` has only been normalized for `InherentImplCandidate`.
2232                // We don't normalize the other candidates for perf/backwards-compat reasons...
2233                // but `self.return_type` is only set on the diagnostic-path, so we
2234                // should be okay doing it here.
2235                if !#[allow(non_exhaustive_omitted_patterns)] match probe.kind {
    InherentImplCandidate { .. } => true,
    _ => false,
}matches!(probe.kind, InherentImplCandidate { .. }) {
2236                    xform_ret_ty =
2237                        ocx.normalize(&cause, self.param_env, Unnormalized::new_wip(xform_ret_ty));
2238                }
2239
2240                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:2240",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2240u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("comparing return_ty {0:?} with xform ret ty {1:?}",
                                                    return_ty, xform_ret_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("comparing return_ty {:?} with xform ret ty {:?}", return_ty, xform_ret_ty);
2241                match ocx.relate(cause, self.param_env, self.variance(), xform_ret_ty, return_ty) {
2242                    Ok(()) => {}
2243                    Err(_) => {
2244                        result = ProbeResult::BadReturnType;
2245                    }
2246                }
2247
2248                // Evaluate those obligations to see if they might possibly hold.
2249                for error in ocx.try_evaluate_obligations() {
2250                    result = ProbeResult::NoMatch;
2251                    possibly_unsatisfied_predicates.push((
2252                        error.obligation.predicate,
2253                        Some(error.root_obligation.predicate)
2254                            .filter(|predicate| *predicate != error.obligation.predicate),
2255                        Some(error.root_obligation.cause),
2256                    ));
2257                }
2258            }
2259
2260            if self.infcx.next_trait_solver() {
2261                if self.should_reject_candidate_due_to_opaque_treated_as_rigid(trait_predicate) {
2262                    result = ProbeResult::NoMatch;
2263                }
2264            }
2265
2266            // Previously, method probe used `evaluate_predicate` to determine if a predicate
2267            // was impossible to satisfy. This did a leak check, so we must also do a leak
2268            // check here to prevent backwards-incompatible ambiguity being introduced. See
2269            // `tests/ui/methods/leak-check-disquality.rs` for a simple example of when this
2270            // may happen.
2271            if let Err(_) = self.leak_check(outer_universe, Some(snapshot)) {
2272                result = ProbeResult::NoMatch;
2273            }
2274
2275            result
2276        })
2277    }
2278
2279    /// Trait candidates for not-yet-defined opaque types are a somewhat hacky.
2280    ///
2281    /// We want to only accept trait methods if they were hold even if the
2282    /// opaque types were rigid. To handle this, we both check that for trait
2283    /// candidates the goal were to hold even when treating opaques as rigid,
2284    /// see [OpaqueTypesJank](rustc_trait_selection::solve::OpaqueTypesJank).
2285    ///
2286    /// We also check that all opaque types encountered as self types in the
2287    /// autoderef chain don't get constrained when applying the candidate.
2288    /// Importantly, this also handles calling methods taking `&self` on
2289    /// `impl Trait` to reject the "by-self" candidate.
2290    ///
2291    /// This needs to happen at the end of `consider_probe` as we need to take
2292    /// all the constraints from that into account.
2293    x;#[instrument(level = "debug", skip(self), ret)]
2294    fn should_reject_candidate_due_to_opaque_treated_as_rigid(
2295        &self,
2296        trait_predicate: Option<ty::Predicate<'tcx>>,
2297    ) -> bool {
2298        // This function is what hacky and doesn't perfectly do what we want it to.
2299        // It's not soundness critical and we should be able to freely improve this
2300        // in the future.
2301        //
2302        // Some concrete edge cases include the fact that `goal_may_hold_opaque_types_jank`
2303        // also fails if there are any constraints opaques which are never used as a self
2304        // type. We also allow where-bounds which are currently ambiguous but end up
2305        // constraining an opaque later on.
2306
2307        // Check whether the trait candidate would not be applicable if the
2308        // opaque type were rigid.
2309        if let Some(predicate) = trait_predicate {
2310            let goal = Goal { param_env: self.param_env, predicate };
2311            if !self.infcx.goal_may_hold_opaque_types_jank(goal) {
2312                return true;
2313            }
2314        }
2315
2316        // Check whether any opaque types in the autoderef chain have been
2317        // constrained.
2318        for step in self.steps {
2319            if step.self_ty_is_opaque {
2320                debug!(?step.autoderefs, ?step.self_ty, "self_type_is_opaque");
2321                let constrained_opaque = self.probe(|_| {
2322                    // If we fail to instantiate the self type of this
2323                    // step, this part of the deref-chain is no longer
2324                    // reachable. In this case we don't care about opaque
2325                    // types there.
2326                    let Ok(ok) = self.fcx.probe_instantiate_query_response(
2327                        self.span,
2328                        self.orig_steps_var_values,
2329                        &step.self_ty,
2330                    ) else {
2331                        debug!("failed to instantiate self_ty");
2332                        return false;
2333                    };
2334                    let ocx = ObligationCtxt::new(self);
2335                    let self_ty = ocx.register_infer_ok_obligations(ok);
2336                    if !ocx.try_evaluate_obligations().no_errors() {
2337                        debug!("failed to prove instantiate self_ty obligations");
2338                        return false;
2339                    }
2340
2341                    !self.resolve_vars_if_possible(self_ty).is_ty_var()
2342                });
2343                if constrained_opaque {
2344                    debug!("opaque type has been constrained");
2345                    return true;
2346                }
2347            }
2348        }
2349
2350        false
2351    }
2352
2353    /// Sometimes we get in a situation where we have multiple probes that are all impls of the
2354    /// same trait, but we don't know which impl to use. In this case, since in all cases the
2355    /// external interface of the method can be determined from the trait, it's ok not to decide.
2356    /// We can basically just collapse all of the probes for various impls into one where-clause
2357    /// probe. This will result in a pending obligation so when more type-info is available we can
2358    /// make the final decision.
2359    ///
2360    /// Example (`tests/ui/methods/method-two-trait-defer-resolution-1.rs`):
2361    ///
2362    /// ```ignore (illustrative)
2363    /// trait Foo { ... }
2364    /// impl Foo for Vec<i32> { ... }
2365    /// impl Foo for Vec<usize> { ... }
2366    /// ```
2367    ///
2368    /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
2369    /// use, so it's ok to just commit to "using the method from the trait Foo".
2370    fn collapse_candidates_to_trait_pick(
2371        &self,
2372        self_ty: Ty<'tcx>,
2373        probes: &[(&Candidate<'tcx>, ProbeResult)],
2374    ) -> Option<Pick<'tcx>> {
2375        // Do all probes correspond to the same trait?
2376        let container = probes[0].0.item.trait_container(self.tcx)?;
2377        for (p, _) in &probes[1..] {
2378            let p_container = p.item.trait_container(self.tcx)?;
2379            if p_container != container {
2380                return None;
2381            }
2382        }
2383
2384        let lint_ambiguous = match probes[0].0.kind {
2385            TraitCandidate(_, lint) => lint,
2386            _ => false,
2387        };
2388
2389        // FIXME: check the return type here somehow.
2390        // If so, just use this trait and call it a day.
2391        Some(Pick {
2392            item: probes[0].0.item,
2393            kind: TraitPick(lint_ambiguous),
2394            import_ids: probes[0].0.import_ids,
2395            autoderefs: 0,
2396            autoref_or_ptr_adjustment: None,
2397            self_ty,
2398            unstable_candidates: ::alloc::vec::Vec::new()vec![],
2399            receiver_steps: None,
2400            shadowed_candidates: ::alloc::vec::Vec::new()vec![],
2401        })
2402    }
2403
2404    /// Much like `collapse_candidates_to_trait_pick`, this method allows us to collapse
2405    /// multiple conflicting picks if there is one pick whose trait container is a subtrait
2406    /// of the trait containers of all of the other picks.
2407    ///
2408    /// This is the method-probe analogue of
2409    /// `rustc_hir_analysis::hir_ty_lowering::HirTyLowerer::collapse_candidates_to_subtrait_pick`;
2410    /// keep both implementations in sync.
2411    ///
2412    /// This implements RFC #3624.
2413    fn collapse_candidates_to_subtrait_pick(
2414        &self,
2415        self_ty: Ty<'tcx>,
2416        probes: &[(&Candidate<'tcx>, ProbeResult)],
2417    ) -> Option<Pick<'tcx>> {
2418        let mut child_candidate = probes[0].0;
2419        let mut child_trait = child_candidate.item.trait_container(self.tcx)?;
2420        let mut supertraits: SsoHashSet<_> = supertrait_def_ids(self.tcx, child_trait).collect();
2421
2422        let mut remaining_candidates: Vec<_> = probes[1..].iter().map(|&(p, _)| p).collect();
2423        while !remaining_candidates.is_empty() {
2424            let mut made_progress = false;
2425            let mut next_round = ::alloc::vec::Vec::new()vec![];
2426
2427            for remaining_candidate in remaining_candidates {
2428                let remaining_trait = remaining_candidate.item.trait_container(self.tcx)?;
2429                if supertraits.contains(&remaining_trait) {
2430                    made_progress = true;
2431                    continue;
2432                }
2433
2434                // This candidate is not a supertrait of the `child_trait`.
2435                // Check if it's a subtrait of the `child_trait`, instead.
2436                // If it is, then it must have been a subtrait of every
2437                // other pick we've eliminated at this point. It will
2438                // take over at this point.
2439                let remaining_trait_supertraits: SsoHashSet<_> =
2440                    supertrait_def_ids(self.tcx, remaining_trait).collect();
2441                if remaining_trait_supertraits.contains(&child_trait) {
2442                    child_candidate = remaining_candidate;
2443                    child_trait = remaining_trait;
2444                    supertraits = remaining_trait_supertraits;
2445                    made_progress = true;
2446                    continue;
2447                }
2448
2449                // Neither `child_trait` or the current candidate are
2450                // supertraits of each other.
2451                // Don't bail here, since we may be comparing two supertraits
2452                // of a common subtrait. These two supertraits won't be related
2453                // at all, but we will pick them up next round when we find their
2454                // child as we continue iterating in this round.
2455                next_round.push(remaining_candidate);
2456            }
2457
2458            if made_progress {
2459                // If we've made progress, iterate again.
2460                remaining_candidates = next_round;
2461            } else {
2462                // Otherwise, we must have at least two candidates which
2463                // are not related to each other at all.
2464                return None;
2465            }
2466        }
2467
2468        let lint_ambiguous = match probes[0].0.kind {
2469            TraitCandidate(_, lint) => lint,
2470            _ => false,
2471        };
2472
2473        Some(Pick {
2474            item: child_candidate.item,
2475            kind: TraitPick(lint_ambiguous),
2476            import_ids: child_candidate.import_ids,
2477            autoderefs: 0,
2478            autoref_or_ptr_adjustment: None,
2479            self_ty,
2480            unstable_candidates: ::alloc::vec::Vec::new()vec![],
2481            shadowed_candidates: probes
2482                .iter()
2483                .map(|(c, _)| c.item)
2484                .filter(|item| item.def_id != child_candidate.item.def_id)
2485                .collect(),
2486            receiver_steps: None,
2487        })
2488    }
2489
2490    /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
2491    /// candidate method where the method name may have been misspelled. Similarly to other
2492    /// edit distance based suggestions, we provide at most one such suggestion.
2493    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("probe_for_similar_candidate",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2493u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Option<ty::AssocItem>, MethodError<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:2497",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2497u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("probing for method names similar to {0:?}",
                                                                self.method_name) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            self.probe(|_|
                    {
                        let mut pcx =
                            ProbeContext::new(self.fcx, self.span, self.mode,
                                self.method_name, self.return_type,
                                self.orig_steps_var_values, self.steps, self.scope_expr_id,
                                IsSuggestion(true));
                        pcx.allow_similar_names = true;
                        pcx.assemble_inherent_candidates();
                        pcx.assemble_extension_candidates_for_all_traits();
                        let method_names = pcx.candidate_method_names(|_| true);
                        pcx.allow_similar_names = false;
                        let applicable_close_candidates: Vec<ty::AssocItem> =
                            method_names.iter().filter_map(|&method_name|
                                        {
                                            pcx.reset();
                                            pcx.method_name = Some(method_name);
                                            pcx.assemble_inherent_candidates();
                                            pcx.assemble_extension_candidates_for_all_traits();
                                            pcx.pick_core(&mut Vec::new()).and_then(|pick|
                                                        pick.ok()).map(|pick| pick.item)
                                        }).collect();
                        if applicable_close_candidates.is_empty() {
                            Ok(None)
                        } else {
                            let best_name =
                                applicable_close_candidates.iter().find(|cand|
                                                self.matches_by_doc_alias(cand.def_id)).map(|cand|
                                            cand.name()).or_else(||
                                        {
                                            let names =
                                                applicable_close_candidates.iter().map(|cand|
                                                            cand.name()).collect::<Vec<Symbol>>();
                                            find_best_match_for_name_with_substrings(&names,
                                                self.method_name.unwrap().name, None)
                                        });
                            Ok(best_name.and_then(|best_name|
                                        {
                                            applicable_close_candidates.into_iter().find(|method|
                                                    method.name() == best_name)
                                        }))
                        }
                    })
        }
    }
}#[instrument(level = "debug", skip(self))]
2494    pub(crate) fn probe_for_similar_candidate(
2495        &mut self,
2496    ) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
2497        debug!("probing for method names similar to {:?}", self.method_name);
2498
2499        self.probe(|_| {
2500            let mut pcx = ProbeContext::new(
2501                self.fcx,
2502                self.span,
2503                self.mode,
2504                self.method_name,
2505                self.return_type,
2506                self.orig_steps_var_values,
2507                self.steps,
2508                self.scope_expr_id,
2509                IsSuggestion(true),
2510            );
2511            pcx.allow_similar_names = true;
2512            pcx.assemble_inherent_candidates();
2513            pcx.assemble_extension_candidates_for_all_traits();
2514
2515            let method_names = pcx.candidate_method_names(|_| true);
2516            pcx.allow_similar_names = false;
2517            let applicable_close_candidates: Vec<ty::AssocItem> = method_names
2518                .iter()
2519                .filter_map(|&method_name| {
2520                    pcx.reset();
2521                    pcx.method_name = Some(method_name);
2522                    pcx.assemble_inherent_candidates();
2523                    pcx.assemble_extension_candidates_for_all_traits();
2524                    pcx.pick_core(&mut Vec::new()).and_then(|pick| pick.ok()).map(|pick| pick.item)
2525                })
2526                .collect();
2527
2528            if applicable_close_candidates.is_empty() {
2529                Ok(None)
2530            } else {
2531                let best_name = applicable_close_candidates
2532                    .iter()
2533                    .find(|cand| self.matches_by_doc_alias(cand.def_id))
2534                    .map(|cand| cand.name())
2535                    .or_else(|| {
2536                        let names = applicable_close_candidates
2537                            .iter()
2538                            .map(|cand| cand.name())
2539                            .collect::<Vec<Symbol>>();
2540                        find_best_match_for_name_with_substrings(
2541                            &names,
2542                            self.method_name.unwrap().name,
2543                            None,
2544                        )
2545                    });
2546                Ok(best_name.and_then(|best_name| {
2547                    applicable_close_candidates
2548                        .into_iter()
2549                        .find(|method| method.name() == best_name)
2550                }))
2551            }
2552        })
2553    }
2554
2555    ///////////////////////////////////////////////////////////////////////////
2556    // MISCELLANY
2557    fn has_applicable_self(&self, item: &ty::AssocItem) -> bool {
2558        // "Fast track" -- check for usage of sugar when in method call
2559        // mode.
2560        //
2561        // In Path mode (i.e., resolving a value like `T::next`), consider any
2562        // associated value (i.e., methods, constants) but not types.
2563        match self.mode {
2564            Mode::MethodCall => item.is_method(),
2565            Mode::Path => match item.kind {
2566                ty::AssocKind::Type { .. } => false,
2567                ty::AssocKind::Fn { .. } | ty::AssocKind::Const { .. } => true,
2568            },
2569        }
2570        // FIXME -- check for types that deref to `Self`,
2571        // like `Rc<Self>` and so on.
2572        //
2573        // Note also that the current code will break if this type
2574        // includes any of the type parameters defined on the method
2575        // -- but this could be overcome.
2576    }
2577
2578    fn record_static_candidate(&self, source: CandidateSource) {
2579        self.static_candidates.borrow_mut().push(source);
2580    }
2581
2582    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("xform_self_ty",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2582u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: (Ty<'tcx>, Option<Ty<'tcx>>) =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if item.is_fn() && self.mode == Mode::MethodCall {
                let sig = self.xform_method_sig(item.def_id, args);
                (self.self_ty_override.unwrap_or(sig.inputs()[0]),
                    Some(sig.output()))
            } else { (impl_ty, None) }
        }
    }
}#[instrument(level = "debug", skip(self))]
2583    fn xform_self_ty(
2584        &self,
2585        item: ty::AssocItem,
2586        impl_ty: Ty<'tcx>,
2587        args: GenericArgsRef<'tcx>,
2588    ) -> (Ty<'tcx>, Option<Ty<'tcx>>) {
2589        if item.is_fn() && self.mode == Mode::MethodCall {
2590            let sig = self.xform_method_sig(item.def_id, args);
2591            (self.self_ty_override.unwrap_or(sig.inputs()[0]), Some(sig.output()))
2592        } else {
2593            (impl_ty, None)
2594        }
2595    }
2596
2597    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("xform_method_sig",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2597u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("method")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("method");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::FnSig<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let fn_sig = self.tcx.fn_sig(method);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/probe.rs:2600",
                                    "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2600u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_sig");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if !!args.has_escaping_bound_vars() {
                ::core::panicking::panic("assertion failed: !args.has_escaping_bound_vars()")
            };
            let generics = self.tcx.generics_of(method);
            {
                match (&args.len(), &generics.parent_count) {
                    (left_val, right_val) => {
                        if !(*left_val == *right_val) {
                            let kind = ::core::panicking::AssertKind::Eq;
                            ::core::panicking::assert_failed(kind, &*left_val,
                                &*right_val, ::core::option::Option::None);
                        }
                    }
                }
            };
            let xform_fn_sig =
                if generics.is_own_empty() {
                    fn_sig.instantiate(self.tcx, args).skip_norm_wip()
                } else {
                    let args =
                        GenericArgs::for_item(self.tcx, method,
                            |param, _|
                                {
                                    let i = param.index as usize;
                                    if i < args.len() {
                                        args[i]
                                    } else {
                                        match param.kind {
                                            GenericParamDefKind::Lifetime => {
                                                self.tcx.lifetimes.re_erased.into()
                                            }
                                            GenericParamDefKind::Type { .. } |
                                                GenericParamDefKind::Const { .. } => {
                                                self.var_for_def(self.span, param)
                                            }
                                        }
                                    }
                                });
                    fn_sig.instantiate(self.tcx, args).skip_norm_wip()
                };
            self.tcx.instantiate_bound_regions_with_erased(xform_fn_sig)
        }
    }
}#[instrument(level = "debug", skip(self))]
2598    fn xform_method_sig(&self, method: DefId, args: GenericArgsRef<'tcx>) -> ty::FnSig<'tcx> {
2599        let fn_sig = self.tcx.fn_sig(method);
2600        debug!(?fn_sig);
2601
2602        assert!(!args.has_escaping_bound_vars());
2603
2604        // It is possible for type parameters or early-bound lifetimes
2605        // to appear in the signature of `self`. The generic parameters
2606        // we are given do not include type/lifetime parameters for the
2607        // method yet. So create fresh variables here for those too,
2608        // if there are any.
2609        let generics = self.tcx.generics_of(method);
2610        assert_eq!(args.len(), generics.parent_count);
2611
2612        let xform_fn_sig = if generics.is_own_empty() {
2613            fn_sig.instantiate(self.tcx, args).skip_norm_wip()
2614        } else {
2615            let args = GenericArgs::for_item(self.tcx, method, |param, _| {
2616                let i = param.index as usize;
2617                if i < args.len() {
2618                    args[i]
2619                } else {
2620                    match param.kind {
2621                        GenericParamDefKind::Lifetime => {
2622                            // In general, during probe we erase regions.
2623                            self.tcx.lifetimes.re_erased.into()
2624                        }
2625                        GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
2626                            self.var_for_def(self.span, param)
2627                        }
2628                    }
2629                }
2630            });
2631            fn_sig.instantiate(self.tcx, args).skip_norm_wip()
2632        };
2633
2634        self.tcx.instantiate_bound_regions_with_erased(xform_fn_sig)
2635    }
2636
2637    /// Determine if the given associated item type is relevant in the current context.
2638    fn is_relevant_kind_for_mode(&self, kind: ty::AssocKind) -> bool {
2639        match (self.mode, kind) {
2640            (Mode::MethodCall, ty::AssocKind::Fn { .. }) => true,
2641            (Mode::Path, ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. }) => true,
2642            _ => false,
2643        }
2644    }
2645
2646    /// Determine if the associated item with the given DefId matches
2647    /// the desired name via a doc alias or rustc_confusables
2648    fn matches_by_doc_alias(&self, def_id: DefId) -> bool {
2649        let Some(method) = self.method_name else {
2650            return false;
2651        };
2652
2653        if let Some(d) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(Doc(d)) => {
                        break 'done Some(d);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, def_id, Doc(d) => d)
2654            && d.aliases.contains_key(&method.name)
2655        {
2656            return true;
2657        }
2658
2659        if let Some(confusables) =
2660            {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcConfusables {
                        confusables }) => {
                        break 'done Some(confusables);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, def_id, RustcConfusables{ confusables } => confusables)
2661            && confusables.contains(&method.name)
2662        {
2663            return true;
2664        }
2665
2666        false
2667    }
2668
2669    /// Finds the method with the appropriate name (or return type, as the case may be). If
2670    /// `allow_similar_names` is set, find methods with close-matching names.
2671    // The length of the returned iterator is nearly always 0 or 1 and this
2672    // method is fairly hot.
2673    fn impl_or_trait_item(&self, def_id: DefId) -> SmallVec<[ty::AssocItem; 1]> {
2674        if let Some(name) = self.method_name {
2675            if self.allow_similar_names {
2676                let max_dist = max(name.as_str().len(), 3) / 3;
2677                self.tcx
2678                    .associated_items(def_id)
2679                    .in_definition_order()
2680                    .filter(|x| {
2681                        if !self.is_relevant_kind_for_mode(x.kind) {
2682                            return false;
2683                        }
2684                        if let Some(d) = edit_distance_with_substrings(
2685                            name.as_str(),
2686                            x.name().as_str(),
2687                            max_dist,
2688                        ) {
2689                            return d > 0;
2690                        }
2691                        self.matches_by_doc_alias(x.def_id)
2692                    })
2693                    .copied()
2694                    .collect()
2695            } else {
2696                self.fcx
2697                    .associated_value(def_id, name)
2698                    .filter(|x| self.is_relevant_kind_for_mode(x.kind))
2699                    .map_or_else(SmallVec::new, |x| SmallVec::from_buf([x]))
2700            }
2701        } else {
2702            self.tcx
2703                .associated_items(def_id)
2704                .in_definition_order()
2705                .filter(|x| self.is_relevant_kind_for_mode(x.kind))
2706                .copied()
2707                .collect()
2708        }
2709    }
2710}
2711
2712impl<'tcx> Candidate<'tcx> {
2713    fn to_unadjusted_pick(
2714        &self,
2715        self_ty: Ty<'tcx>,
2716        unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
2717    ) -> Pick<'tcx> {
2718        Pick {
2719            item: self.item,
2720            kind: match self.kind {
2721                InherentImplCandidate { .. } => InherentImplPick,
2722                ObjectCandidate(_) => ObjectPick,
2723                TraitCandidate(_, lint_ambiguous) => TraitPick(lint_ambiguous),
2724                WhereClauseCandidate(trait_ref) => {
2725                    // Only trait derived from where-clauses should
2726                    // appear here, so they should not contain any
2727                    // inference variables or other artifacts. This
2728                    // means they are safe to put into the
2729                    // `WhereClausePick`.
2730                    if !(!trait_ref.skip_binder().args.has_infer() &&
            !trait_ref.skip_binder().args.has_placeholders()) {
    ::core::panicking::panic("assertion failed: !trait_ref.skip_binder().args.has_infer() &&\n    !trait_ref.skip_binder().args.has_placeholders()")
};assert!(
2731                        !trait_ref.skip_binder().args.has_infer()
2732                            && !trait_ref.skip_binder().args.has_placeholders()
2733                    );
2734
2735                    WhereClausePick(trait_ref)
2736                }
2737            },
2738            import_ids: self.import_ids,
2739            autoderefs: 0,
2740            autoref_or_ptr_adjustment: None,
2741            self_ty,
2742            unstable_candidates,
2743            receiver_steps: match self.kind {
2744                InherentImplCandidate { receiver_steps, .. } => Some(receiver_steps),
2745                _ => None,
2746            },
2747            shadowed_candidates: ::alloc::vec::Vec::new()vec![],
2748        }
2749    }
2750}