Skip to main content

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