Skip to main content

rustc_hir_typeck/method/
probe.rs

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