rustc_hir_typeck/method/
probe.rs

1use std::cell::{Cell, RefCell};
2use std::cmp::max;
3use std::ops::Deref;
4
5use rustc_data_structures::debug_assert_matches;
6use rustc_data_structures::fx::FxHashSet;
7use rustc_data_structures::sso::SsoHashSet;
8use rustc_errors::Applicability;
9use rustc_hir::attrs::AttributeKind;
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_middle::middle::stability;
17use rustc_middle::ty::elaborate::supertrait_def_ids;
18use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type};
19use rustc_middle::ty::{
20    self, AssocContainer, AssocItem, GenericArgs, GenericArgsRef, GenericParamDefKind, ParamEnvAnd,
21    Ty, TyCtxt, TypeVisitableExt, Upcast,
22};
23use rustc_middle::{bug, span_bug};
24use rustc_session::lint;
25use rustc_span::def_id::{DefId, LocalDefId};
26use rustc_span::edit_distance::{
27    edit_distance_with_substrings, find_best_match_for_name_with_substrings,
28};
29use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
30use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
31use rustc_trait_selection::infer::InferCtxtExt as _;
32use rustc_trait_selection::solve::Goal;
33use rustc_trait_selection::traits::query::CanonicalMethodAutoderefStepsGoal;
34use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
35use rustc_trait_selection::traits::query::method_autoderef::{
36    CandidateStep, MethodAutoderefBadTy, MethodAutoderefStepsResult,
37};
38use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt};
39use smallvec::{SmallVec, smallvec};
40use tracing::{debug, instrument};
41
42use self::CandidateKind::*;
43pub(crate) use self::PickKind::*;
44use super::{CandidateSource, MethodError, NoMatchData, suggest};
45use crate::FnCtxt;
46
47/// Boolean flag used to indicate if this search is for a suggestion
48/// or not. If true, we can allow ambiguity and so forth.
49#[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)]
50pub(crate) struct IsSuggestion(pub bool);
51
52pub(crate) struct ProbeContext<'a, 'tcx> {
53    fcx: &'a FnCtxt<'a, 'tcx>,
54    span: Span,
55    mode: Mode,
56    method_name: Option<Ident>,
57    return_type: Option<Ty<'tcx>>,
58
59    /// This is the OriginalQueryValues for the steps queries
60    /// that are answered in steps.
61    orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
62    steps: &'tcx [CandidateStep<'tcx>],
63
64    inherent_candidates: Vec<Candidate<'tcx>>,
65    extension_candidates: Vec<Candidate<'tcx>>,
66    impl_dups: FxHashSet<DefId>,
67
68    /// When probing for names, include names that are close to the
69    /// requested name (by edit distance)
70    allow_similar_names: bool,
71
72    /// List of potential private candidates. Will be trimmed to ones that
73    /// actually apply and then the result inserted into `private_candidate`
74    private_candidates: Vec<Candidate<'tcx>>,
75
76    /// Some(candidate) if there is a private candidate
77    private_candidate: Cell<Option<(DefKind, DefId)>>,
78
79    /// Collects near misses when the candidate functions are missing a `self` keyword and is only
80    /// used for error reporting
81    static_candidates: RefCell<Vec<CandidateSource>>,
82
83    scope_expr_id: HirId,
84
85    /// Is this probe being done for a diagnostic? This will skip some error reporting
86    /// machinery, since we don't particularly care about, for example, similarly named
87    /// candidates if we're *reporting* similarly named candidates.
88    is_suggestion: IsSuggestion,
89}
90
91impl<'a, 'tcx> Deref for ProbeContext<'a, 'tcx> {
92    type Target = FnCtxt<'a, 'tcx>;
93    fn deref(&self) -> &Self::Target {
94        self.fcx
95    }
96}
97
98#[derive(#[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)]
99pub(crate) struct Candidate<'tcx> {
100    pub(crate) item: ty::AssocItem,
101    pub(crate) kind: CandidateKind<'tcx>,
102    pub(crate) import_ids: SmallVec<[LocalDefId; 1]>,
103}
104
105#[derive(#[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)]
106pub(crate) enum CandidateKind<'tcx> {
107    InherentImplCandidate { impl_def_id: DefId, receiver_steps: usize },
108    ObjectCandidate(ty::PolyTraitRef<'tcx>),
109    TraitCandidate(ty::PolyTraitRef<'tcx>, bool /* lint_ambiguous */),
110    WhereClauseCandidate(ty::PolyTraitRef<'tcx>),
111}
112
113#[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_receiver_is_total_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)]
114enum ProbeResult {
115    NoMatch,
116    BadReturnType,
117    Match,
118}
119
120/// When adjusting a receiver we often want to do one of
121///
122/// - Add a `&` (or `&mut`), converting the receiver from `T` to `&T` (or `&mut T`)
123/// - If the receiver has type `*mut T`, convert it to `*const T`
124///
125/// This type tells us which one to do.
126///
127/// Note that in principle we could do both at the same time. For example, when the receiver has
128/// type `T`, we could autoref it to `&T`, then convert to `*const T`. Or, when it has type `*mut
129/// T`, we could convert it to `*const T`, then autoref to `&*const T`. However, currently we do
130/// (at most) one of these. Either the receiver has type `T` and we convert it to `&T` (or with
131/// `mut`), or it has type `*mut T` and we convert it to `*const T`.
132#[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)]
133pub(crate) enum AutorefOrPtrAdjustment {
134    /// Receiver has type `T`, add `&` or `&mut` (if `T` is `mut`), and maybe also "unsize" it.
135    /// Unsizing is used to convert a `[T; N]` to `[T]`, which only makes sense when autorefing.
136    Autoref {
137        mutbl: hir::Mutability,
138
139        /// Indicates that the source expression should be "unsized" to a target type.
140        /// This is special-cased for just arrays unsizing to slices.
141        unsize: bool,
142    },
143    /// Receiver has type `*mut T`, convert to `*const T`
144    ToConstPtr,
145
146    /// Reborrow a `Pin<&mut T>` or `Pin<&T>`.
147    ReborrowPin(hir::Mutability),
148}
149
150impl AutorefOrPtrAdjustment {
151    fn get_unsize(&self) -> bool {
152        match self {
153            AutorefOrPtrAdjustment::Autoref { mutbl: _, unsize } => *unsize,
154            AutorefOrPtrAdjustment::ToConstPtr => false,
155            AutorefOrPtrAdjustment::ReborrowPin(_) => false,
156        }
157    }
158}
159
160/// Extra information required only for error reporting.
161#[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)]
162struct PickDiagHints<'a, 'tcx> {
163    /// Unstable candidates alongside the stable ones.
164    unstable_candidates: Option<Vec<(Candidate<'tcx>, Symbol)>>,
165
166    /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
167    /// for error reporting
168    unsatisfied_predicates: &'a mut UnsatisfiedPredicates<'tcx>,
169}
170
171pub(crate) type UnsatisfiedPredicates<'tcx> =
172    Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>;
173
174/// Criteria to apply when searching for a given Pick. This is used during
175/// the search for potentially shadowed methods to ensure we don't search
176/// more candidates than strictly necessary.
177#[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)]
178struct PickConstraintsForShadowed {
179    autoderefs: usize,
180    receiver_steps: Option<usize>,
181    def_id: DefId,
182}
183
184impl PickConstraintsForShadowed {
185    fn may_shadow_based_on_autoderefs(&self, autoderefs: usize) -> bool {
186        autoderefs == self.autoderefs
187    }
188
189    fn candidate_may_shadow(&self, candidate: &Candidate<'_>) -> bool {
190        // An item never shadows itself
191        candidate.item.def_id != self.def_id
192            // and we're only concerned about inherent impls doing the shadowing.
193            // Shadowing can only occur if the impl being shadowed is further along
194            // the Receiver dereferencing chain than the impl doing the shadowing.
195            && match candidate.kind {
196                CandidateKind::InherentImplCandidate { receiver_steps, .. } => match self.receiver_steps {
197                    Some(shadowed_receiver_steps) => receiver_steps > shadowed_receiver_steps,
198                    _ => false
199                },
200                _ => false
201            }
202    }
203}
204
205#[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)]
206pub(crate) struct Pick<'tcx> {
207    pub item: ty::AssocItem,
208    pub kind: PickKind<'tcx>,
209    pub import_ids: SmallVec<[LocalDefId; 1]>,
210
211    /// Indicates that the source expression should be autoderef'd N times
212    /// ```ignore (not-rust)
213    /// A = expr | *expr | **expr | ...
214    /// ```
215    pub autoderefs: usize,
216
217    /// Indicates that we want to add an autoref (and maybe also unsize it), or if the receiver is
218    /// `*mut T`, convert it to `*const T`.
219    pub autoref_or_ptr_adjustment: Option<AutorefOrPtrAdjustment>,
220    pub self_ty: Ty<'tcx>,
221
222    /// Unstable candidates alongside the stable ones.
223    unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
224
225    /// Number of jumps along the `Receiver::Target` chain we followed
226    /// to identify this method. Used only for deshadowing errors.
227    /// Only applies for inherent impls.
228    pub receiver_steps: Option<usize>,
229
230    /// Candidates that were shadowed by supertraits.
231    pub shadowed_candidates: Vec<ty::AssocItem>,
232}
233
234#[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_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<ty::PolyTraitRef<'tcx>>;
    }
}Eq)]
235pub(crate) enum PickKind<'tcx> {
236    InherentImplPick,
237    ObjectPick,
238    TraitPick(
239        // Is Ambiguously Imported
240        bool,
241    ),
242    WhereClausePick(
243        // Trait
244        ty::PolyTraitRef<'tcx>,
245    ),
246}
247
248pub(crate) type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
249
250#[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_receiver_is_total_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)]
251pub(crate) enum Mode {
252    // An expression of the form `receiver.method_name(...)`.
253    // Autoderefs are performed on `receiver`, lookup is done based on the
254    // `self` argument of the method, and static methods aren't considered.
255    MethodCall,
256    // An expression of the form `Type::item` or `<T>::item`.
257    // No autoderefs are performed, lookup is done based on the type each
258    // implementation is for, and static methods are included.
259    Path,
260}
261
262#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for ProbeScope {
    #[inline]
    fn eq(&self, other: &ProbeScope) -> 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), ProbeScope::Single(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ProbeScope {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<DefId>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::Copy for ProbeScope { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ProbeScope {
    #[inline]
    fn clone(&self) -> ProbeScope {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ProbeScope {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ProbeScope::Single(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Single",
                    &__self_0),
            ProbeScope::TraitsInScope =>
                ::core::fmt::Formatter::write_str(f, "TraitsInScope"),
            ProbeScope::AllTraits =>
                ::core::fmt::Formatter::write_str(f, "AllTraits"),
        }
    }
}Debug)]
263pub(crate) enum ProbeScope {
264    // Single candidate coming from pre-resolved delegation method.
265    Single(DefId),
266
267    // Assemble candidates coming only from traits in scope.
268    TraitsInScope,
269
270    // Assemble candidates coming from all traits.
271    AllTraits,
272}
273
274impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
275    /// This is used to offer suggestions to users. It returns methods
276    /// that could have been called which have the desired return
277    /// type. Some effort is made to rule out methods that, if called,
278    /// would result in an error (basically, the same criteria we
279    /// would use to decide if a method is a plausible fit for
280    /// ambiguity purposes).
281    #[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(281u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["span", "mode",
                                                    "return_type", "self_ty", "scope_expr_id"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&return_type)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope_expr_id)
                                                            as &dyn 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))]
282    pub(crate) fn probe_for_return_type_for_diagnostic(
283        &self,
284        span: Span,
285        mode: Mode,
286        return_type: Ty<'tcx>,
287        self_ty: Ty<'tcx>,
288        scope_expr_id: HirId,
289        candidate_filter: impl Fn(&ty::AssocItem) -> bool,
290    ) -> Vec<ty::AssocItem> {
291        let method_names = self
292            .probe_op(
293                span,
294                mode,
295                None,
296                Some(return_type),
297                IsSuggestion(true),
298                self_ty,
299                scope_expr_id,
300                ProbeScope::AllTraits,
301                |probe_cx| Ok(probe_cx.candidate_method_names(candidate_filter)),
302            )
303            .unwrap_or_default();
304        method_names
305            .iter()
306            .flat_map(|&method_name| {
307                self.probe_op(
308                    span,
309                    mode,
310                    Some(method_name),
311                    Some(return_type),
312                    IsSuggestion(true),
313                    self_ty,
314                    scope_expr_id,
315                    ProbeScope::AllTraits,
316                    |probe_cx| probe_cx.pick(),
317                )
318                .ok()
319                .map(|pick| pick.item)
320            })
321            .collect()
322    }
323
324    #[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(324u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["mode", "item_name",
                                                    "return_type", "is_suggestion", "self_ty", "scope_expr_id",
                                                    "scope"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&return_type)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_suggestion)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope_expr_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope)
                                                            as &dyn 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))]
325    pub(crate) fn probe_for_name(
326        &self,
327        mode: Mode,
328        item_name: Ident,
329        return_type: Option<Ty<'tcx>>,
330        is_suggestion: IsSuggestion,
331        self_ty: Ty<'tcx>,
332        scope_expr_id: HirId,
333        scope: ProbeScope,
334    ) -> PickResult<'tcx> {
335        self.probe_op(
336            item_name.span,
337            mode,
338            Some(item_name),
339            return_type,
340            is_suggestion,
341            self_ty,
342            scope_expr_id,
343            scope,
344            |probe_cx| probe_cx.pick(),
345        )
346    }
347
348    #[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(348u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["mode", "item_name",
                                                    "return_type", "is_suggestion", "self_ty", "scope_expr_id",
                                                    "scope"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&return_type)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_suggestion)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope_expr_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope)
                                                            as &dyn 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))]
349    pub(crate) fn probe_for_name_many(
350        &self,
351        mode: Mode,
352        item_name: Ident,
353        return_type: Option<Ty<'tcx>>,
354        is_suggestion: IsSuggestion,
355        self_ty: Ty<'tcx>,
356        scope_expr_id: HirId,
357        scope: ProbeScope,
358    ) -> Result<Vec<Candidate<'tcx>>, MethodError<'tcx>> {
359        self.probe_op(
360            item_name.span,
361            mode,
362            Some(item_name),
363            return_type,
364            is_suggestion,
365            self_ty,
366            scope_expr_id,
367            scope,
368            |probe_cx| {
369                Ok(probe_cx
370                    .inherent_candidates
371                    .into_iter()
372                    .chain(probe_cx.extension_candidates)
373                    .collect())
374            },
375        )
376    }
377
378    pub(crate) fn probe_op<OP, R>(
379        &'a self,
380        span: Span,
381        mode: Mode,
382        method_name: Option<Ident>,
383        return_type: Option<Ty<'tcx>>,
384        is_suggestion: IsSuggestion,
385        self_ty: Ty<'tcx>,
386        scope_expr_id: HirId,
387        scope: ProbeScope,
388        op: OP,
389    ) -> Result<R, MethodError<'tcx>>
390    where
391        OP: FnOnce(ProbeContext<'_, 'tcx>) -> Result<R, MethodError<'tcx>>,
392    {
393        let mut orig_values = OriginalQueryValues::default();
394        let predefined_opaques_in_body = if self.next_trait_solver() {
395            self.tcx.mk_predefined_opaques_in_body_from_iter(
396                self.inner.borrow_mut().opaque_types().iter_opaque_types().map(|(k, v)| (k, v.ty)),
397            )
398        } else {
399            ty::List::empty()
400        };
401        let value = query::MethodAutoderefSteps { predefined_opaques_in_body, self_ty };
402        let query_input = self
403            .canonicalize_query(ParamEnvAnd { param_env: self.param_env, value }, &mut orig_values);
404
405        let steps = match mode {
406            Mode::MethodCall => self.tcx.method_autoderef_steps(query_input),
407            Mode::Path => self.probe(|_| {
408                // Mode::Path - the deref steps is "trivial". This turns
409                // our CanonicalQuery into a "trivial" QueryResponse. This
410                // is a bit inefficient, but I don't think that writing
411                // special handling for this "trivial case" is a good idea.
412
413                let infcx = &self.infcx;
414                let (ParamEnvAnd { param_env: _, value }, var_values) =
415                    infcx.instantiate_canonical(span, &query_input.canonical);
416                let query::MethodAutoderefSteps { predefined_opaques_in_body: _, self_ty } = value;
417                {
    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:417",
                        "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(417u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message", "self_ty",
                                        "query_input"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("probe_op: Mode::Path")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&self_ty) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&query_input)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?self_ty, ?query_input, "probe_op: Mode::Path");
418                MethodAutoderefStepsResult {
419                    steps: infcx.tcx.arena.alloc_from_iter([CandidateStep {
420                        self_ty: self
421                            .make_query_response_ignoring_pending_obligations(var_values, self_ty),
422                        self_ty_is_opaque: false,
423                        autoderefs: 0,
424                        from_unsafe_deref: false,
425                        unsize: false,
426                        reachable_via_deref: true,
427                    }]),
428                    opt_bad_ty: None,
429                    reached_recursion_limit: false,
430                }
431            }),
432        };
433
434        // If our autoderef loop had reached the recursion limit,
435        // report an overflow error, but continue going on with
436        // the truncated autoderef list.
437        if steps.reached_recursion_limit && !is_suggestion.0 {
438            self.probe(|_| {
439                let ty = &steps
440                    .steps
441                    .last()
442                    .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?"))
443                    .self_ty;
444                let ty = self
445                    .probe_instantiate_query_response(span, &orig_values, ty)
446                    .unwrap_or_else(|_| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("instantiating {0:?} failed?", ty))span_bug!(span, "instantiating {:?} failed?", ty));
447                autoderef::report_autoderef_recursion_limit_error(self.tcx, span, ty.value);
448            });
449        }
450
451        // If we encountered an `_` type or an error type during autoderef, this is
452        // ambiguous.
453        if let Some(bad_ty) = &steps.opt_bad_ty {
454            if is_suggestion.0 {
455                // Ambiguity was encountered during a suggestion. There's really
456                // not much use in suggesting methods in this case.
457                return Err(MethodError::NoMatch(NoMatchData {
458                    static_candidates: Vec::new(),
459                    unsatisfied_predicates: Vec::new(),
460                    out_of_scope_traits: Vec::new(),
461                    similar_candidate: None,
462                    mode,
463                }));
464            } else if bad_ty.reached_raw_pointer
465                && !self.tcx.features().arbitrary_self_types_pointers()
466                && !self.tcx.sess.at_least_rust_2018()
467            {
468                // this case used to be allowed by the compiler,
469                // so we do a future-compat lint here for the 2015 edition
470                // (see https://github.com/rust-lang/rust/issues/46906)
471                self.tcx.node_span_lint(
472                    lint::builtin::TYVAR_BEHIND_RAW_POINTER,
473                    scope_expr_id,
474                    span,
475                    |lint| {
476                        lint.primary_message("type annotations needed");
477                    },
478                );
479            } else {
480                // Ended up encountering a type variable when doing autoderef,
481                // but it may not be a type variable after processing obligations
482                // in our local `FnCtxt`, so don't call `structurally_resolve_type`.
483                let ty = &bad_ty.ty;
484                let ty = self
485                    .probe_instantiate_query_response(span, &orig_values, ty)
486                    .unwrap_or_else(|_| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("instantiating {0:?} failed?", ty))span_bug!(span, "instantiating {:?} failed?", ty));
487                let ty = self.resolve_vars_if_possible(ty.value);
488                let guar = match *ty.kind() {
489                    ty::Infer(ty::TyVar(_)) => {
490                        // We want to get the variable name that the method
491                        // is being called on. If it is a method call.
492                        let err_span = match (mode, self.tcx.hir_node(scope_expr_id)) {
493                            (
494                                Mode::MethodCall,
495                                Node::Expr(hir::Expr {
496                                    kind: ExprKind::MethodCall(_, recv, ..),
497                                    ..
498                                }),
499                            ) => recv.span,
500                            _ => span,
501                        };
502
503                        let raw_ptr_call = bad_ty.reached_raw_pointer
504                            && !self.tcx.features().arbitrary_self_types();
505
506                        let mut err = self.err_ctxt().emit_inference_failure_err(
507                            self.body_id,
508                            err_span,
509                            ty.into(),
510                            TypeAnnotationNeeded::E0282,
511                            !raw_ptr_call,
512                        );
513                        if raw_ptr_call {
514                            err.span_label(span, "cannot call a method on a raw pointer with an unknown pointee type");
515                        }
516                        err.emit()
517                    }
518                    ty::Error(guar) => guar,
519                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bad final type in method autoderef"))bug!("unexpected bad final type in method autoderef"),
520                };
521                self.demand_eqtype(span, ty, Ty::new_error(self.tcx, guar));
522                return Err(MethodError::ErrorReported(guar));
523            }
524        }
525
526        {
    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:526",
                        "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(526u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ProbeContext: steps for self_ty={0:?} are {1:?}",
                                                    self_ty, steps) as &dyn Value))])
            });
    } else { ; }
};debug!("ProbeContext: steps for self_ty={:?} are {:?}", self_ty, steps);
527
528        // this creates one big transaction so that all type variables etc
529        // that we create during the probe process are removed later
530        self.probe(|_| {
531            let mut probe_cx = ProbeContext::new(
532                self,
533                span,
534                mode,
535                method_name,
536                return_type,
537                &orig_values,
538                steps.steps,
539                scope_expr_id,
540                is_suggestion,
541            );
542
543            match scope {
544                ProbeScope::TraitsInScope => {
545                    probe_cx.assemble_inherent_candidates();
546                    probe_cx.assemble_extension_candidates_for_traits_in_scope();
547                }
548                ProbeScope::AllTraits => {
549                    probe_cx.assemble_inherent_candidates();
550                    probe_cx.assemble_extension_candidates_for_all_traits();
551                }
552                ProbeScope::Single(def_id) => {
553                    let item = self.tcx.associated_item(def_id);
554                    // FIXME(fn_delegation): Delegation to inherent methods is not yet supported.
555                    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);
556
557                    let trait_def_id = self.tcx.parent(def_id);
558                    let trait_span = self.tcx.def_span(trait_def_id);
559
560                    let trait_args = self.fresh_args_for_item(trait_span, trait_def_id);
561                    let trait_ref = ty::TraitRef::new_from_args(self.tcx, trait_def_id, trait_args);
562
563                    probe_cx.push_candidate(
564                        Candidate {
565                            item,
566                            kind: CandidateKind::TraitCandidate(
567                                ty::Binder::dummy(trait_ref),
568                                false,
569                            ),
570                            import_ids: ::smallvec::SmallVec::new()smallvec![],
571                        },
572                        false,
573                    );
574                }
575            };
576            op(probe_cx)
577        })
578    }
579}
580
581pub(crate) fn method_autoderef_steps<'tcx>(
582    tcx: TyCtxt<'tcx>,
583    goal: CanonicalMethodAutoderefStepsGoal<'tcx>,
584) -> MethodAutoderefStepsResult<'tcx> {
585    {
    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:585",
                        "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(585u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("method_autoderef_steps({0:?})",
                                                    goal) as &dyn Value))])
            });
    } else { ; }
};debug!("method_autoderef_steps({:?})", goal);
586
587    let (ref infcx, goal, inference_vars) = tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &goal);
588    let ParamEnvAnd {
589        param_env,
590        value: query::MethodAutoderefSteps { predefined_opaques_in_body, self_ty },
591    } = goal;
592    for (key, ty) in predefined_opaques_in_body {
593        let prev = infcx
594            .register_hidden_type_in_storage(key, ty::ProvisionalHiddenType { span: DUMMY_SP, ty });
595        // It may be possible that two entries in the opaque type storage end up
596        // with the same key after resolving contained inference variables.
597        //
598        // We could put them in the duplicate list but don't have to. The opaques we
599        // encounter here are already tracked in the caller, so there's no need to
600        // also store them here. We'd take them out when computing the query response
601        // and then discard them, as they're already present in the input.
602        //
603        // Ideally we'd drop duplicate opaque type definitions when computing
604        // the canonical input. This is more annoying to implement and may cause a
605        // perf regression, so we do it inside of the query for now.
606        if let Some(prev) = prev {
607            {
    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:607",
                        "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(607u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message", "key",
                                        "ty", "prev"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ignore duplicate in `opaque_types_storage`")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&key) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&ty) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&prev) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?key, ?ty, ?prev, "ignore duplicate in `opaque_types_storage`");
608        }
609    }
610
611    // We accept not-yet-defined opaque types in the autoderef
612    // chain to support recursive calls. We do error if the final
613    // infer var is not an opaque.
614    let self_ty_is_opaque = |ty: Ty<'_>| {
615        if let &ty::Infer(ty::TyVar(vid)) = ty.kind() {
616            infcx.has_opaques_with_sub_unified_hidden_type(vid)
617        } else {
618            false
619        }
620    };
621
622    // If arbitrary self types is not enabled, we follow the chain of
623    // `Deref<Target=T>`. If arbitrary self types is enabled, we instead
624    // follow the chain of `Receiver<Target=T>`, but we also record whether
625    // such types are reachable by following the (potentially shorter)
626    // chain of `Deref<Target=T>`. We will use the first list when finding
627    // potentially relevant function implementations (e.g. relevant impl blocks)
628    // but the second list when determining types that the receiver may be
629    // converted to, in order to find out which of those methods might actually
630    // be callable.
631    let mut autoderef_via_deref =
632        Autoderef::new(infcx, param_env, hir::def_id::CRATE_DEF_ID, DUMMY_SP, self_ty)
633            .include_raw_pointers()
634            .silence_errors();
635
636    let mut reached_raw_pointer = false;
637    let arbitrary_self_types_enabled =
638        tcx.features().arbitrary_self_types() || tcx.features().arbitrary_self_types_pointers();
639    let (mut steps, reached_recursion_limit): (Vec<_>, bool) = if arbitrary_self_types_enabled {
640        let reachable_via_deref =
641            autoderef_via_deref.by_ref().map(|_| true).chain(std::iter::repeat(false));
642
643        let mut autoderef_via_receiver =
644            Autoderef::new(infcx, param_env, hir::def_id::CRATE_DEF_ID, DUMMY_SP, self_ty)
645                .include_raw_pointers()
646                .use_receiver_trait()
647                .silence_errors();
648        let steps = autoderef_via_receiver
649            .by_ref()
650            .zip(reachable_via_deref)
651            .map(|((ty, d), reachable_via_deref)| {
652                let step = CandidateStep {
653                    self_ty: infcx
654                        .make_query_response_ignoring_pending_obligations(inference_vars, ty),
655                    self_ty_is_opaque: self_ty_is_opaque(ty),
656                    autoderefs: d,
657                    from_unsafe_deref: reached_raw_pointer,
658                    unsize: false,
659                    reachable_via_deref,
660                };
661                if ty.is_raw_ptr() {
662                    // all the subsequent steps will be from_unsafe_deref
663                    reached_raw_pointer = true;
664                }
665                step
666            })
667            .collect();
668        (steps, autoderef_via_receiver.reached_recursion_limit())
669    } else {
670        let steps = autoderef_via_deref
671            .by_ref()
672            .map(|(ty, d)| {
673                let step = CandidateStep {
674                    self_ty: infcx
675                        .make_query_response_ignoring_pending_obligations(inference_vars, ty),
676                    self_ty_is_opaque: self_ty_is_opaque(ty),
677                    autoderefs: d,
678                    from_unsafe_deref: reached_raw_pointer,
679                    unsize: false,
680                    reachable_via_deref: true,
681                };
682                if ty.is_raw_ptr() {
683                    // all the subsequent steps will be from_unsafe_deref
684                    reached_raw_pointer = true;
685                }
686                step
687            })
688            .collect();
689        (steps, autoderef_via_deref.reached_recursion_limit())
690    };
691    let final_ty = autoderef_via_deref.final_ty();
692    let opt_bad_ty = match final_ty.kind() {
693        ty::Infer(ty::TyVar(_)) if !self_ty_is_opaque(final_ty) => Some(MethodAutoderefBadTy {
694            reached_raw_pointer,
695            ty: infcx.make_query_response_ignoring_pending_obligations(inference_vars, final_ty),
696        }),
697        ty::Error(_) => Some(MethodAutoderefBadTy {
698            reached_raw_pointer,
699            ty: infcx.make_query_response_ignoring_pending_obligations(inference_vars, final_ty),
700        }),
701        ty::Array(elem_ty, _) => {
702            let autoderefs = steps.iter().filter(|s| s.reachable_via_deref).count() - 1;
703            steps.push(CandidateStep {
704                self_ty: infcx.make_query_response_ignoring_pending_obligations(
705                    inference_vars,
706                    Ty::new_slice(infcx.tcx, *elem_ty),
707                ),
708                self_ty_is_opaque: false,
709                autoderefs,
710                // this could be from an unsafe deref if we had
711                // a *mut/const [T; N]
712                from_unsafe_deref: reached_raw_pointer,
713                unsize: true,
714                reachable_via_deref: true, // this is always the final type from
715                                           // autoderef_via_deref
716            });
717
718            None
719        }
720        _ => None,
721    };
722
723    {
    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:723",
                        "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(723u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("method_autoderef_steps: steps={0:?} opt_bad_ty={1:?}",
                                                    steps, opt_bad_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
724    // Need to empty the opaque types storage before it gets dropped.
725    let _ = infcx.take_opaque_types();
726    MethodAutoderefStepsResult {
727        steps: tcx.arena.alloc_from_iter(steps),
728        opt_bad_ty: opt_bad_ty.map(|ty| &*tcx.arena.alloc(ty)),
729        reached_recursion_limit,
730    }
731}
732
733impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
734    fn new(
735        fcx: &'a FnCtxt<'a, 'tcx>,
736        span: Span,
737        mode: Mode,
738        method_name: Option<Ident>,
739        return_type: Option<Ty<'tcx>>,
740        orig_steps_var_values: &'a OriginalQueryValues<'tcx>,
741        steps: &'tcx [CandidateStep<'tcx>],
742        scope_expr_id: HirId,
743        is_suggestion: IsSuggestion,
744    ) -> ProbeContext<'a, 'tcx> {
745        ProbeContext {
746            fcx,
747            span,
748            mode,
749            method_name,
750            return_type,
751            inherent_candidates: Vec::new(),
752            extension_candidates: Vec::new(),
753            impl_dups: FxHashSet::default(),
754            orig_steps_var_values,
755            steps,
756            allow_similar_names: false,
757            private_candidates: Vec::new(),
758            private_candidate: Cell::new(None),
759            static_candidates: RefCell::new(Vec::new()),
760            scope_expr_id,
761            is_suggestion,
762        }
763    }
764
765    fn reset(&mut self) {
766        self.inherent_candidates.clear();
767        self.extension_candidates.clear();
768        self.impl_dups.clear();
769        self.private_candidates.clear();
770        self.private_candidate.set(None);
771        self.static_candidates.borrow_mut().clear();
772    }
773
774    /// When we're looking up a method by path (UFCS), we relate the receiver
775    /// types invariantly. When we are looking up a method by the `.` operator,
776    /// we relate them covariantly.
777    fn variance(&self) -> ty::Variance {
778        match self.mode {
779            Mode::MethodCall => ty::Covariant,
780            Mode::Path => ty::Invariant,
781        }
782    }
783
784    ///////////////////////////////////////////////////////////////////////////
785    // CANDIDATE ASSEMBLY
786
787    fn push_candidate(&mut self, candidate: Candidate<'tcx>, is_inherent: bool) {
788        let is_accessible = if let Some(name) = self.method_name {
789            let item = candidate.item;
790            let hir_id = self.tcx.local_def_id_to_hir_id(self.body_id);
791            let def_scope =
792                self.tcx.adjust_ident_and_get_scope(name, item.container_id(self.tcx), hir_id).1;
793            item.visibility(self.tcx).is_accessible_from(def_scope, self.tcx)
794        } else {
795            true
796        };
797        if is_accessible {
798            if is_inherent {
799                self.inherent_candidates.push(candidate);
800            } else {
801                self.extension_candidates.push(candidate);
802            }
803        } else {
804            self.private_candidates.push(candidate);
805        }
806    }
807
808    fn assemble_inherent_candidates(&mut self) {
809        for step in self.steps.iter() {
810            self.assemble_probe(&step.self_ty, step.autoderefs);
811        }
812    }
813
814    #[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(814u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["self_ty",
                                                    "receiver_steps"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&receiver_steps as
                                                            &dyn 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)
                }
                _ => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
815    fn assemble_probe(
816        &mut self,
817        self_ty: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
818        receiver_steps: usize,
819    ) {
820        let raw_self_ty = self_ty.value.value;
821        match *raw_self_ty.kind() {
822            ty::Dynamic(data, ..) if let Some(p) = data.principal() => {
823                // Subtle: we can't use `instantiate_query_response` here: using it will
824                // commit to all of the type equalities assumed by inference going through
825                // autoderef (see the `method-probe-no-guessing` test).
826                //
827                // However, in this code, it is OK if we end up with an object type that is
828                // "more general" than the object type that we are evaluating. For *every*
829                // object type `MY_OBJECT`, a function call that goes through a trait-ref
830                // of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
831                // `ObjectCandidate`, and it should be discoverable "exactly" through one
832                // of the iterations in the autoderef loop, so there is no problem with it
833                // being discoverable in another one of these iterations.
834                //
835                // Using `instantiate_canonical` on our
836                // `Canonical<QueryResponse<Ty<'tcx>>>` and then *throwing away* the
837                // `CanonicalVarValues` will exactly give us such a generalization - it
838                // will still match the original object type, but it won't pollute our
839                // type variables in any form, so just do that!
840                let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
841                    self.fcx.instantiate_canonical(self.span, self_ty);
842
843                self.assemble_inherent_candidates_from_object(generalized_self_ty);
844                self.assemble_inherent_impl_candidates_for_type(p.def_id(), receiver_steps);
845                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
846            }
847            ty::Adt(def, _) => {
848                let def_id = def.did();
849                self.assemble_inherent_impl_candidates_for_type(def_id, receiver_steps);
850                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
851            }
852            ty::Foreign(did) => {
853                self.assemble_inherent_impl_candidates_for_type(did, receiver_steps);
854                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps);
855            }
856            ty::Param(_) => {
857                self.assemble_inherent_candidates_from_param(raw_self_ty);
858            }
859            ty::Bool
860            | ty::Char
861            | ty::Int(_)
862            | ty::Uint(_)
863            | ty::Float(_)
864            | ty::Str
865            | ty::Array(..)
866            | ty::Slice(_)
867            | ty::RawPtr(_, _)
868            | ty::Ref(..)
869            | ty::Never
870            | ty::Tuple(..) => {
871                self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty, receiver_steps)
872            }
873            _ => {}
874        }
875    }
876
877    fn assemble_inherent_candidates_for_incoherent_ty(
878        &mut self,
879        self_ty: Ty<'tcx>,
880        receiver_steps: usize,
881    ) {
882        let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::InstantiateWithInfer) else {
883            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected incoherent type: {0:?}",
        self_ty))bug!("unexpected incoherent type: {:?}", self_ty)
884        };
885        for &impl_def_id in self.tcx.incoherent_impls(simp).into_iter() {
886            self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
887        }
888    }
889
890    fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId, receiver_steps: usize) {
891        let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id).into_iter();
892        for &impl_def_id in impl_def_ids {
893            self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);
894        }
895    }
896
897    #[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(897u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["impl_def_id",
                                                    "receiver_steps"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&receiver_steps as
                                                            &dyn 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: ::smallvec::SmallVec::new(),
                    }, true);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
898    fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId, receiver_steps: usize) {
899        if !self.impl_dups.insert(impl_def_id) {
900            return; // already visited
901        }
902
903        for item in self.impl_or_trait_item(impl_def_id) {
904            if !self.has_applicable_self(&item) {
905                // No receiver declared. Not a candidate.
906                self.record_static_candidate(CandidateSource::Impl(impl_def_id));
907                continue;
908            }
909            self.push_candidate(
910                Candidate {
911                    item,
912                    kind: InherentImplCandidate { impl_def_id, receiver_steps },
913                    import_ids: smallvec![],
914                },
915                true,
916            );
917        }
918    }
919
920    #[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(920u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["self_ty"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn 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: ::smallvec::SmallVec::new(),
                            }, true);
                    });
        }
    }
}#[instrument(level = "debug", skip(self))]
921    fn assemble_inherent_candidates_from_object(&mut self, self_ty: Ty<'tcx>) {
922        let principal = match self_ty.kind() {
923            ty::Dynamic(data, ..) => Some(data),
924            _ => None,
925        }
926        .and_then(|data| data.principal())
927        .unwrap_or_else(|| {
928            span_bug!(
929                self.span,
930                "non-object {:?} in assemble_inherent_candidates_from_object",
931                self_ty
932            )
933        });
934
935        // It is illegal to invoke a method on a trait instance that refers to
936        // the `Self` type. An [`DynCompatibilityViolation::SupertraitSelf`] error
937        // will be reported by `dyn_compatibility.rs` if the method refers to the
938        // `Self` type anywhere other than the receiver. Here, we use a
939        // instantiation that replaces `Self` with the object type itself. Hence,
940        // a `&self` method will wind up with an argument type like `&dyn Trait`.
941        let trait_ref = principal.with_self_ty(self.tcx, self_ty);
942        self.assemble_candidates_for_bounds(
943            traits::supertraits(self.tcx, trait_ref),
944            |this, new_trait_ref, item| {
945                this.push_candidate(
946                    Candidate {
947                        item,
948                        kind: ObjectCandidate(new_trait_ref),
949                        import_ids: smallvec![],
950                    },
951                    true,
952                );
953            },
954        );
955    }
956
957    #[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(957u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["param_ty"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_ty)
                                                            as &dyn 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(|predicate|
                        {
                            let bound_predicate = predicate.kind();
                            match bound_predicate.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_predicate.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: ::smallvec::SmallVec::new(),
                            }, true);
                    });
        }
    }
}#[instrument(level = "debug", skip(self))]
958    fn assemble_inherent_candidates_from_param(&mut self, param_ty: Ty<'tcx>) {
959        debug_assert_matches!(param_ty.kind(), ty::Param(_));
960
961        let tcx = self.tcx;
962
963        // We use `DeepRejectCtxt` here which may return false positive on where clauses
964        // with alias self types. We need to later on reject these as inherent candidates
965        // in `consider_probe`.
966        let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| {
967            let bound_predicate = predicate.kind();
968            match bound_predicate.skip_binder() {
969                ty::ClauseKind::Trait(trait_predicate) => DeepRejectCtxt::relate_rigid_rigid(tcx)
970                    .types_may_unify(param_ty, trait_predicate.trait_ref.self_ty())
971                    .then(|| bound_predicate.rebind(trait_predicate.trait_ref)),
972                ty::ClauseKind::RegionOutlives(_)
973                | ty::ClauseKind::TypeOutlives(_)
974                | ty::ClauseKind::Projection(_)
975                | ty::ClauseKind::ConstArgHasType(_, _)
976                | ty::ClauseKind::WellFormed(_)
977                | ty::ClauseKind::ConstEvaluatable(_)
978                | ty::ClauseKind::UnstableFeature(_)
979                | ty::ClauseKind::HostEffect(..) => None,
980            }
981        });
982
983        self.assemble_candidates_for_bounds(bounds, |this, poly_trait_ref, item| {
984            this.push_candidate(
985                Candidate {
986                    item,
987                    kind: WhereClauseCandidate(poly_trait_ref),
988                    import_ids: smallvec![],
989                },
990                true,
991            );
992        });
993    }
994
995    // Do a search through a list of bounds, using a callback to actually
996    // create the candidates.
997    fn assemble_candidates_for_bounds<F>(
998        &mut self,
999        bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
1000        mut mk_cand: F,
1001    ) where
1002        F: for<'b> FnMut(&mut ProbeContext<'b, 'tcx>, ty::PolyTraitRef<'tcx>, ty::AssocItem),
1003    {
1004        for bound_trait_ref in bounds {
1005            {
    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:1005",
                        "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(1005u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("elaborate_bounds(bound_trait_ref={0:?})",
                                                    bound_trait_ref) as &dyn Value))])
            });
    } else { ; }
};debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
1006            for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
1007                if !self.has_applicable_self(&item) {
1008                    self.record_static_candidate(CandidateSource::Trait(bound_trait_ref.def_id()));
1009                } else {
1010                    mk_cand(self, bound_trait_ref, item);
1011                }
1012            }
1013        }
1014    }
1015
1016    #[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(1016u32),
                                    ::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(&[]) })
                } 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))]
1017    fn assemble_extension_candidates_for_traits_in_scope(&mut self) {
1018        let mut duplicates = FxHashSet::default();
1019        let opt_applicable_traits = self.tcx.in_scope_traits(self.scope_expr_id);
1020        if let Some(applicable_traits) = opt_applicable_traits {
1021            for trait_candidate in applicable_traits.iter() {
1022                let trait_did = trait_candidate.def_id;
1023                if duplicates.insert(trait_did) {
1024                    self.assemble_extension_candidates_for_trait(
1025                        &trait_candidate.import_ids,
1026                        trait_did,
1027                        trait_candidate.lint_ambiguous,
1028                    );
1029                }
1030            }
1031        }
1032    }
1033
1034    #[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(1034u32),
                                    ::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(&[]) })
                } 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(&::smallvec::SmallVec::new(),
                        trait_info.def_id, false);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1035    fn assemble_extension_candidates_for_all_traits(&mut self) {
1036        let mut duplicates = FxHashSet::default();
1037        for trait_info in suggest::all_traits(self.tcx) {
1038            if duplicates.insert(trait_info.def_id) {
1039                self.assemble_extension_candidates_for_trait(
1040                    &smallvec![],
1041                    trait_info.def_id,
1042                    false,
1043                );
1044            }
1045        }
1046    }
1047
1048    fn matches_return_type(&self, method: ty::AssocItem, expected: Ty<'tcx>) -> bool {
1049        match method.kind {
1050            ty::AssocKind::Fn { .. } => self.probe(|_| {
1051                let args = self.fresh_args_for_item(self.span, method.def_id);
1052                let fty = self.tcx.fn_sig(method.def_id).instantiate(self.tcx, args);
1053                let fty = self.instantiate_binder_with_fresh_vars(
1054                    self.span,
1055                    BoundRegionConversionTime::FnCall,
1056                    fty,
1057                );
1058                self.can_eq(self.param_env, fty.output(), expected)
1059            }),
1060            _ => false,
1061        }
1062    }
1063
1064    #[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(1064u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["import_ids",
                                                    "trait_def_id", "lint_ambiguous"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&import_ids)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&lint_ambiguous as
                                                            &dyn 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::PredicatePolarity::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: import_ids.clone(),
                                    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:1106",
                                                "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(1106u32),
                                                ::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};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("method has inapplicable self")
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        self.record_static_candidate(CandidateSource::Trait(trait_def_id));
                        continue;
                    }
                    self.push_candidate(Candidate {
                            item,
                            import_ids: import_ids.clone(),
                            kind: TraitCandidate(ty::Binder::dummy(trait_ref),
                                lint_ambiguous),
                        }, false);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1065    fn assemble_extension_candidates_for_trait(
1066        &mut self,
1067        import_ids: &SmallVec<[LocalDefId; 1]>,
1068        trait_def_id: DefId,
1069        lint_ambiguous: bool,
1070    ) {
1071        let trait_args = self.fresh_args_for_item(self.span, trait_def_id);
1072        let trait_ref = ty::TraitRef::new_from_args(self.tcx, trait_def_id, trait_args);
1073
1074        if self.tcx.is_trait_alias(trait_def_id) {
1075            // For trait aliases, recursively assume all explicitly named traits are relevant
1076            for (bound_trait_pred, _) in
1077                traits::expand_trait_aliases(self.tcx, [(trait_ref.upcast(self.tcx), self.span)]).0
1078            {
1079                assert_eq!(bound_trait_pred.polarity(), ty::PredicatePolarity::Positive);
1080                let bound_trait_ref = bound_trait_pred.map_bound(|pred| pred.trait_ref);
1081                for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
1082                    if !self.has_applicable_self(&item) {
1083                        self.record_static_candidate(CandidateSource::Trait(
1084                            bound_trait_ref.def_id(),
1085                        ));
1086                    } else {
1087                        self.push_candidate(
1088                            Candidate {
1089                                item,
1090                                import_ids: import_ids.clone(),
1091                                kind: TraitCandidate(bound_trait_ref, lint_ambiguous),
1092                            },
1093                            false,
1094                        );
1095                    }
1096                }
1097            }
1098        } else {
1099            debug_assert!(self.tcx.is_trait(trait_def_id));
1100            if self.tcx.trait_is_auto(trait_def_id) {
1101                return;
1102            }
1103            for item in self.impl_or_trait_item(trait_def_id) {
1104                // Check whether `trait_def_id` defines a method with suitable name.
1105                if !self.has_applicable_self(&item) {
1106                    debug!("method has inapplicable self");
1107                    self.record_static_candidate(CandidateSource::Trait(trait_def_id));
1108                    continue;
1109                }
1110                self.push_candidate(
1111                    Candidate {
1112                        item,
1113                        import_ids: import_ids.clone(),
1114                        kind: TraitCandidate(ty::Binder::dummy(trait_ref), lint_ambiguous),
1115                    },
1116                    false,
1117                );
1118            }
1119        }
1120    }
1121
1122    fn candidate_method_names(
1123        &self,
1124        candidate_filter: impl Fn(&ty::AssocItem) -> bool,
1125    ) -> Vec<Ident> {
1126        let mut set = FxHashSet::default();
1127        let mut names: Vec<_> = self
1128            .inherent_candidates
1129            .iter()
1130            .chain(&self.extension_candidates)
1131            .filter(|candidate| candidate_filter(&candidate.item))
1132            .filter(|candidate| {
1133                if let Some(return_ty) = self.return_type {
1134                    self.matches_return_type(candidate.item, return_ty)
1135                } else {
1136                    true
1137                }
1138            })
1139            // ensure that we don't suggest unstable methods
1140            .filter(|candidate| {
1141                // note that `DUMMY_SP` is ok here because it is only used for
1142                // suggestions and macro stuff which isn't applicable here.
1143                !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.eval_stability(candidate.item.def_id,
        None, DUMMY_SP, None) {
    stability::EvalResult::Deny { .. } => true,
    _ => false,
}matches!(
1144                    self.tcx.eval_stability(candidate.item.def_id, None, DUMMY_SP, None),
1145                    stability::EvalResult::Deny { .. }
1146                )
1147            })
1148            .map(|candidate| candidate.item.ident(self.tcx))
1149            .filter(|&name| set.insert(name))
1150            .collect();
1151
1152        // Sort them by the name so we have a stable result.
1153        names.sort_by(|a, b| a.as_str().cmp(b.as_str()));
1154        names
1155    }
1156
1157    ///////////////////////////////////////////////////////////////////////////
1158    // THE ACTUAL SEARCH
1159
1160    #[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(1160u32),
                                    ::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(&[]) })
                } 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:1182",
                                    "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(1182u32),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("pick: actual search failed, assemble diagnostics")
                                                        as &dyn 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)) =>
                        <[_]>::into_vec(::alloc::boxed::box_new([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))]
1161    fn pick(mut self) -> PickResult<'tcx> {
1162        assert!(self.method_name.is_some());
1163
1164        let mut unsatisfied_predicates = Vec::new();
1165
1166        if let Some(r) = self.pick_core(&mut unsatisfied_predicates) {
1167            return r;
1168        }
1169
1170        // If it's a `lookup_probe_for_diagnostic`, then quit early. No need to
1171        // probe for other candidates.
1172        if self.is_suggestion.0 {
1173            return Err(MethodError::NoMatch(NoMatchData {
1174                static_candidates: vec![],
1175                unsatisfied_predicates: vec![],
1176                out_of_scope_traits: vec![],
1177                similar_candidate: None,
1178                mode: self.mode,
1179            }));
1180        }
1181
1182        debug!("pick: actual search failed, assemble diagnostics");
1183
1184        let static_candidates = std::mem::take(self.static_candidates.get_mut());
1185        let private_candidate = self.private_candidate.take();
1186
1187        // things failed, so lets look at all traits, for diagnostic purposes now:
1188        self.reset();
1189
1190        self.assemble_extension_candidates_for_all_traits();
1191
1192        let out_of_scope_traits = match self.pick_core(&mut Vec::new()) {
1193            Some(Ok(p)) => vec![p.item.container_id(self.tcx)],
1194            Some(Err(MethodError::Ambiguity(v))) => v
1195                .into_iter()
1196                .map(|source| match source {
1197                    CandidateSource::Trait(id) => id,
1198                    CandidateSource::Impl(impl_id) => self.tcx.impl_trait_id(impl_id),
1199                })
1200                .collect(),
1201            Some(Err(MethodError::NoMatch(NoMatchData {
1202                out_of_scope_traits: others, ..
1203            }))) => {
1204                assert!(others.is_empty());
1205                vec![]
1206            }
1207            _ => vec![],
1208        };
1209
1210        if let Some((kind, def_id)) = private_candidate {
1211            return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits));
1212        }
1213        let similar_candidate = self.probe_for_similar_candidate()?;
1214
1215        Err(MethodError::NoMatch(NoMatchData {
1216            static_candidates,
1217            unsatisfied_predicates,
1218            out_of_scope_traits,
1219            similar_candidate,
1220            mode: self.mode,
1221        }))
1222    }
1223
1224    fn pick_core(
1225        &self,
1226        unsatisfied_predicates: &mut UnsatisfiedPredicates<'tcx>,
1227    ) -> Option<PickResult<'tcx>> {
1228        // Pick stable methods only first, and consider unstable candidates if not found.
1229        self.pick_all_method(&mut PickDiagHints {
1230            // This first cycle, maintain a list of unstable candidates which
1231            // we encounter. This will end up in the Pick for diagnostics.
1232            unstable_candidates: Some(Vec::new()),
1233            // Contribute to the list of unsatisfied predicates which may
1234            // also be used for diagnostics.
1235            unsatisfied_predicates,
1236        })
1237        .or_else(|| {
1238            self.pick_all_method(&mut PickDiagHints {
1239                // On the second search, don't provide a special list of unstable
1240                // candidates. This indicates to the picking code that it should
1241                // in fact include such unstable candidates in the actual
1242                // search.
1243                unstable_candidates: None,
1244                // And there's no need to duplicate ourselves in the
1245                // unsatisifed predicates list. Provide a throwaway list.
1246                unsatisfied_predicates: &mut Vec::new(),
1247            })
1248        })
1249    }
1250
1251    fn pick_all_method<'b>(
1252        &self,
1253        pick_diag_hints: &mut PickDiagHints<'b, 'tcx>,
1254    ) -> Option<PickResult<'tcx>> {
1255        let track_unstable_candidates = pick_diag_hints.unstable_candidates.is_some();
1256        self.steps
1257            .iter()
1258            // At this point we're considering the types to which the receiver can be converted,
1259            // so we want to follow the `Deref` chain not the `Receiver` chain. Filter out
1260            // steps which can only be reached by following the (longer) `Receiver` chain.
1261            .filter(|step| step.reachable_via_deref)
1262            .filter(|step| {
1263                {
    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:1263",
                        "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(1263u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("pick_all_method: step={0:?}",
                                                    step) as &dyn Value))])
            });
    } else { ; }
};debug!("pick_all_method: step={:?}", step);
1264                // skip types that are from a type error or that would require dereferencing
1265                // a raw pointer
1266                !step.self_ty.value.references_error() && !step.from_unsafe_deref
1267            })
1268            .find_map(|step| {
1269                let InferOk { value: self_ty, obligations: instantiate_self_ty_obligations } = self
1270                    .fcx
1271                    .probe_instantiate_query_response(
1272                        self.span,
1273                        self.orig_steps_var_values,
1274                        &step.self_ty,
1275                    )
1276                    .unwrap_or_else(|_| {
1277                        ::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)
1278                    });
1279
1280                let by_value_pick = self.pick_by_value_method(
1281                    step,
1282                    self_ty,
1283                    &instantiate_self_ty_obligations,
1284                    pick_diag_hints,
1285                );
1286
1287                // Check for shadowing of a by-reference method by a by-value method (see comments on check_for_shadowing)
1288                if let Some(by_value_pick) = by_value_pick {
1289                    if let Ok(by_value_pick) = by_value_pick.as_ref() {
1290                        if by_value_pick.kind == PickKind::InherentImplPick {
1291                            for mutbl in [hir::Mutability::Not, hir::Mutability::Mut] {
1292                                if let Err(e) = self.check_for_shadowed_autorefd_method(
1293                                    by_value_pick,
1294                                    step,
1295                                    self_ty,
1296                                    &instantiate_self_ty_obligations,
1297                                    mutbl,
1298                                    track_unstable_candidates,
1299                                ) {
1300                                    return Some(Err(e));
1301                                }
1302                            }
1303                        }
1304                    }
1305                    return Some(by_value_pick);
1306                }
1307
1308                let autoref_pick = self.pick_autorefd_method(
1309                    step,
1310                    self_ty,
1311                    &instantiate_self_ty_obligations,
1312                    hir::Mutability::Not,
1313                    pick_diag_hints,
1314                    None,
1315                );
1316                // Check for shadowing of a by-mut-ref method by a by-reference method (see comments on check_for_shadowing)
1317                if let Some(autoref_pick) = autoref_pick {
1318                    if let Ok(autoref_pick) = autoref_pick.as_ref() {
1319                        // Check we're not shadowing others
1320                        if autoref_pick.kind == PickKind::InherentImplPick {
1321                            if let Err(e) = self.check_for_shadowed_autorefd_method(
1322                                autoref_pick,
1323                                step,
1324                                self_ty,
1325                                &instantiate_self_ty_obligations,
1326                                hir::Mutability::Mut,
1327                                track_unstable_candidates,
1328                            ) {
1329                                return Some(Err(e));
1330                            }
1331                        }
1332                    }
1333                    return Some(autoref_pick);
1334                }
1335
1336                // Note that no shadowing errors are produced from here on,
1337                // as we consider const ptr methods.
1338                // We allow new methods that take *mut T to shadow
1339                // methods which took *const T, so there is no entry in
1340                // this list for the results of `pick_const_ptr_method`.
1341                // The reason is that the standard pointer cast method
1342                // (on a mutable pointer) always already shadows the
1343                // cast method (on a const pointer). So, if we added
1344                // `pick_const_ptr_method` to this method, the anti-
1345                // shadowing algorithm would always complain about
1346                // the conflict between *const::cast and *mut::cast.
1347                // In practice therefore this does constrain us:
1348                // we cannot add new
1349                //   self: *mut Self
1350                // methods to types such as NonNull or anything else
1351                // which implements Receiver, because this might in future
1352                // shadow existing methods taking
1353                //   self: *const NonNull<Self>
1354                // in the pointee. In practice, methods taking raw pointers
1355                // are rare, and it seems that it should be easily possible
1356                // to avoid such compatibility breaks.
1357                // We also don't check for reborrowed pin methods which
1358                // may be shadowed; these also seem unlikely to occur.
1359                self.pick_autorefd_method(
1360                    step,
1361                    self_ty,
1362                    &instantiate_self_ty_obligations,
1363                    hir::Mutability::Mut,
1364                    pick_diag_hints,
1365                    None,
1366                )
1367                .or_else(|| {
1368                    self.pick_const_ptr_method(
1369                        step,
1370                        self_ty,
1371                        &instantiate_self_ty_obligations,
1372                        pick_diag_hints,
1373                    )
1374                })
1375                .or_else(|| {
1376                    self.pick_reborrow_pin_method(
1377                        step,
1378                        self_ty,
1379                        &instantiate_self_ty_obligations,
1380                        pick_diag_hints,
1381                    )
1382                })
1383            })
1384    }
1385
1386    /// Check for cases where arbitrary self types allows shadowing
1387    /// of methods that might be a compatibility break. Specifically,
1388    /// we have something like:
1389    /// ```ignore (illustrative)
1390    /// struct A;
1391    /// impl A {
1392    ///   fn foo(self: &NonNull<A>) {}
1393    ///      // note this is by reference
1394    /// }
1395    /// ```
1396    /// then we've come along and added this method to `NonNull`:
1397    /// ```ignore (illustrative)
1398    ///   fn foo(self)  // note this is by value
1399    /// ```
1400    /// Report an error in this case.
1401    fn check_for_shadowed_autorefd_method(
1402        &self,
1403        possible_shadower: &Pick<'tcx>,
1404        step: &CandidateStep<'tcx>,
1405        self_ty: Ty<'tcx>,
1406        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1407        mutbl: hir::Mutability,
1408        track_unstable_candidates: bool,
1409    ) -> Result<(), MethodError<'tcx>> {
1410        // The errors emitted by this function are part of
1411        // the arbitrary self types work, and should not impact
1412        // other users.
1413        if !self.tcx.features().arbitrary_self_types()
1414            && !self.tcx.features().arbitrary_self_types_pointers()
1415        {
1416            return Ok(());
1417        }
1418
1419        // We don't want to remember any of the diagnostic hints from this
1420        // shadow search, but we do need to provide Some/None for the
1421        // unstable_candidates in order to reflect the behavior of the
1422        // main search.
1423        let mut pick_diag_hints = PickDiagHints {
1424            unstable_candidates: if track_unstable_candidates { Some(Vec::new()) } else { None },
1425            unsatisfied_predicates: &mut Vec::new(),
1426        };
1427        // Set criteria for how we find methods possibly shadowed by 'possible_shadower'
1428        let pick_constraints = PickConstraintsForShadowed {
1429            // It's the same `self` type...
1430            autoderefs: possible_shadower.autoderefs,
1431            // ... but the method was found in an impl block determined
1432            // by searching further along the Receiver chain than the other,
1433            // showing that it's a smart pointer type causing the problem...
1434            receiver_steps: possible_shadower.receiver_steps,
1435            // ... and they don't end up pointing to the same item in the
1436            // first place (could happen with things like blanket impls for T)
1437            def_id: possible_shadower.item.def_id,
1438        };
1439        // A note on the autoderefs above. Within pick_by_value_method, an extra
1440        // autoderef may be applied in order to reborrow a reference with
1441        // a different lifetime. That seems as though it would break the
1442        // logic of these constraints, since the number of autoderefs could
1443        // no longer be used to identify the fundamental type of the receiver.
1444        // However, this extra autoderef is applied only to by-value calls
1445        // where the receiver is already a reference. So this situation would
1446        // only occur in cases where the shadowing looks like this:
1447        // ```
1448        // struct A;
1449        // impl A {
1450        //   fn foo(self: &&NonNull<A>) {}
1451        //      // note this is by DOUBLE reference
1452        // }
1453        // ```
1454        // then we've come along and added this method to `NonNull`:
1455        // ```
1456        //   fn foo(&self)  // note this is by single reference
1457        // ```
1458        // and the call is:
1459        // ```
1460        // let bar = NonNull<Foo>;
1461        // let bar = &foo;
1462        // bar.foo();
1463        // ```
1464        // In these circumstances, the logic is wrong, and we wouldn't spot
1465        // the shadowing, because the autoderef-based maths wouldn't line up.
1466        // This is a niche case and we can live without generating an error
1467        // in the case of such shadowing.
1468        let potentially_shadowed_pick = self.pick_autorefd_method(
1469            step,
1470            self_ty,
1471            instantiate_self_ty_obligations,
1472            mutbl,
1473            &mut pick_diag_hints,
1474            Some(&pick_constraints),
1475        );
1476        // Look for actual pairs of shadower/shadowed which are
1477        // the sort of shadowing case we want to avoid. Specifically...
1478        if let Some(Ok(possible_shadowed)) = potentially_shadowed_pick.as_ref() {
1479            let sources = [possible_shadower, possible_shadowed]
1480                .into_iter()
1481                .map(|p| self.candidate_source_from_pick(p))
1482                .collect();
1483            return Err(MethodError::Ambiguity(sources));
1484        }
1485        Ok(())
1486    }
1487
1488    /// For each type `T` in the step list, this attempts to find a method where
1489    /// the (transformed) self type is exactly `T`. We do however do one
1490    /// transformation on the adjustment: if we are passing a region pointer in,
1491    /// we will potentially *reborrow* it to a shorter lifetime. This allows us
1492    /// to transparently pass `&mut` pointers, in particular, without consuming
1493    /// them for their entire lifetime.
1494    fn pick_by_value_method(
1495        &self,
1496        step: &CandidateStep<'tcx>,
1497        self_ty: Ty<'tcx>,
1498        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1499        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1500    ) -> Option<PickResult<'tcx>> {
1501        if step.unsize {
1502            return None;
1503        }
1504
1505        self.pick_method(self_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(|r| {
1506            r.map(|mut pick| {
1507                pick.autoderefs = step.autoderefs;
1508
1509                match *step.self_ty.value.value.kind() {
1510                    // Insert a `&*` or `&mut *` if this is a reference type:
1511                    ty::Ref(_, _, mutbl) => {
1512                        pick.autoderefs += 1;
1513                        pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::Autoref {
1514                            mutbl,
1515                            unsize: pick.autoref_or_ptr_adjustment.is_some_and(|a| a.get_unsize()),
1516                        })
1517                    }
1518
1519                    ty::Adt(def, args)
1520                        if self.tcx.features().pin_ergonomics()
1521                            && self.tcx.is_lang_item(def.did(), hir::LangItem::Pin) =>
1522                    {
1523                        // make sure this is a pinned reference (and not a `Pin<Box>` or something)
1524                        if let ty::Ref(_, _, mutbl) = args[0].expect_ty().kind() {
1525                            pick.autoref_or_ptr_adjustment =
1526                                Some(AutorefOrPtrAdjustment::ReborrowPin(*mutbl));
1527                        }
1528                    }
1529
1530                    _ => (),
1531                }
1532
1533                pick
1534            })
1535        })
1536    }
1537
1538    fn pick_autorefd_method(
1539        &self,
1540        step: &CandidateStep<'tcx>,
1541        self_ty: Ty<'tcx>,
1542        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1543        mutbl: hir::Mutability,
1544        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1545        pick_constraints: Option<&PickConstraintsForShadowed>,
1546    ) -> Option<PickResult<'tcx>> {
1547        let tcx = self.tcx;
1548
1549        if let Some(pick_constraints) = pick_constraints {
1550            if !pick_constraints.may_shadow_based_on_autoderefs(step.autoderefs) {
1551                return None;
1552            }
1553        }
1554
1555        // In general, during probing we erase regions.
1556        let region = tcx.lifetimes.re_erased;
1557
1558        let autoref_ty = Ty::new_ref(tcx, region, self_ty, mutbl);
1559        self.pick_method(
1560            autoref_ty,
1561            instantiate_self_ty_obligations,
1562            pick_diag_hints,
1563            pick_constraints,
1564        )
1565        .map(|r| {
1566            r.map(|mut pick| {
1567                pick.autoderefs = step.autoderefs;
1568                pick.autoref_or_ptr_adjustment =
1569                    Some(AutorefOrPtrAdjustment::Autoref { mutbl, unsize: step.unsize });
1570                pick
1571            })
1572        })
1573    }
1574
1575    /// Looks for applicable methods if we reborrow a `Pin<&mut T>` as a `Pin<&T>`.
1576    #[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(1576u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["self_ty",
                                                    "instantiate_self_ty_obligations"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instantiate_self_ty_obligations)
                                                            as &dyn 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(), hir::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))]
1577    fn pick_reborrow_pin_method(
1578        &self,
1579        step: &CandidateStep<'tcx>,
1580        self_ty: Ty<'tcx>,
1581        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1582        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1583    ) -> Option<PickResult<'tcx>> {
1584        if !self.tcx.features().pin_ergonomics() {
1585            return None;
1586        }
1587
1588        // make sure self is a Pin<&mut T>
1589        let inner_ty = match self_ty.kind() {
1590            ty::Adt(def, args) if self.tcx.is_lang_item(def.did(), hir::LangItem::Pin) => {
1591                match args[0].expect_ty().kind() {
1592                    ty::Ref(_, ty, hir::Mutability::Mut) => *ty,
1593                    _ => {
1594                        return None;
1595                    }
1596                }
1597            }
1598            _ => return None,
1599        };
1600
1601        let region = self.tcx.lifetimes.re_erased;
1602        let autopin_ty = Ty::new_pinned_ref(self.tcx, region, inner_ty, hir::Mutability::Not);
1603        self.pick_method(autopin_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1604            |r| {
1605                r.map(|mut pick| {
1606                    pick.autoderefs = step.autoderefs;
1607                    pick.autoref_or_ptr_adjustment =
1608                        Some(AutorefOrPtrAdjustment::ReborrowPin(hir::Mutability::Not));
1609                    pick
1610                })
1611            },
1612        )
1613    }
1614
1615    /// If `self_ty` is `*mut T` then this picks `*const T` methods. The reason why we have a
1616    /// special case for this is because going from `*mut T` to `*const T` with autoderefs and
1617    /// autorefs would require dereferencing the pointer, which is not safe.
1618    fn pick_const_ptr_method(
1619        &self,
1620        step: &CandidateStep<'tcx>,
1621        self_ty: Ty<'tcx>,
1622        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1623        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1624    ) -> Option<PickResult<'tcx>> {
1625        // Don't convert an unsized reference to ptr
1626        if step.unsize {
1627            return None;
1628        }
1629
1630        let &ty::RawPtr(ty, hir::Mutability::Mut) = self_ty.kind() else {
1631            return None;
1632        };
1633
1634        let const_ptr_ty = Ty::new_imm_ptr(self.tcx, ty);
1635        self.pick_method(const_ptr_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1636            |r| {
1637                r.map(|mut pick| {
1638                    pick.autoderefs = step.autoderefs;
1639                    pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::ToConstPtr);
1640                    pick
1641                })
1642            },
1643        )
1644    }
1645
1646    fn pick_method(
1647        &self,
1648        self_ty: Ty<'tcx>,
1649        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1650        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1651        pick_constraints: Option<&PickConstraintsForShadowed>,
1652    ) -> Option<PickResult<'tcx>> {
1653        {
    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:1653",
                        "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(1653u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("pick_method(self_ty={0})",
                                                    self.ty_to_string(self_ty)) as &dyn Value))])
            });
    } else { ; }
};debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1654
1655        for (kind, candidates) in
1656            [("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1657        {
1658            {
    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:1658",
                        "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(1658u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("searching {0} candidates",
                                                    kind) as &dyn Value))])
            });
    } else { ; }
};debug!("searching {} candidates", kind);
1659            let res = self.consider_candidates(
1660                self_ty,
1661                instantiate_self_ty_obligations,
1662                candidates,
1663                pick_diag_hints,
1664                pick_constraints,
1665            );
1666            if let Some(pick) = res {
1667                return Some(pick);
1668            }
1669        }
1670
1671        if self.private_candidate.get().is_none() {
1672            if let Some(Ok(pick)) = self.consider_candidates(
1673                self_ty,
1674                instantiate_self_ty_obligations,
1675                &self.private_candidates,
1676                &mut PickDiagHints {
1677                    unstable_candidates: None,
1678                    unsatisfied_predicates: &mut ::alloc::vec::Vec::new()vec![],
1679                },
1680                None,
1681            ) {
1682                self.private_candidate.set(Some((pick.item.as_def_kind(), pick.item.def_id)));
1683            }
1684        }
1685        None
1686    }
1687
1688    fn consider_candidates(
1689        &self,
1690        self_ty: Ty<'tcx>,
1691        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1692        candidates: &[Candidate<'tcx>],
1693        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1694        pick_constraints: Option<&PickConstraintsForShadowed>,
1695    ) -> Option<PickResult<'tcx>> {
1696        let mut applicable_candidates: Vec<_> = candidates
1697            .iter()
1698            .filter(|candidate| {
1699                pick_constraints
1700                    .map(|pick_constraints| pick_constraints.candidate_may_shadow(&candidate))
1701                    .unwrap_or(true)
1702            })
1703            .map(|probe| {
1704                (
1705                    probe,
1706                    self.consider_probe(
1707                        self_ty,
1708                        instantiate_self_ty_obligations,
1709                        probe,
1710                        &mut pick_diag_hints.unsatisfied_predicates,
1711                    ),
1712                )
1713            })
1714            .filter(|&(_, status)| status != ProbeResult::NoMatch)
1715            .collect();
1716
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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("applicable_candidates: {0:?}",
                                                    applicable_candidates) as &dyn Value))])
            });
    } else { ; }
};debug!("applicable_candidates: {:?}", applicable_candidates);
1718
1719        if applicable_candidates.len() > 1 {
1720            if let Some(pick) =
1721                self.collapse_candidates_to_trait_pick(self_ty, &applicable_candidates)
1722            {
1723                return Some(Ok(pick));
1724            }
1725        }
1726
1727        if let Some(uc) = &mut pick_diag_hints.unstable_candidates {
1728            applicable_candidates.retain(|&(candidate, _)| {
1729                if let stability::EvalResult::Deny { feature, .. } =
1730                    self.tcx.eval_stability(candidate.item.def_id, None, self.span, None)
1731                {
1732                    uc.push((candidate.clone(), feature));
1733                    return false;
1734                }
1735                true
1736            });
1737        }
1738
1739        if applicable_candidates.len() > 1 {
1740            // We collapse to a subtrait pick *after* filtering unstable candidates
1741            // to make sure we don't prefer a unstable subtrait method over a stable
1742            // supertrait method.
1743            if self.tcx.features().supertrait_item_shadowing() {
1744                if let Some(pick) =
1745                    self.collapse_candidates_to_subtrait_pick(self_ty, &applicable_candidates)
1746                {
1747                    return Some(Ok(pick));
1748                }
1749            }
1750
1751            let sources =
1752                applicable_candidates.iter().map(|p| self.candidate_source(p.0, self_ty)).collect();
1753            return Some(Err(MethodError::Ambiguity(sources)));
1754        }
1755
1756        applicable_candidates.pop().map(|(probe, status)| match status {
1757            ProbeResult::Match => Ok(probe.to_unadjusted_pick(
1758                self_ty,
1759                pick_diag_hints.unstable_candidates.clone().unwrap_or_default(),
1760            )),
1761            ProbeResult::NoMatch | ProbeResult::BadReturnType => Err(MethodError::BadReturnType),
1762        })
1763    }
1764}
1765
1766impl<'tcx> Pick<'tcx> {
1767    /// In case there were unstable name collisions, emit them as a lint.
1768    /// Checks whether two picks do not refer to the same trait item for the same `Self` type.
1769    /// Only useful for comparisons of picks in order to improve diagnostics.
1770    /// Do not use for type checking.
1771    pub(crate) fn differs_from(&self, other: &Self) -> bool {
1772        let Self {
1773            item: AssocItem { def_id, kind: _, container: _ },
1774            kind: _,
1775            import_ids: _,
1776            autoderefs: _,
1777            autoref_or_ptr_adjustment: _,
1778            self_ty,
1779            unstable_candidates: _,
1780            receiver_steps: _,
1781            shadowed_candidates: _,
1782        } = *self;
1783        self_ty != other.self_ty || def_id != other.item.def_id
1784    }
1785
1786    /// In case there were unstable name collisions, emit them as a lint.
1787    pub(crate) fn maybe_emit_unstable_name_collision_hint(
1788        &self,
1789        tcx: TyCtxt<'tcx>,
1790        span: Span,
1791        scope_expr_id: HirId,
1792    ) {
1793        if self.unstable_candidates.is_empty() {
1794            return;
1795        }
1796        let def_kind = self.item.as_def_kind();
1797        tcx.node_span_lint(lint::builtin::UNSTABLE_NAME_COLLISIONS, scope_expr_id, span, |lint| {
1798            lint.primary_message(::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, self.item.def_id),
                tcx.def_kind_descr(def_kind, self.item.def_id)))
    })format!(
1799                "{} {} with this name may be added to the standard library in the future",
1800                tcx.def_kind_descr_article(def_kind, self.item.def_id),
1801                tcx.def_kind_descr(def_kind, self.item.def_id),
1802            ));
1803
1804            match (self.item.kind, self.item.container) {
1805                (ty::AssocKind::Fn { .. }, _) => {
1806                    // FIXME: This should be a `span_suggestion` instead of `help`
1807                    // However `self.span` only
1808                    // highlights the method name, so we can't use it. Also consider reusing
1809                    // the code from `report_method_error()`.
1810                    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(self.item.def_id)))
    })format!(
1811                        "call with fully qualified syntax `{}(...)` to keep using the current \
1812                             method",
1813                        tcx.def_path_str(self.item.def_id),
1814                    ));
1815                }
1816                (ty::AssocKind::Const { name }, ty::AssocContainer::Trait) => {
1817                    let def_id = self.item.container_id(tcx);
1818                    lint.span_suggestion(
1819                        span,
1820                        "use the fully qualified path to the associated const",
1821                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", self.self_ty,
                tcx.def_path_str(def_id), name))
    })format!("<{} as {}>::{}", self.self_ty, tcx.def_path_str(def_id), name),
1822                        Applicability::MachineApplicable,
1823                    );
1824                }
1825                _ => {}
1826            }
1827            tcx.disabled_nightly_features(
1828                lint,
1829                self.unstable_candidates.iter().map(|(candidate, feature)| {
1830                    (::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)
1831                }),
1832            );
1833        });
1834    }
1835}
1836
1837impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
1838    fn select_trait_candidate(
1839        &self,
1840        trait_ref: ty::TraitRef<'tcx>,
1841    ) -> traits::SelectionResult<'tcx, traits::Selection<'tcx>> {
1842        let obligation =
1843            traits::Obligation::new(self.tcx, self.misc(self.span), self.param_env, trait_ref);
1844        traits::SelectionContext::new(self).select(&obligation)
1845    }
1846
1847    /// Used for ambiguous method call error reporting. Uses probing that throws away the result internally,
1848    /// so do not use to make a decision that may lead to a successful compilation.
1849    fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>) -> CandidateSource {
1850        match candidate.kind {
1851            InherentImplCandidate { .. } => {
1852                CandidateSource::Impl(candidate.item.container_id(self.tcx))
1853            }
1854            ObjectCandidate(_) | WhereClauseCandidate(_) => {
1855                CandidateSource::Trait(candidate.item.container_id(self.tcx))
1856            }
1857            TraitCandidate(trait_ref, _) => self.probe(|_| {
1858                let trait_ref = self.instantiate_binder_with_fresh_vars(
1859                    self.span,
1860                    BoundRegionConversionTime::FnCall,
1861                    trait_ref,
1862                );
1863                let (xform_self_ty, _) =
1864                    self.xform_self_ty(candidate.item, trait_ref.self_ty(), trait_ref.args);
1865                // Guide the trait selection to show impls that have methods whose type matches
1866                // up with the `self` parameter of the method.
1867                let _ = self.at(&ObligationCause::dummy(), self.param_env).sup(
1868                    DefineOpaqueTypes::Yes,
1869                    xform_self_ty,
1870                    self_ty,
1871                );
1872                match self.select_trait_candidate(trait_ref) {
1873                    Ok(Some(traits::ImplSource::UserDefined(ref impl_data))) => {
1874                        // If only a single impl matches, make the error message point
1875                        // to that impl.
1876                        CandidateSource::Impl(impl_data.impl_def_id)
1877                    }
1878                    _ => CandidateSource::Trait(candidate.item.container_id(self.tcx)),
1879                }
1880            }),
1881        }
1882    }
1883
1884    fn candidate_source_from_pick(&self, pick: &Pick<'tcx>) -> CandidateSource {
1885        match pick.kind {
1886            InherentImplPick => CandidateSource::Impl(pick.item.container_id(self.tcx)),
1887            ObjectPick | WhereClausePick(_) | TraitPick(_) => {
1888                CandidateSource::Trait(pick.item.container_id(self.tcx))
1889            }
1890        }
1891    }
1892
1893    x;#[instrument(level = "debug", skip(self, possibly_unsatisfied_predicates), ret)]
1894    fn consider_probe(
1895        &self,
1896        self_ty: Ty<'tcx>,
1897        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1898        probe: &Candidate<'tcx>,
1899        possibly_unsatisfied_predicates: &mut UnsatisfiedPredicates<'tcx>,
1900    ) -> ProbeResult {
1901        self.probe(|snapshot| {
1902            let outer_universe = self.universe();
1903
1904            let mut result = ProbeResult::Match;
1905            let cause = &self.misc(self.span);
1906            let ocx = ObligationCtxt::new_with_diagnostics(self);
1907
1908            // Subtle: we're not *really* instantiating the current self type while
1909            // probing, but instead fully recompute the autoderef steps once we've got
1910            // a final `Pick`. We can't nicely handle these obligations outside of a probe.
1911            //
1912            // We simply handle them for each candidate here for now. That's kinda scuffed
1913            // and ideally we just put them into the `FnCtxt` right away. We need to consider
1914            // them to deal with defining uses in `method_autoderef_steps`.
1915            if self.next_trait_solver() {
1916                ocx.register_obligations(instantiate_self_ty_obligations.iter().cloned());
1917                let errors = ocx.try_evaluate_obligations();
1918                if !errors.is_empty() {
1919                    unreachable!("unexpected autoderef error {errors:?}");
1920                }
1921            }
1922
1923            let mut trait_predicate = None;
1924            let (mut xform_self_ty, mut xform_ret_ty);
1925
1926            match probe.kind {
1927                InherentImplCandidate { impl_def_id, .. } => {
1928                    let impl_args = self.fresh_args_for_item(self.span, impl_def_id);
1929                    let impl_ty = self.tcx.type_of(impl_def_id).instantiate(self.tcx, impl_args);
1930                    (xform_self_ty, xform_ret_ty) =
1931                        self.xform_self_ty(probe.item, impl_ty, impl_args);
1932                    xform_self_ty = ocx.normalize(cause, self.param_env, xform_self_ty);
1933                    match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
1934                    {
1935                        Ok(()) => {}
1936                        Err(err) => {
1937                            debug!("--> cannot relate self-types {:?}", err);
1938                            return ProbeResult::NoMatch;
1939                        }
1940                    }
1941                    // FIXME: Weirdly, we normalize the ret ty in this candidate, but no other candidates.
1942                    xform_ret_ty = ocx.normalize(cause, self.param_env, xform_ret_ty);
1943                    // Check whether the impl imposes obligations we have to worry about.
1944                    let impl_def_id = probe.item.container_id(self.tcx);
1945                    let impl_bounds =
1946                        self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_args);
1947                    let impl_bounds = ocx.normalize(cause, self.param_env, impl_bounds);
1948                    // Convert the bounds into obligations.
1949                    ocx.register_obligations(traits::predicates_for_generics(
1950                        |idx, span| {
1951                            let code = ObligationCauseCode::WhereClauseInExpr(
1952                                impl_def_id,
1953                                span,
1954                                self.scope_expr_id,
1955                                idx,
1956                            );
1957                            self.cause(self.span, code)
1958                        },
1959                        self.param_env,
1960                        impl_bounds,
1961                    ));
1962                }
1963                TraitCandidate(poly_trait_ref, _) => {
1964                    // Some trait methods are excluded for arrays before 2021.
1965                    // (`array.into_iter()` wants a slice iterator for compatibility.)
1966                    if let Some(method_name) = self.method_name {
1967                        if self_ty.is_array() && !method_name.span.at_least_rust_2021() {
1968                            let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
1969                            if trait_def.skip_array_during_method_dispatch {
1970                                return ProbeResult::NoMatch;
1971                            }
1972                        }
1973
1974                        // Some trait methods are excluded for boxed slices before 2024.
1975                        // (`boxed_slice.into_iter()` wants a slice iterator for compatibility.)
1976                        if self_ty.boxed_ty().is_some_and(Ty::is_slice)
1977                            && !method_name.span.at_least_rust_2024()
1978                        {
1979                            let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
1980                            if trait_def.skip_boxed_slice_during_method_dispatch {
1981                                return ProbeResult::NoMatch;
1982                            }
1983                        }
1984                    }
1985
1986                    let trait_ref = self.instantiate_binder_with_fresh_vars(
1987                        self.span,
1988                        BoundRegionConversionTime::FnCall,
1989                        poly_trait_ref,
1990                    );
1991                    let trait_ref = ocx.normalize(cause, self.param_env, trait_ref);
1992                    (xform_self_ty, xform_ret_ty) =
1993                        self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
1994                    xform_self_ty = ocx.normalize(cause, self.param_env, xform_self_ty);
1995                    match self_ty.kind() {
1996                        // HACK: opaque types will match anything for which their bounds hold.
1997                        // Thus we need to prevent them from trying to match the `&_` autoref
1998                        // candidates that get created for `&self` trait methods.
1999                        ty::Alias(ty::Opaque, alias_ty)
2000                            if !self.next_trait_solver()
2001                                && self.infcx.can_define_opaque_ty(alias_ty.def_id)
2002                                && !xform_self_ty.is_ty_var() =>
2003                        {
2004                            return ProbeResult::NoMatch;
2005                        }
2006                        _ => match ocx.relate(
2007                            cause,
2008                            self.param_env,
2009                            self.variance(),
2010                            self_ty,
2011                            xform_self_ty,
2012                        ) {
2013                            Ok(()) => {}
2014                            Err(err) => {
2015                                debug!("--> cannot relate self-types {:?}", err);
2016                                return ProbeResult::NoMatch;
2017                            }
2018                        },
2019                    }
2020                    let obligation = traits::Obligation::new(
2021                        self.tcx,
2022                        cause.clone(),
2023                        self.param_env,
2024                        ty::Binder::dummy(trait_ref),
2025                    );
2026
2027                    // We only need this hack to deal with fatal overflow in the old solver.
2028                    if self.infcx.next_trait_solver() || self.infcx.predicate_may_hold(&obligation)
2029                    {
2030                        ocx.register_obligation(obligation);
2031                    } else {
2032                        result = ProbeResult::NoMatch;
2033                        if let Ok(Some(candidate)) = self.select_trait_candidate(trait_ref) {
2034                            for nested_obligation in candidate.nested_obligations() {
2035                                if !self.infcx.predicate_may_hold(&nested_obligation) {
2036                                    possibly_unsatisfied_predicates.push((
2037                                        self.resolve_vars_if_possible(nested_obligation.predicate),
2038                                        Some(self.resolve_vars_if_possible(obligation.predicate)),
2039                                        Some(nested_obligation.cause),
2040                                    ));
2041                                }
2042                            }
2043                        }
2044                    }
2045
2046                    trait_predicate = Some(trait_ref.upcast(self.tcx));
2047                }
2048                ObjectCandidate(poly_trait_ref) | WhereClauseCandidate(poly_trait_ref) => {
2049                    let trait_ref = self.instantiate_binder_with_fresh_vars(
2050                        self.span,
2051                        BoundRegionConversionTime::FnCall,
2052                        poly_trait_ref,
2053                    );
2054                    (xform_self_ty, xform_ret_ty) =
2055                        self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
2056
2057                    if matches!(probe.kind, WhereClauseCandidate(_)) {
2058                        // `WhereClauseCandidate` requires that the self type is a param,
2059                        // because it has special behavior with candidate preference as an
2060                        // inherent pick.
2061                        match ocx.structurally_normalize_ty(
2062                            cause,
2063                            self.param_env,
2064                            trait_ref.self_ty(),
2065                        ) {
2066                            Ok(ty) => {
2067                                if !matches!(ty.kind(), ty::Param(_)) {
2068                                    debug!("--> not a param ty: {xform_self_ty:?}");
2069                                    return ProbeResult::NoMatch;
2070                                }
2071                            }
2072                            Err(errors) => {
2073                                debug!("--> cannot relate self-types {:?}", errors);
2074                                return ProbeResult::NoMatch;
2075                            }
2076                        }
2077                    }
2078
2079                    xform_self_ty = ocx.normalize(cause, self.param_env, xform_self_ty);
2080                    match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
2081                    {
2082                        Ok(()) => {}
2083                        Err(err) => {
2084                            debug!("--> cannot relate self-types {:?}", err);
2085                            return ProbeResult::NoMatch;
2086                        }
2087                    }
2088                }
2089            }
2090
2091            // See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/134>.
2092            //
2093            // In the new solver, check the well-formedness of the return type.
2094            // This emulates, in a way, the predicates that fall out of
2095            // normalizing the return type in the old solver.
2096            //
2097            // FIXME(-Znext-solver): We alternatively could check the predicates of
2098            // the method itself hold, but we intentionally do not do this in the old
2099            // solver b/c of cycles, and doing it in the new solver would be stronger.
2100            // This should be fixed in the future, since it likely leads to much better
2101            // method winnowing.
2102            if let Some(xform_ret_ty) = xform_ret_ty
2103                && self.infcx.next_trait_solver()
2104            {
2105                ocx.register_obligation(traits::Obligation::new(
2106                    self.tcx,
2107                    cause.clone(),
2108                    self.param_env,
2109                    ty::ClauseKind::WellFormed(xform_ret_ty.into()),
2110                ));
2111            }
2112
2113            // Evaluate those obligations to see if they might possibly hold.
2114            for error in ocx.try_evaluate_obligations() {
2115                result = ProbeResult::NoMatch;
2116                let nested_predicate = self.resolve_vars_if_possible(error.obligation.predicate);
2117                if let Some(trait_predicate) = trait_predicate
2118                    && nested_predicate == self.resolve_vars_if_possible(trait_predicate)
2119                {
2120                    // Don't report possibly unsatisfied predicates if the root
2121                    // trait obligation from a `TraitCandidate` is unsatisfied.
2122                    // That just means the candidate doesn't hold.
2123                } else {
2124                    possibly_unsatisfied_predicates.push((
2125                        nested_predicate,
2126                        Some(self.resolve_vars_if_possible(error.root_obligation.predicate))
2127                            .filter(|root_predicate| *root_predicate != nested_predicate),
2128                        Some(error.obligation.cause),
2129                    ));
2130                }
2131            }
2132
2133            if let ProbeResult::Match = result
2134                && let Some(return_ty) = self.return_type
2135                && let Some(mut xform_ret_ty) = xform_ret_ty
2136            {
2137                // `xform_ret_ty` has only been normalized for `InherentImplCandidate`.
2138                // We don't normalize the other candidates for perf/backwards-compat reasons...
2139                // but `self.return_type` is only set on the diagnostic-path, so we
2140                // should be okay doing it here.
2141                if !matches!(probe.kind, InherentImplCandidate { .. }) {
2142                    xform_ret_ty = ocx.normalize(&cause, self.param_env, xform_ret_ty);
2143                }
2144
2145                debug!("comparing return_ty {:?} with xform ret ty {:?}", return_ty, xform_ret_ty);
2146                match ocx.relate(cause, self.param_env, self.variance(), xform_ret_ty, return_ty) {
2147                    Ok(()) => {}
2148                    Err(_) => {
2149                        result = ProbeResult::BadReturnType;
2150                    }
2151                }
2152
2153                // Evaluate those obligations to see if they might possibly hold.
2154                for error in ocx.try_evaluate_obligations() {
2155                    result = ProbeResult::NoMatch;
2156                    possibly_unsatisfied_predicates.push((
2157                        error.obligation.predicate,
2158                        Some(error.root_obligation.predicate)
2159                            .filter(|predicate| *predicate != error.obligation.predicate),
2160                        Some(error.root_obligation.cause),
2161                    ));
2162                }
2163            }
2164
2165            if self.infcx.next_trait_solver() {
2166                if self.should_reject_candidate_due_to_opaque_treated_as_rigid(trait_predicate) {
2167                    result = ProbeResult::NoMatch;
2168                }
2169            }
2170
2171            // Previously, method probe used `evaluate_predicate` to determine if a predicate
2172            // was impossible to satisfy. This did a leak check, so we must also do a leak
2173            // check here to prevent backwards-incompatible ambiguity being introduced. See
2174            // `tests/ui/methods/leak-check-disquality.rs` for a simple example of when this
2175            // may happen.
2176            if let Err(_) = self.leak_check(outer_universe, Some(snapshot)) {
2177                result = ProbeResult::NoMatch;
2178            }
2179
2180            result
2181        })
2182    }
2183
2184    /// Trait candidates for not-yet-defined opaque types are a somewhat hacky.
2185    ///
2186    /// We want to only accept trait methods if they were hold even if the
2187    /// opaque types were rigid. To handle this, we both check that for trait
2188    /// candidates the goal were to hold even when treating opaques as rigid,
2189    /// see [OpaqueTypesJank](rustc_trait_selection::solve::OpaqueTypesJank).
2190    ///
2191    /// We also check that all opaque types encountered as self types in the
2192    /// autoderef chain don't get constrained when applying the candidate.
2193    /// Importantly, this also handles calling methods taking `&self` on
2194    /// `impl Trait` to reject the "by-self" candidate.
2195    ///
2196    /// This needs to happen at the end of `consider_probe` as we need to take
2197    /// all the constraints from that into account.
2198    x;#[instrument(level = "debug", skip(self), ret)]
2199    fn should_reject_candidate_due_to_opaque_treated_as_rigid(
2200        &self,
2201        trait_predicate: Option<ty::Predicate<'tcx>>,
2202    ) -> bool {
2203        // This function is what hacky and doesn't perfectly do what we want it to.
2204        // It's not soundness critical and we should be able to freely improve this
2205        // in the future.
2206        //
2207        // Some concrete edge cases include the fact that `goal_may_hold_opaque_types_jank`
2208        // also fails if there are any constraints opaques which are never used as a self
2209        // type. We also allow where-bounds which are currently ambiguous but end up
2210        // constraining an opaque later on.
2211
2212        // Check whether the trait candidate would not be applicable if the
2213        // opaque type were rigid.
2214        if let Some(predicate) = trait_predicate {
2215            let goal = Goal { param_env: self.param_env, predicate };
2216            if !self.infcx.goal_may_hold_opaque_types_jank(goal) {
2217                return true;
2218            }
2219        }
2220
2221        // Check whether any opaque types in the autoderef chain have been
2222        // constrained.
2223        for step in self.steps {
2224            if step.self_ty_is_opaque {
2225                debug!(?step.autoderefs, ?step.self_ty, "self_type_is_opaque");
2226                let constrained_opaque = self.probe(|_| {
2227                    // If we fail to instantiate the self type of this
2228                    // step, this part of the deref-chain is no longer
2229                    // reachable. In this case we don't care about opaque
2230                    // types there.
2231                    let Ok(ok) = self.fcx.probe_instantiate_query_response(
2232                        self.span,
2233                        self.orig_steps_var_values,
2234                        &step.self_ty,
2235                    ) else {
2236                        debug!("failed to instantiate self_ty");
2237                        return false;
2238                    };
2239                    let ocx = ObligationCtxt::new(self);
2240                    let self_ty = ocx.register_infer_ok_obligations(ok);
2241                    if !ocx.try_evaluate_obligations().is_empty() {
2242                        debug!("failed to prove instantiate self_ty obligations");
2243                        return false;
2244                    }
2245
2246                    !self.resolve_vars_if_possible(self_ty).is_ty_var()
2247                });
2248                if constrained_opaque {
2249                    debug!("opaque type has been constrained");
2250                    return true;
2251                }
2252            }
2253        }
2254
2255        false
2256    }
2257
2258    /// Sometimes we get in a situation where we have multiple probes that are all impls of the
2259    /// same trait, but we don't know which impl to use. In this case, since in all cases the
2260    /// external interface of the method can be determined from the trait, it's ok not to decide.
2261    /// We can basically just collapse all of the probes for various impls into one where-clause
2262    /// probe. This will result in a pending obligation so when more type-info is available we can
2263    /// make the final decision.
2264    ///
2265    /// Example (`tests/ui/methods/method-two-trait-defer-resolution-1.rs`):
2266    ///
2267    /// ```ignore (illustrative)
2268    /// trait Foo { ... }
2269    /// impl Foo for Vec<i32> { ... }
2270    /// impl Foo for Vec<usize> { ... }
2271    /// ```
2272    ///
2273    /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
2274    /// use, so it's ok to just commit to "using the method from the trait Foo".
2275    fn collapse_candidates_to_trait_pick(
2276        &self,
2277        self_ty: Ty<'tcx>,
2278        probes: &[(&Candidate<'tcx>, ProbeResult)],
2279    ) -> Option<Pick<'tcx>> {
2280        // Do all probes correspond to the same trait?
2281        let container = probes[0].0.item.trait_container(self.tcx)?;
2282        for (p, _) in &probes[1..] {
2283            let p_container = p.item.trait_container(self.tcx)?;
2284            if p_container != container {
2285                return None;
2286            }
2287        }
2288
2289        let lint_ambiguous = match probes[0].0.kind {
2290            TraitCandidate(_, lint) => lint,
2291            _ => false,
2292        };
2293
2294        // FIXME: check the return type here somehow.
2295        // If so, just use this trait and call it a day.
2296        Some(Pick {
2297            item: probes[0].0.item,
2298            kind: TraitPick(lint_ambiguous),
2299            import_ids: probes[0].0.import_ids.clone(),
2300            autoderefs: 0,
2301            autoref_or_ptr_adjustment: None,
2302            self_ty,
2303            unstable_candidates: ::alloc::vec::Vec::new()vec![],
2304            receiver_steps: None,
2305            shadowed_candidates: ::alloc::vec::Vec::new()vec![],
2306        })
2307    }
2308
2309    /// Much like `collapse_candidates_to_trait_pick`, this method allows us to collapse
2310    /// multiple conflicting picks if there is one pick whose trait container is a subtrait
2311    /// of the trait containers of all of the other picks.
2312    ///
2313    /// This implements RFC #3624.
2314    fn collapse_candidates_to_subtrait_pick(
2315        &self,
2316        self_ty: Ty<'tcx>,
2317        probes: &[(&Candidate<'tcx>, ProbeResult)],
2318    ) -> Option<Pick<'tcx>> {
2319        let mut child_candidate = probes[0].0;
2320        let mut child_trait = child_candidate.item.trait_container(self.tcx)?;
2321        let mut supertraits: SsoHashSet<_> = supertrait_def_ids(self.tcx, child_trait).collect();
2322
2323        let mut remaining_candidates: Vec<_> = probes[1..].iter().map(|&(p, _)| p).collect();
2324        while !remaining_candidates.is_empty() {
2325            let mut made_progress = false;
2326            let mut next_round = ::alloc::vec::Vec::new()vec![];
2327
2328            for remaining_candidate in remaining_candidates {
2329                let remaining_trait = remaining_candidate.item.trait_container(self.tcx)?;
2330                if supertraits.contains(&remaining_trait) {
2331                    made_progress = true;
2332                    continue;
2333                }
2334
2335                // This pick is not a supertrait of the `child_pick`.
2336                // Check if it's a subtrait of the `child_pick`, instead.
2337                // If it is, then it must have been a subtrait of every
2338                // other pick we've eliminated at this point. It will
2339                // take over at this point.
2340                let remaining_trait_supertraits: SsoHashSet<_> =
2341                    supertrait_def_ids(self.tcx, remaining_trait).collect();
2342                if remaining_trait_supertraits.contains(&child_trait) {
2343                    child_candidate = remaining_candidate;
2344                    child_trait = remaining_trait;
2345                    supertraits = remaining_trait_supertraits;
2346                    made_progress = true;
2347                    continue;
2348                }
2349
2350                // `child_pick` is not a supertrait of this pick.
2351                // Don't bail here, since we may be comparing two supertraits
2352                // of a common subtrait. These two supertraits won't be related
2353                // at all, but we will pick them up next round when we find their
2354                // child as we continue iterating in this round.
2355                next_round.push(remaining_candidate);
2356            }
2357
2358            if made_progress {
2359                // If we've made progress, iterate again.
2360                remaining_candidates = next_round;
2361            } else {
2362                // Otherwise, we must have at least two candidates which
2363                // are not related to each other at all.
2364                return None;
2365            }
2366        }
2367
2368        let lint_ambiguous = match probes[0].0.kind {
2369            TraitCandidate(_, lint) => lint,
2370            _ => false,
2371        };
2372
2373        Some(Pick {
2374            item: child_candidate.item,
2375            kind: TraitPick(lint_ambiguous),
2376            import_ids: child_candidate.import_ids.clone(),
2377            autoderefs: 0,
2378            autoref_or_ptr_adjustment: None,
2379            self_ty,
2380            unstable_candidates: ::alloc::vec::Vec::new()vec![],
2381            shadowed_candidates: probes
2382                .iter()
2383                .map(|(c, _)| c.item)
2384                .filter(|item| item.def_id != child_candidate.item.def_id)
2385                .collect(),
2386            receiver_steps: None,
2387        })
2388    }
2389
2390    /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
2391    /// candidate method where the method name may have been misspelled. Similarly to other
2392    /// edit distance based suggestions, we provide at most one such suggestion.
2393    #[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(2393u32),
                                    ::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(&[]) })
                } 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:2397",
                                    "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(2397u32),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("probing for method names similar to {0:?}",
                                                                self.method_name) as &dyn 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 =
                                {
                                        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)
                                    }.or_else(||
                                        {
                                            applicable_close_candidates.iter().find(|cand|
                                                        self.matches_by_doc_alias(cand.def_id)).map(|cand|
                                                    cand.name())
                                        });
                            Ok(best_name.and_then(|best_name|
                                        {
                                            applicable_close_candidates.into_iter().find(|method|
                                                    method.name() == best_name)
                                        }))
                        }
                    })
        }
    }
}#[instrument(level = "debug", skip(self))]
2394    pub(crate) fn probe_for_similar_candidate(
2395        &mut self,
2396    ) -> Result<Option<ty::AssocItem>, MethodError<'tcx>> {
2397        debug!("probing for method names similar to {:?}", self.method_name);
2398
2399        self.probe(|_| {
2400            let mut pcx = ProbeContext::new(
2401                self.fcx,
2402                self.span,
2403                self.mode,
2404                self.method_name,
2405                self.return_type,
2406                self.orig_steps_var_values,
2407                self.steps,
2408                self.scope_expr_id,
2409                IsSuggestion(true),
2410            );
2411            pcx.allow_similar_names = true;
2412            pcx.assemble_inherent_candidates();
2413            pcx.assemble_extension_candidates_for_all_traits();
2414
2415            let method_names = pcx.candidate_method_names(|_| true);
2416            pcx.allow_similar_names = false;
2417            let applicable_close_candidates: Vec<ty::AssocItem> = method_names
2418                .iter()
2419                .filter_map(|&method_name| {
2420                    pcx.reset();
2421                    pcx.method_name = Some(method_name);
2422                    pcx.assemble_inherent_candidates();
2423                    pcx.assemble_extension_candidates_for_all_traits();
2424                    pcx.pick_core(&mut Vec::new()).and_then(|pick| pick.ok()).map(|pick| pick.item)
2425                })
2426                .collect();
2427
2428            if applicable_close_candidates.is_empty() {
2429                Ok(None)
2430            } else {
2431                let best_name = {
2432                    let names = applicable_close_candidates
2433                        .iter()
2434                        .map(|cand| cand.name())
2435                        .collect::<Vec<Symbol>>();
2436                    find_best_match_for_name_with_substrings(
2437                        &names,
2438                        self.method_name.unwrap().name,
2439                        None,
2440                    )
2441                }
2442                .or_else(|| {
2443                    applicable_close_candidates
2444                        .iter()
2445                        .find(|cand| self.matches_by_doc_alias(cand.def_id))
2446                        .map(|cand| cand.name())
2447                });
2448                Ok(best_name.and_then(|best_name| {
2449                    applicable_close_candidates
2450                        .into_iter()
2451                        .find(|method| method.name() == best_name)
2452                }))
2453            }
2454        })
2455    }
2456
2457    ///////////////////////////////////////////////////////////////////////////
2458    // MISCELLANY
2459    fn has_applicable_self(&self, item: &ty::AssocItem) -> bool {
2460        // "Fast track" -- check for usage of sugar when in method call
2461        // mode.
2462        //
2463        // In Path mode (i.e., resolving a value like `T::next`), consider any
2464        // associated value (i.e., methods, constants) but not types.
2465        match self.mode {
2466            Mode::MethodCall => item.is_method(),
2467            Mode::Path => match item.kind {
2468                ty::AssocKind::Type { .. } => false,
2469                ty::AssocKind::Fn { .. } | ty::AssocKind::Const { .. } => true,
2470            },
2471        }
2472        // FIXME -- check for types that deref to `Self`,
2473        // like `Rc<Self>` and so on.
2474        //
2475        // Note also that the current code will break if this type
2476        // includes any of the type parameters defined on the method
2477        // -- but this could be overcome.
2478    }
2479
2480    fn record_static_candidate(&self, source: CandidateSource) {
2481        self.static_candidates.borrow_mut().push(source);
2482    }
2483
2484    #[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(2484u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["item", "impl_ty",
                                                    "args"], ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn 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);
                (sig.inputs()[0], Some(sig.output()))
            } else { (impl_ty, None) }
        }
    }
}#[instrument(level = "debug", skip(self))]
2485    fn xform_self_ty(
2486        &self,
2487        item: ty::AssocItem,
2488        impl_ty: Ty<'tcx>,
2489        args: GenericArgsRef<'tcx>,
2490    ) -> (Ty<'tcx>, Option<Ty<'tcx>>) {
2491        if item.is_fn() && self.mode == Mode::MethodCall {
2492            let sig = self.xform_method_sig(item.def_id, args);
2493            (sig.inputs()[0], Some(sig.output()))
2494        } else {
2495            (impl_ty, None)
2496        }
2497    }
2498
2499    #[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(2499u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["method", "args"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn 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:2502",
                                    "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(2502u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&["fn_sig"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&fn_sig) as
                                                        &dyn 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)
                } 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)
                };
            self.tcx.instantiate_bound_regions_with_erased(xform_fn_sig)
        }
    }
}#[instrument(level = "debug", skip(self))]
2500    fn xform_method_sig(&self, method: DefId, args: GenericArgsRef<'tcx>) -> ty::FnSig<'tcx> {
2501        let fn_sig = self.tcx.fn_sig(method);
2502        debug!(?fn_sig);
2503
2504        assert!(!args.has_escaping_bound_vars());
2505
2506        // It is possible for type parameters or early-bound lifetimes
2507        // to appear in the signature of `self`. The generic parameters
2508        // we are given do not include type/lifetime parameters for the
2509        // method yet. So create fresh variables here for those too,
2510        // if there are any.
2511        let generics = self.tcx.generics_of(method);
2512        assert_eq!(args.len(), generics.parent_count);
2513
2514        let xform_fn_sig = if generics.is_own_empty() {
2515            fn_sig.instantiate(self.tcx, args)
2516        } else {
2517            let args = GenericArgs::for_item(self.tcx, method, |param, _| {
2518                let i = param.index as usize;
2519                if i < args.len() {
2520                    args[i]
2521                } else {
2522                    match param.kind {
2523                        GenericParamDefKind::Lifetime => {
2524                            // In general, during probe we erase regions.
2525                            self.tcx.lifetimes.re_erased.into()
2526                        }
2527                        GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
2528                            self.var_for_def(self.span, param)
2529                        }
2530                    }
2531                }
2532            });
2533            fn_sig.instantiate(self.tcx, args)
2534        };
2535
2536        self.tcx.instantiate_bound_regions_with_erased(xform_fn_sig)
2537    }
2538
2539    /// Determine if the given associated item type is relevant in the current context.
2540    fn is_relevant_kind_for_mode(&self, kind: ty::AssocKind) -> bool {
2541        match (self.mode, kind) {
2542            (Mode::MethodCall, ty::AssocKind::Fn { .. }) => true,
2543            (Mode::Path, ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. }) => true,
2544            _ => false,
2545        }
2546    }
2547
2548    /// Determine if the associated item with the given DefId matches
2549    /// the desired name via a doc alias.
2550    fn matches_by_doc_alias(&self, def_id: DefId) -> bool {
2551        let Some(method) = self.method_name else {
2552            return false;
2553        };
2554        let Some(local_def_id) = def_id.as_local() else {
2555            return false;
2556        };
2557        let hir_id = self.fcx.tcx.local_def_id_to_hir_id(local_def_id);
2558        let attrs = self.fcx.tcx.hir_attrs(hir_id);
2559
2560        if let Some(d) = {
    'done:
        {
        for i in attrs {
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(AttributeKind::Doc(d)) => {
                    break 'done Some(d);
                }
                _ => {}
            }
        }
        None
    }
}find_attr!(attrs, AttributeKind::Doc(d) => d)
2561            && d.aliases.contains_key(&method.name)
2562        {
2563            return true;
2564        }
2565
2566        for attr in attrs {
2567            if attr.has_name(sym::rustc_confusables) {
2568                let Some(confusables) = attr.meta_item_list() else {
2569                    continue;
2570                };
2571                // #[rustc_confusables("foo", "bar"))]
2572                for n in confusables {
2573                    if let Some(lit) = n.lit()
2574                        && method.name == lit.symbol
2575                    {
2576                        return true;
2577                    }
2578                }
2579            }
2580        }
2581        false
2582    }
2583
2584    /// Finds the method with the appropriate name (or return type, as the case may be). If
2585    /// `allow_similar_names` is set, find methods with close-matching names.
2586    // The length of the returned iterator is nearly always 0 or 1 and this
2587    // method is fairly hot.
2588    fn impl_or_trait_item(&self, def_id: DefId) -> SmallVec<[ty::AssocItem; 1]> {
2589        if let Some(name) = self.method_name {
2590            if self.allow_similar_names {
2591                let max_dist = max(name.as_str().len(), 3) / 3;
2592                self.tcx
2593                    .associated_items(def_id)
2594                    .in_definition_order()
2595                    .filter(|x| {
2596                        if !self.is_relevant_kind_for_mode(x.kind) {
2597                            return false;
2598                        }
2599                        if let Some(d) = edit_distance_with_substrings(
2600                            name.as_str(),
2601                            x.name().as_str(),
2602                            max_dist,
2603                        ) {
2604                            return d > 0;
2605                        }
2606                        self.matches_by_doc_alias(x.def_id)
2607                    })
2608                    .copied()
2609                    .collect()
2610            } else {
2611                self.fcx
2612                    .associated_value(def_id, name)
2613                    .filter(|x| self.is_relevant_kind_for_mode(x.kind))
2614                    .map_or_else(SmallVec::new, |x| SmallVec::from_buf([x]))
2615            }
2616        } else {
2617            self.tcx
2618                .associated_items(def_id)
2619                .in_definition_order()
2620                .filter(|x| self.is_relevant_kind_for_mode(x.kind))
2621                .copied()
2622                .collect()
2623        }
2624    }
2625}
2626
2627impl<'tcx> Candidate<'tcx> {
2628    fn to_unadjusted_pick(
2629        &self,
2630        self_ty: Ty<'tcx>,
2631        unstable_candidates: Vec<(Candidate<'tcx>, Symbol)>,
2632    ) -> Pick<'tcx> {
2633        Pick {
2634            item: self.item,
2635            kind: match self.kind {
2636                InherentImplCandidate { .. } => InherentImplPick,
2637                ObjectCandidate(_) => ObjectPick,
2638                TraitCandidate(_, lint_ambiguous) => TraitPick(lint_ambiguous),
2639                WhereClauseCandidate(trait_ref) => {
2640                    // Only trait derived from where-clauses should
2641                    // appear here, so they should not contain any
2642                    // inference variables or other artifacts. This
2643                    // means they are safe to put into the
2644                    // `WhereClausePick`.
2645                    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!(
2646                        !trait_ref.skip_binder().args.has_infer()
2647                            && !trait_ref.skip_binder().args.has_placeholders()
2648                    );
2649
2650                    WhereClausePick(trait_ref)
2651                }
2652            },
2653            import_ids: self.import_ids.clone(),
2654            autoderefs: 0,
2655            autoref_or_ptr_adjustment: None,
2656            self_ty,
2657            unstable_candidates,
2658            receiver_steps: match self.kind {
2659                InherentImplCandidate { receiver_steps, .. } => Some(receiver_steps),
2660                _ => None,
2661            },
2662            shadowed_candidates: ::alloc::vec::Vec::new()vec![],
2663        }
2664    }
2665}