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