Skip to main content

rustc_hir_typeck/method/
probe.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut duplicates = FxHashSet::default();
            let opt_applicable_traits =
                self.tcx.in_scope_traits(self.scope_expr_id);
            if let Some(applicable_traits) = opt_applicable_traits {
                for trait_candidate in applicable_traits.iter() {
                    let trait_did = trait_candidate.def_id;
                    if duplicates.insert((trait_did,
                                trait_candidate.lint_ambiguous)) {
                        self.assemble_extension_candidates_for_trait(&trait_candidate.import_ids,
                            trait_did, trait_candidate.lint_ambiguous);
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1093    fn assemble_extension_candidates_for_traits_in_scope(&mut self) {
1094        let mut duplicates = FxHashSet::default();
1095        let opt_applicable_traits = self.tcx.in_scope_traits(self.scope_expr_id);
1096        if let Some(applicable_traits) = opt_applicable_traits {
1097            for trait_candidate in applicable_traits.iter() {
1098                let trait_did = trait_candidate.def_id;
1099                // If we have the same trait in scope but one of them is ambiguous and the other
1100                // is not, we should treat them differently and then handle them later on.
1101                if duplicates.insert((trait_did, trait_candidate.lint_ambiguous)) {
1102                    self.assemble_extension_candidates_for_trait(
1103                        &trait_candidate.import_ids,
1104                        trait_did,
1105                        trait_candidate.lint_ambiguous,
1106                    );
1107                }
1108            }
1109        }
1110    }
1111
1112    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1112u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<PickResult<'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.tcx.features().pin_ergonomics() { return None; }
            let inner_ty =
                match self_ty.kind() {
                    ty::Adt(def, args) if
                        self.tcx.is_lang_item(def.did(), LangItem::Pin) => {
                        match args[0].expect_ty().kind() {
                            ty::Ref(_, ty, hir::Mutability::Mut) => *ty,
                            _ => { return None; }
                        }
                    }
                    _ => return None,
                };
            let region = self.tcx.lifetimes.re_erased;
            let autopin_ty =
                Ty::new_pinned_ref(self.tcx, region, inner_ty,
                    hir::Mutability::Not);
            self.pick_method(autopin_ty, instantiate_self_ty_obligations,
                    pick_diag_hints,
                    None).map(|r|
                    {
                        r.map(|mut pick|
                                {
                                    pick.autoderefs = step.autoderefs;
                                    pick.autoref_or_ptr_adjustment =
                                        Some(AutorefOrPtrAdjustment::ReborrowPin(hir::Mutability::Not));
                                    pick
                                })
                    })
        }
    }
}#[instrument(level = "debug", skip(self, step, pick_diag_hints))]
1658    fn pick_reborrow_pin_method(
1659        &self,
1660        step: &CandidateStep<'tcx>,
1661        self_ty: Ty<'tcx>,
1662        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1663        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1664    ) -> Option<PickResult<'tcx>> {
1665        if !self.tcx.features().pin_ergonomics() {
1666            return None;
1667        }
1668
1669        // make sure self is a Pin<&mut T>
1670        let inner_ty = match self_ty.kind() {
1671            ty::Adt(def, args) if self.tcx.is_lang_item(def.did(), LangItem::Pin) => {
1672                match args[0].expect_ty().kind() {
1673                    ty::Ref(_, ty, hir::Mutability::Mut) => *ty,
1674                    _ => {
1675                        return None;
1676                    }
1677                }
1678            }
1679            _ => return None,
1680        };
1681
1682        let region = self.tcx.lifetimes.re_erased;
1683        let autopin_ty = Ty::new_pinned_ref(self.tcx, region, inner_ty, hir::Mutability::Not);
1684        self.pick_method(autopin_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1685            |r| {
1686                r.map(|mut pick| {
1687                    pick.autoderefs = step.autoderefs;
1688                    pick.autoref_or_ptr_adjustment =
1689                        Some(AutorefOrPtrAdjustment::ReborrowPin(hir::Mutability::Not));
1690                    pick
1691                })
1692            },
1693        )
1694    }
1695
1696    /// If `self_ty` is `*mut T` then this picks `*const T` methods. The reason why we have a
1697    /// special case for this is because going from `*mut T` to `*const T` with autoderefs and
1698    /// autorefs would require dereferencing the pointer, which is not safe.
1699    fn pick_const_ptr_method(
1700        &self,
1701        step: &CandidateStep<'tcx>,
1702        self_ty: Ty<'tcx>,
1703        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1704        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1705    ) -> Option<PickResult<'tcx>> {
1706        // Don't convert an unsized reference to ptr
1707        if step.unsize {
1708            return None;
1709        }
1710
1711        let &ty::RawPtr(ty, hir::Mutability::Mut) = self_ty.kind() else {
1712            return None;
1713        };
1714
1715        let const_ptr_ty = Ty::new_imm_ptr(self.tcx, ty);
1716        self.pick_method(const_ptr_ty, instantiate_self_ty_obligations, pick_diag_hints, None).map(
1717            |r| {
1718                r.map(|mut pick| {
1719                    pick.autoderefs = step.autoderefs;
1720                    pick.autoref_or_ptr_adjustment = Some(AutorefOrPtrAdjustment::ToConstPtr);
1721                    pick
1722                })
1723            },
1724        )
1725    }
1726
1727    fn pick_method(
1728        &self,
1729        self_ty: Ty<'tcx>,
1730        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1731        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1732        pick_constraints: Option<&PickConstraintsForShadowed>,
1733    ) -> Option<PickResult<'tcx>> {
1734        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:1734",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1734u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pick_method(self_ty={0})",
                                                    self.ty_to_string(self_ty)) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("pick_method(self_ty={})", self.ty_to_string(self_ty));
1735
1736        for (kind, candidates) in
1737            [("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)]
1738        {
1739            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:1739",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1739u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("searching {0} candidates",
                                                    kind) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("searching {} candidates", kind);
1740            let res = self.consider_candidates(
1741                self_ty,
1742                instantiate_self_ty_obligations,
1743                candidates,
1744                pick_diag_hints,
1745                pick_constraints,
1746            );
1747            if let Some(pick) = res {
1748                return Some(pick);
1749            }
1750        }
1751
1752        if self.private_candidate.get().is_none() {
1753            if let Some(Ok(pick)) = self.consider_candidates(
1754                self_ty,
1755                instantiate_self_ty_obligations,
1756                &self.private_candidates,
1757                &mut PickDiagHints {
1758                    unstable_candidates: None,
1759                    unsatisfied_predicates: &mut ::alloc::vec::Vec::new()vec![],
1760                },
1761                None,
1762            ) {
1763                self.private_candidate.set(Some((pick.item.as_def_kind(), pick.item.def_id)));
1764            }
1765        }
1766        None
1767    }
1768
1769    fn consider_candidates(
1770        &self,
1771        self_ty: Ty<'tcx>,
1772        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
1773        candidates: &[Candidate<'tcx>],
1774        pick_diag_hints: &mut PickDiagHints<'_, 'tcx>,
1775        pick_constraints: Option<&PickConstraintsForShadowed>,
1776    ) -> Option<PickResult<'tcx>> {
1777        let mut applicable_candidates: Vec<_> = candidates
1778            .iter()
1779            .filter(|candidate| {
1780                pick_constraints
1781                    .map(|pick_constraints| pick_constraints.candidate_may_shadow(&candidate))
1782                    .unwrap_or(true)
1783            })
1784            .map(|probe| {
1785                (
1786                    probe,
1787                    self.consider_probe(
1788                        self_ty,
1789                        instantiate_self_ty_obligations,
1790                        probe,
1791                        &mut pick_diag_hints.unsatisfied_predicates,
1792                    ),
1793                )
1794            })
1795            .filter(|&(_, status)| status != ProbeResult::NoMatch)
1796            .collect();
1797
1798        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:1798",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(1798u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("applicable_candidates: {0:?}",
                                                    applicable_candidates) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("applicable_candidates: {:?}", applicable_candidates);
1799
1800        if applicable_candidates.len() > 1 {
1801            if let Some(pick) =
1802                self.collapse_candidates_to_trait_pick(self_ty, &applicable_candidates)
1803            {
1804                return Some(Ok(pick));
1805            }
1806        }
1807
1808        if let Some(uc) = &mut pick_diag_hints.unstable_candidates {
1809            applicable_candidates.retain(|&(candidate, _)| {
1810                if let stability::EvalResult::Deny { feature, .. } =
1811                    self.tcx.eval_stability(candidate.item.def_id, None, self.span, None)
1812                {
1813                    uc.push((candidate.clone(), feature));
1814                    return false;
1815                }
1816                true
1817            });
1818        }
1819
1820        if applicable_candidates.len() > 1 {
1821            // We collapse to a subtrait pick *after* filtering unstable candidates
1822            // to make sure we don't prefer a unstable subtrait method over a stable
1823            // supertrait method.
1824            if self.tcx.features().supertrait_item_shadowing() {
1825                if let Some(pick) =
1826                    self.collapse_candidates_to_subtrait_pick(self_ty, &applicable_candidates)
1827                {
1828                    return Some(Ok(pick));
1829                }
1830            }
1831
1832            let sources =
1833                applicable_candidates.iter().map(|p| self.candidate_source(p.0, self_ty)).collect();
1834            return Some(Err(MethodError::Ambiguity(sources)));
1835        }
1836
1837        applicable_candidates.pop().map(|(probe, status)| match status {
1838            ProbeResult::Match => Ok(probe.to_unadjusted_pick(
1839                self_ty,
1840                pick_diag_hints.unstable_candidates.clone().unwrap_or_default(),
1841            )),
1842            ProbeResult::NoMatch | ProbeResult::BadReturnType => Err(MethodError::BadReturnType),
1843        })
1844    }
1845}
1846
1847impl<'tcx> Pick<'tcx> {
1848    /// In case there were unstable name collisions, emit them as a lint.
1849    /// Checks whether two picks do not refer to the same trait item for the same `Self` type.
1850    /// Only useful for comparisons of picks in order to improve diagnostics.
1851    /// Do not use for type checking.
1852    pub(crate) fn differs_from(&self, other: &Self) -> bool {
1853        let Self {
1854            item: AssocItem { def_id, kind: _, container: _ },
1855            kind: _,
1856            import_ids: _,
1857            autoderefs: _,
1858            autoref_or_ptr_adjustment: _,
1859            self_ty,
1860            unstable_candidates: _,
1861            receiver_steps: _,
1862            shadowed_candidates: _,
1863        } = *self;
1864        self_ty != other.self_ty || def_id != other.item.def_id
1865    }
1866
1867    /// In case there were unstable name collisions, emit them as a lint.
1868    pub(crate) fn maybe_emit_unstable_name_collision_hint(
1869        &self,
1870        tcx: TyCtxt<'tcx>,
1871        span: Span,
1872        scope_expr_id: HirId,
1873    ) {
1874        struct ItemMaybeBeAddedToStd<'a, 'tcx> {
1875            this: &'a Pick<'tcx>,
1876            tcx: TyCtxt<'tcx>,
1877            span: Span,
1878        }
1879
1880        impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for ItemMaybeBeAddedToStd<'b, 'tcx> {
1881            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1882                let Self { this, tcx, span } = self;
1883                let def_kind = this.item.as_def_kind();
1884                let mut lint = Diag::new(
1885                    dcx,
1886                    level,
1887                    ::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!(
1888                        "{} {} with this name may be added to the standard library in the future",
1889                        tcx.def_kind_descr_article(def_kind, this.item.def_id),
1890                        tcx.def_kind_descr(def_kind, this.item.def_id),
1891                    ),
1892                );
1893
1894                match (this.item.kind, this.item.container) {
1895                    (ty::AssocKind::Fn { .. }, _) => {
1896                        // FIXME: This should be a `span_suggestion` instead of `help`
1897                        // However `this.span` only
1898                        // highlights the method name, so we can't use it. Also consider reusing
1899                        // the code from `report_method_error()`.
1900                        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!(
1901                            "call with fully qualified syntax `{}(...)` to keep using the current \
1902                                 method",
1903                            tcx.def_path_str(this.item.def_id),
1904                        ));
1905                    }
1906                    (ty::AssocKind::Const { name, .. }, ty::AssocContainer::Trait) => {
1907                        let def_id = this.item.container_id(tcx);
1908                        lint.span_suggestion(
1909                            span,
1910                            "use the fully qualified path to the associated const",
1911                            ::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),
1912                            Applicability::MachineApplicable,
1913                        );
1914                    }
1915                    _ => {}
1916                }
1917                tcx.disabled_nightly_features(
1918                    &mut lint,
1919                    this.unstable_candidates.iter().map(|(candidate, feature)| {
1920                        (::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)
1921                    }),
1922                );
1923                lint
1924            }
1925        }
1926
1927        if self.unstable_candidates.is_empty() {
1928            return;
1929        }
1930        tcx.emit_node_span_lint(
1931            UNSTABLE_NAME_COLLISIONS,
1932            scope_expr_id,
1933            span,
1934            ItemMaybeBeAddedToStd { this: self, tcx, span },
1935        );
1936    }
1937}
1938
1939impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
1940    fn select_trait_candidate_for_diagnostics(
1941        &self,
1942        trait_ref: ty::TraitRef<'tcx>,
1943    ) -> traits::SelectionResult<'tcx, traits::Selection<'tcx>> {
1944        let obligation =
1945            traits::Obligation::new(self.tcx, self.misc(self.span), self.param_env, trait_ref);
1946        let candidate = traits::SelectionContext::new(self).select(&obligation);
1947        if let Ok(Some(traits::ImplSource::UserDefined(impl_source_user_defined_data))) = &candidate
1948            && self.infcx.tcx.do_not_recommend_impl(impl_source_user_defined_data.impl_def_id)
1949        {
1950            return Err(traits::SelectionError::Unimplemented);
1951        }
1952        candidate
1953    }
1954
1955    /// Used for ambiguous method call error reporting. Uses probing that throws away the result internally,
1956    /// so do not use to make a decision that may lead to a successful compilation.
1957    fn candidate_source(&self, candidate: &Candidate<'tcx>, self_ty: Ty<'tcx>) -> CandidateSource {
1958        match candidate.kind {
1959            InherentImplCandidate { .. } => {
1960                CandidateSource::Impl(candidate.item.container_id(self.tcx))
1961            }
1962            ObjectCandidate(_) | WhereClauseCandidate(_) => {
1963                CandidateSource::Trait(candidate.item.container_id(self.tcx))
1964            }
1965            TraitCandidate { trait_ref, is_ambiguously_imported: _ } => self.probe(|_| {
1966                let trait_ref = self.instantiate_binder_with_fresh_vars(
1967                    self.span,
1968                    BoundRegionConversionTime::FnCall,
1969                    trait_ref,
1970                );
1971                let (xform_self_ty, _) =
1972                    self.xform_self_ty(candidate.item, trait_ref.self_ty(), trait_ref.args);
1973                // Guide the trait selection to show impls that have methods whose type matches
1974                // up with the `self` parameter of the method.
1975                let _ = self.at(&ObligationCause::dummy(), self.param_env).sup(
1976                    DefineOpaqueTypes::Yes,
1977                    xform_self_ty,
1978                    self_ty,
1979                );
1980                match self.select_trait_candidate_for_diagnostics(trait_ref) {
1981                    Ok(Some(traits::ImplSource::UserDefined(ref impl_data))) => {
1982                        // If only a single impl matches, make the error message point
1983                        // to that impl.
1984                        CandidateSource::Impl(impl_data.impl_def_id)
1985                    }
1986                    _ => CandidateSource::Trait(candidate.item.container_id(self.tcx)),
1987                }
1988            }),
1989        }
1990    }
1991
1992    fn candidate_source_from_pick(&self, pick: &Pick<'tcx>) -> CandidateSource {
1993        match pick.kind {
1994            InherentImplPick => CandidateSource::Impl(pick.item.container_id(self.tcx)),
1995            ObjectPick | WhereClausePick(_) | TraitPick { .. } => {
1996                CandidateSource::Trait(pick.item.container_id(self.tcx))
1997            }
1998        }
1999    }
2000
2001    fn consider_probe(
2002        &self,
2003        self_ty: Ty<'tcx>,
2004        instantiate_self_ty_obligations: &[PredicateObligation<'tcx>],
2005        probe: &Candidate<'tcx>,
2006        possibly_unsatisfied_predicates: &mut UnsatisfiedPredicates<'tcx>,
2007    ) -> ProbeResult {
2008        self.probe(|snapshot| {
2009            let outer_universe = self.universe();
2010
2011            let mut result = ProbeResult::Match;
2012            let cause = &self.misc(self.span);
2013            let ocx = ObligationCtxt::new_with_diagnostics(self);
2014
2015            // Subtle: we're not *really* instantiating the current self type while
2016            // probing, but instead fully recompute the autoderef steps once we've got
2017            // a final `Pick`. We can't nicely handle these obligations outside of a probe.
2018            //
2019            // We simply handle them for each candidate here for now. That's kinda scuffed
2020            // and ideally we just put them into the `FnCtxt` right away. We need to consider
2021            // them to deal with defining uses in `method_autoderef_steps`.
2022            if self.next_trait_solver() {
2023                ocx.register_obligations(instantiate_self_ty_obligations.iter().cloned());
2024                let errors = ocx.try_evaluate_obligations();
2025                if !errors.no_errors() {
2026                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected autoderef error {0:?}", errors)));
};unreachable!("unexpected autoderef error {errors:?}");
2027                }
2028            }
2029
2030            let mut trait_predicate = None;
2031            let (mut xform_self_ty, mut xform_ret_ty);
2032
2033            match probe.kind {
2034                InherentImplCandidate { impl_def_id, .. } => {
2035                    let impl_args = self.fresh_args_for_item(self.span, impl_def_id);
2036                    let impl_ty = self
2037                        .tcx
2038                        .type_of(impl_def_id)
2039                        .instantiate(self.tcx, impl_args)
2040                        .skip_norm_wip();
2041                    (xform_self_ty, xform_ret_ty) =
2042                        self.xform_self_ty(probe.item, impl_ty, impl_args);
2043                    xform_self_ty =
2044                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_self_ty));
2045                    match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
2046                    {
2047                        Ok(()) => {}
2048                        Err(err) => {
2049                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2049",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2049u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> cannot relate self-types {0:?}",
                                                    err) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> cannot relate self-types {:?}", err);
2050                            return ProbeResult::NoMatch;
2051                        }
2052                    }
2053                    // FIXME: Weirdly, we normalize the ret ty in this candidate, but no other candidates.
2054                    xform_ret_ty =
2055                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_ret_ty));
2056                    // Check whether the impl imposes obligations we have to worry about.
2057                    let impl_def_id = probe.item.container_id(self.tcx);
2058                    let impl_bounds =
2059                        self.tcx.clauses_of(impl_def_id).instantiate(self.tcx, impl_args);
2060                    // Convert the bounds into obligations.
2061                    ocx.register_obligations(traits::predicates_for_generics(
2062                        |idx, span| {
2063                            let code = ObligationCauseCode::WhereClauseInExpr(
2064                                impl_def_id,
2065                                span,
2066                                self.scope_expr_id,
2067                                idx,
2068                            );
2069                            self.cause(self.span, code)
2070                        },
2071                        |clause| ocx.normalize(cause, self.param_env, clause),
2072                        self.param_env,
2073                        impl_bounds,
2074                    ));
2075                }
2076                TraitCandidate { trait_ref: poly_trait_ref, is_ambiguously_imported: _ } => {
2077                    // Some trait methods are excluded for arrays before 2021.
2078                    // (`array.into_iter()` wants a slice iterator for compatibility.)
2079                    if let Some(method_name) = self.method_name {
2080                        if self_ty.is_array() && !method_name.span.at_least_rust_2021() {
2081                            let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
2082                            if trait_def.skip_array_during_method_dispatch {
2083                                return ProbeResult::NoMatch;
2084                            }
2085                        }
2086
2087                        // Some trait methods are excluded for boxed slices before 2024.
2088                        // (`boxed_slice.into_iter()` wants a slice iterator for compatibility.)
2089                        if self_ty.boxed_ty().is_some_and(Ty::is_slice)
2090                            && !method_name.span.at_least_rust_2024()
2091                        {
2092                            let trait_def = self.tcx.trait_def(poly_trait_ref.def_id());
2093                            if trait_def.skip_boxed_slice_during_method_dispatch {
2094                                return ProbeResult::NoMatch;
2095                            }
2096                        }
2097                    }
2098
2099                    let trait_ref = self.instantiate_binder_with_fresh_vars(
2100                        self.span,
2101                        BoundRegionConversionTime::FnCall,
2102                        poly_trait_ref,
2103                    );
2104                    let trait_ref =
2105                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(trait_ref));
2106                    (xform_self_ty, xform_ret_ty) =
2107                        self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
2108                    xform_self_ty =
2109                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_self_ty));
2110                    match self_ty.kind() {
2111                        // HACK: opaque types will match anything for which their bounds hold.
2112                        // Thus we need to prevent them from trying to match the `&_` autoref
2113                        // candidates that get created for `&self` trait methods.
2114                        &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. })
2115                            if !self.next_trait_solver()
2116                                && self.infcx.can_define_opaque_ty(def_id)
2117                                && !xform_self_ty.is_ty_var() =>
2118                        {
2119                            return ProbeResult::NoMatch;
2120                        }
2121                        _ => match ocx.relate(
2122                            cause,
2123                            self.param_env,
2124                            self.variance(),
2125                            self_ty,
2126                            xform_self_ty,
2127                        ) {
2128                            Ok(()) => {}
2129                            Err(err) => {
2130                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2130",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2130u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> cannot relate self-types {0:?}",
                                                    err) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> cannot relate self-types {:?}", err);
2131                                return ProbeResult::NoMatch;
2132                            }
2133                        },
2134                    }
2135                    let obligation = traits::Obligation::new(
2136                        self.tcx,
2137                        cause.clone(),
2138                        self.param_env,
2139                        ty::Binder::dummy(trait_ref),
2140                    );
2141
2142                    // We only need this hack to deal with fatal overflow in the old solver.
2143                    if self.infcx.next_trait_solver() || self.infcx.predicate_may_hold(&obligation)
2144                    {
2145                        ocx.register_obligation(obligation);
2146                    } else {
2147                        result = ProbeResult::NoMatch;
2148                        if let Ok(Some(candidate)) =
2149                            self.select_trait_candidate_for_diagnostics(trait_ref)
2150                        {
2151                            for nested_obligation in candidate.nested_obligations() {
2152                                if !self.infcx.predicate_may_hold(&nested_obligation) {
2153                                    possibly_unsatisfied_predicates.push((
2154                                        self.deeply_resolve_ignoring_regions(
2155                                            nested_obligation.predicate,
2156                                        ),
2157                                        Some(
2158                                            self.deeply_resolve_ignoring_regions(
2159                                                obligation.predicate,
2160                                            ),
2161                                        ),
2162                                        Some(nested_obligation.cause),
2163                                    ));
2164                                }
2165                            }
2166                        }
2167                    }
2168
2169                    trait_predicate = Some(trait_ref.upcast(self.tcx));
2170                }
2171                ObjectCandidate(poly_trait_ref) | WhereClauseCandidate(poly_trait_ref) => {
2172                    let trait_ref = self.instantiate_binder_with_fresh_vars(
2173                        self.span,
2174                        BoundRegionConversionTime::FnCall,
2175                        poly_trait_ref,
2176                    );
2177                    (xform_self_ty, xform_ret_ty) =
2178                        self.xform_self_ty(probe.item, trait_ref.self_ty(), trait_ref.args);
2179
2180                    if #[allow(non_exhaustive_omitted_patterns)] match probe.kind {
    WhereClauseCandidate(_) => true,
    _ => false,
}matches!(probe.kind, WhereClauseCandidate(_)) {
2181                        // `WhereClauseCandidate` requires that the self type is a param,
2182                        // because it has special behavior with candidate preference as an
2183                        // inherent pick.
2184                        let ty = ocx.normalize(
2185                            cause,
2186                            self.param_env,
2187                            Unnormalized::new_wip(trait_ref.self_ty()),
2188                        );
2189                        if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Param(_) => true,
    _ => false,
}matches!(ty.kind(), ty::Param(_)) {
2190                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2190",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2190u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> not a param ty: {0:?}",
                                                    xform_self_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> not a param ty: {xform_self_ty:?}");
2191                            return ProbeResult::NoMatch;
2192                        }
2193                    }
2194
2195                    xform_self_ty =
2196                        ocx.normalize(cause, self.param_env, Unnormalized::new_wip(xform_self_ty));
2197                    match ocx.relate(cause, self.param_env, self.variance(), self_ty, xform_self_ty)
2198                    {
2199                        Ok(()) => {}
2200                        Err(err) => {
2201                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2201",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2201u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("--> cannot relate self-types {0:?}",
                                                    err) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("--> cannot relate self-types {:?}", err);
2202                            return ProbeResult::NoMatch;
2203                        }
2204                    }
2205                }
2206            }
2207
2208            // Evaluate those obligations to see if they might possibly hold.
2209            for error in ocx.try_evaluate_obligations() {
2210                result = ProbeResult::NoMatch;
2211                let nested_predicate =
2212                    self.deeply_resolve_ignoring_regions(error.obligation.predicate);
2213                if let Some(trait_predicate) = trait_predicate
2214                    && nested_predicate == self.deeply_resolve_ignoring_regions(trait_predicate)
2215                {
2216                    // Don't report possibly unsatisfied predicates if the root
2217                    // trait obligation from a `TraitCandidate` is unsatisfied.
2218                    // That just means the candidate doesn't hold.
2219                } else {
2220                    possibly_unsatisfied_predicates.push((
2221                        nested_predicate,
2222                        Some(self.deeply_resolve_ignoring_regions(error.root_obligation.predicate))
2223                            .filter(|root_predicate| *root_predicate != nested_predicate),
2224                        Some(error.obligation.cause),
2225                    ));
2226                }
2227            }
2228
2229            if let ProbeResult::Match = result
2230                && let Some(return_ty) = self.return_type
2231                && let Some(mut xform_ret_ty) = xform_ret_ty
2232            {
2233                // `xform_ret_ty` has only been normalized for `InherentImplCandidate`.
2234                // We don't normalize the other candidates for perf/backwards-compat reasons...
2235                // but `self.return_type` is only set on the diagnostic-path, so we
2236                // should be okay doing it here.
2237                if !#[allow(non_exhaustive_omitted_patterns)] match probe.kind {
    InherentImplCandidate { .. } => true,
    _ => false,
}matches!(probe.kind, InherentImplCandidate { .. }) {
2238                    xform_ret_ty =
2239                        ocx.normalize(&cause, self.param_env, Unnormalized::new_wip(xform_ret_ty));
2240                }
2241
2242                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2242",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2242u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("comparing return_ty {0:?} with xform ret ty {1:?}",
                                                    return_ty, xform_ret_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("comparing return_ty {:?} with xform ret ty {:?}", return_ty, xform_ret_ty);
2243                match ocx.relate(cause, self.param_env, self.variance(), xform_ret_ty, return_ty) {
2244                    Ok(()) => {}
2245                    Err(_) => {
2246                        result = ProbeResult::BadReturnType;
2247                    }
2248                }
2249
2250                // Evaluate those obligations to see if they might possibly hold.
2251                for error in ocx.try_evaluate_obligations() {
2252                    result = ProbeResult::NoMatch;
2253                    possibly_unsatisfied_predicates.push((
2254                        error.obligation.predicate,
2255                        Some(error.root_obligation.predicate)
2256                            .filter(|predicate| *predicate != error.obligation.predicate),
2257                        Some(error.root_obligation.cause),
2258                    ));
2259                }
2260            }
2261
2262            if self.infcx.next_trait_solver() {
2263                if self.should_reject_candidate_due_to_opaque_treated_as_rigid(trait_predicate) {
2264                    result = ProbeResult::NoMatch;
2265                }
2266            }
2267
2268            // Previously, method probe used `evaluate_predicate` to determine if a predicate
2269            // was impossible to satisfy. This did a leak check, so we must also do a leak
2270            // check here to prevent backwards-incompatible ambiguity being introduced. See
2271            // `tests/ui/methods/leak-check-disquality.rs` for a simple example of when this
2272            // may happen.
2273            if let Err(_) = self.leak_check(outer_universe, Some(snapshot)) {
2274                result = ProbeResult::NoMatch;
2275            }
2276
2277            result
2278        })
2279    }
2280
2281    /// Trait candidates for not-yet-defined opaque types are a somewhat hacky.
2282    ///
2283    /// We want to only accept trait methods if they were hold even if the
2284    /// opaque types were rigid. To handle this, we both check that for trait
2285    /// candidates the goal were to hold even when treating opaques as rigid,
2286    /// see [OpaqueTypesJank](rustc_trait_selection::solve::OpaqueTypesJank).
2287    ///
2288    /// We also check that all opaque types encountered as self types in the
2289    /// autoderef chain don't get constrained when applying the candidate.
2290    /// Importantly, this also handles calling methods taking `&self` on
2291    /// `impl Trait` to reject the "by-self" candidate.
2292    ///
2293    /// This needs to happen at the end of `consider_probe` as we need to take
2294    /// all the constraints from that into account.
2295    {}
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("should_reject_candidate_due_to_opaque_treated_as_rigid",
                                "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                                ::tracing_core::__macro_support::Option::Some(2295u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("trait_predicate")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("trait_predicate");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_predicate)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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: bool = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if let Some(predicate) = trait_predicate {
                            let goal = Goal { param_env: self.param_env, predicate };
                            if !self.infcx.goal_may_hold_opaque_types_jank(goal) {
                                return true;
                            }
                        }
                        for step in self.steps {
                            if step.self_ty_is_opaque {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2322",
                                                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(2322u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                                        ::tracing_core::field::FieldSet::new(&["message",
                                                                        {
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("step.autoderefs")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("step.autoderefs");
                                                                            NAME.as_str()
                                                                        },
                                                                        {
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("step.self_ty")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("step.self_ty");
                                                                            NAME.as_str()
                                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("self_type_is_opaque")
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&step.autoderefs)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&step.self_ty)
                                                                            as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                let constrained_opaque =
                                    self.probe(|_|
                                            {
                                                let Ok(ok) =
                                                    self.fcx.probe_instantiate_query_response(self.span,
                                                        self.orig_steps_var_values,
                                                        &step.self_ty) else {
                                                        {
                                                            use ::tracing::__macro_support::Callsite as _;
                                                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                                {
                                                                    static META: ::tracing::Metadata<'static> =
                                                                        {
                                                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2333",
                                                                                "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                                                                                ::tracing_core::__macro_support::Option::Some(2333u32),
                                                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                                ::tracing::metadata::Kind::EVENT)
                                                                        };
                                                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                                                };
                                                            let enabled =
                                                                ::tracing::Level::DEBUG <=
                                                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                                        ::tracing::Level::DEBUG <=
                                                                            ::tracing::level_filters::LevelFilter::current() &&
                                                                    {
                                                                        let interest = __CALLSITE.interest();
                                                                        !interest.is_never() &&
                                                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                                interest)
                                                                    };
                                                            if enabled {
                                                                (|value_set: ::tracing::field::ValueSet|
                                                                            {
                                                                                let meta = __CALLSITE.metadata();
                                                                                ::tracing::Event::dispatch(meta, &value_set);
                                                                                ;
                                                                            })({
                                                                        #[allow(unused_imports)]
                                                                        use ::tracing::field::{debug, display, Value};
                                                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("failed to instantiate self_ty")
                                                                                                    as &dyn ::tracing::field::Value))])
                                                                    });
                                                            } else { ; }
                                                        };
                                                        return false;
                                                    };
                                                let ocx = ObligationCtxt::new(self);
                                                let self_ty = ocx.register_infer_ok_obligations(ok);
                                                if !ocx.try_evaluate_obligations().no_errors() {
                                                    {
                                                        use ::tracing::__macro_support::Callsite as _;
                                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                            {
                                                                static META: ::tracing::Metadata<'static> =
                                                                    {
                                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2339",
                                                                            "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                                                                            ::tracing_core::__macro_support::Option::Some(2339u32),
                                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                            ::tracing::metadata::Kind::EVENT)
                                                                    };
                                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                                            };
                                                        let enabled =
                                                            ::tracing::Level::DEBUG <=
                                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                                    ::tracing::Level::DEBUG <=
                                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                                {
                                                                    let interest = __CALLSITE.interest();
                                                                    !interest.is_never() &&
                                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                            interest)
                                                                };
                                                        if enabled {
                                                            (|value_set: ::tracing::field::ValueSet|
                                                                        {
                                                                            let meta = __CALLSITE.metadata();
                                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                                            ;
                                                                        })({
                                                                    #[allow(unused_imports)]
                                                                    use ::tracing::field::{debug, display, Value};
                                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("failed to prove instantiate self_ty obligations")
                                                                                                as &dyn ::tracing::field::Value))])
                                                                });
                                                        } else { ; }
                                                    };
                                                    return false;
                                                }
                                                !self.deeply_resolve_ignoring_regions(self_ty).is_ty_var()
                                            });
                                if constrained_opaque {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2346",
                                                            "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(2346u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("opaque type has been constrained")
                                                                                as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                    return true;
                                }
                            }
                        }
                        false
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs:2295",
                        "rustc_hir_typeck::method::probe", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                        ::tracing_core::__macro_support::Option::Some(2295u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
2296    fn should_reject_candidate_due_to_opaque_treated_as_rigid(
2297        &self,
2298        trait_predicate: Option<ty::Predicate<'tcx>>,
2299    ) -> bool {
2300        // This function is what hacky and doesn't perfectly do what we want it to.
2301        // It's not soundness critical and we should be able to freely improve this
2302        // in the future.
2303        //
2304        // Some concrete edge cases include the fact that `goal_may_hold_opaque_types_jank`
2305        // also fails if there are any constraints opaques which are never used as a self
2306        // type. We also allow where-bounds which are currently ambiguous but end up
2307        // constraining an opaque later on.
2308
2309        // Check whether the trait candidate would not be applicable if the
2310        // opaque type were rigid.
2311        if let Some(predicate) = trait_predicate {
2312            let goal = Goal { param_env: self.param_env, predicate };
2313            if !self.infcx.goal_may_hold_opaque_types_jank(goal) {
2314                return true;
2315            }
2316        }
2317
2318        // Check whether any opaque types in the autoderef chain have been
2319        // constrained.
2320        for step in self.steps {
2321            if step.self_ty_is_opaque {
2322                debug!(?step.autoderefs, ?step.self_ty, "self_type_is_opaque");
2323                let constrained_opaque = self.probe(|_| {
2324                    // If we fail to instantiate the self type of this
2325                    // step, this part of the deref-chain is no longer
2326                    // reachable. In this case we don't care about opaque
2327                    // types there.
2328                    let Ok(ok) = self.fcx.probe_instantiate_query_response(
2329                        self.span,
2330                        self.orig_steps_var_values,
2331                        &step.self_ty,
2332                    ) else {
2333                        debug!("failed to instantiate self_ty");
2334                        return false;
2335                    };
2336                    let ocx = ObligationCtxt::new(self);
2337                    let self_ty = ocx.register_infer_ok_obligations(ok);
2338                    if !ocx.try_evaluate_obligations().no_errors() {
2339                        debug!("failed to prove instantiate self_ty obligations");
2340                        return false;
2341                    }
2342
2343                    !self.deeply_resolve_ignoring_regions(self_ty).is_ty_var()
2344                });
2345                if constrained_opaque {
2346                    debug!("opaque type has been constrained");
2347                    return true;
2348                }
2349            }
2350        }
2351
2352        false
2353    }
2354
2355    /// Sometimes we get in a situation where we have multiple probes that are all impls of the
2356    /// same trait, but we don't know which impl to use. In this case, since in all cases the
2357    /// external interface of the method can be determined from the trait, it's ok not to decide.
2358    /// We can basically just collapse all of the probes for various impls into one where-clause
2359    /// probe. This will result in a pending obligation so when more type-info is available we can
2360    /// make the final decision.
2361    ///
2362    /// Example (`tests/ui/methods/method-two-trait-defer-resolution-1.rs`):
2363    ///
2364    /// ```ignore (illustrative)
2365    /// trait Foo { ... }
2366    /// impl Foo for Vec<i32> { ... }
2367    /// impl Foo for Vec<usize> { ... }
2368    /// ```
2369    ///
2370    /// Now imagine the receiver is `Vec<_>`. It doesn't really matter at this time which impl we
2371    /// use, so it's ok to just commit to "using the method from the trait Foo".
2372    fn collapse_candidates_to_trait_pick(
2373        &self,
2374        self_ty: Ty<'tcx>,
2375        probes: &[(&Candidate<'tcx>, ProbeResult)],
2376    ) -> Option<Pick<'tcx>> {
2377        // Do all probes correspond to the same trait?
2378        let container = probes[0].0.item.trait_container(self.tcx)?;
2379        for (p, _) in &probes[1..] {
2380            let p_container = p.item.trait_container(self.tcx)?;
2381            if p_container != container {
2382                return None;
2383            }
2384        }
2385
2386        // They are all the same, so if any of them is ambiguous, we report the pick as ambiguous.
2387        let is_ambiguously_imported = probes.iter().any(|(p, _)| match p.kind {
2388            TraitCandidate { is_ambiguously_imported, .. } => is_ambiguously_imported,
2389            _ => false,
2390        });
2391
2392        // FIXME: check the return type here somehow.
2393        // If so, just use this trait and call it a day.
2394        Some(Pick {
2395            item: probes[0].0.item,
2396            kind: TraitPick { is_ambiguously_imported },
2397            import_ids: probes[0].0.import_ids,
2398            autoderefs: 0,
2399            autoref_or_ptr_adjustment: None,
2400            self_ty,
2401            unstable_candidates: ::alloc::vec::Vec::new()vec![],
2402            receiver_steps: None,
2403            shadowed_candidates: ::alloc::vec::Vec::new()vec![],
2404        })
2405    }
2406
2407    /// Much like `collapse_candidates_to_trait_pick`, this method allows us to collapse
2408    /// multiple conflicting picks if there is one pick whose trait container is a subtrait
2409    /// of the trait containers of all of the other picks.
2410    ///
2411    /// This is the method-probe analogue of
2412    /// `rustc_hir_analysis::hir_ty_lowering::HirTyLowerer::collapse_candidates_to_subtrait_pick`;
2413    /// keep both implementations in sync.
2414    ///
2415    /// This implements RFC #3624.
2416    fn collapse_candidates_to_subtrait_pick(
2417        &self,
2418        self_ty: Ty<'tcx>,
2419        probes: &[(&Candidate<'tcx>, ProbeResult)],
2420    ) -> Option<Pick<'tcx>> {
2421        let mut child_candidate = probes[0].0;
2422        let mut child_trait = child_candidate.item.trait_container(self.tcx)?;
2423        let mut supertraits: SsoHashSet<_> = supertrait_def_ids(self.tcx, child_trait).collect();
2424
2425        let mut remaining_candidates: Vec<_> = probes[1..].iter().map(|&(p, _)| p).collect();
2426        while !remaining_candidates.is_empty() {
2427            let mut made_progress = false;
2428            let mut next_round = ::alloc::vec::Vec::new()vec![];
2429
2430            for remaining_candidate in remaining_candidates {
2431                let remaining_trait = remaining_candidate.item.trait_container(self.tcx)?;
2432                if supertraits.contains(&remaining_trait) {
2433                    made_progress = true;
2434                    continue;
2435                }
2436
2437                // This candidate is not a supertrait of the `child_trait`.
2438                // Check if it's a subtrait of the `child_trait`, instead.
2439                // If it is, then it must have been a subtrait of every
2440                // other pick we've eliminated at this point. It will
2441                // take over at this point.
2442                let remaining_trait_supertraits: SsoHashSet<_> =
2443                    supertrait_def_ids(self.tcx, remaining_trait).collect();
2444                if remaining_trait_supertraits.contains(&child_trait) {
2445                    child_candidate = remaining_candidate;
2446                    child_trait = remaining_trait;
2447                    supertraits = remaining_trait_supertraits;
2448                    made_progress = true;
2449                    continue;
2450                }
2451
2452                // Neither `child_trait` or the current candidate are
2453                // supertraits of each other.
2454                // Don't bail here, since we may be comparing two supertraits
2455                // of a common subtrait. These two supertraits won't be related
2456                // at all, but we will pick them up next round when we find their
2457                // child as we continue iterating in this round.
2458                next_round.push(remaining_candidate);
2459            }
2460
2461            if made_progress {
2462                // If we've made progress, iterate again.
2463                remaining_candidates = next_round;
2464            } else {
2465                // Otherwise, we must have at least two candidates which
2466                // are not related to each other at all.
2467                return None;
2468            }
2469        }
2470
2471        let is_ambiguously_imported = match child_candidate.kind {
2472            TraitCandidate { is_ambiguously_imported, .. } => is_ambiguously_imported,
2473            _ => false,
2474        };
2475
2476        Some(Pick {
2477            item: child_candidate.item,
2478            kind: TraitPick { is_ambiguously_imported },
2479            import_ids: child_candidate.import_ids,
2480            autoderefs: 0,
2481            autoref_or_ptr_adjustment: None,
2482            self_ty,
2483            unstable_candidates: ::alloc::vec::Vec::new()vec![],
2484            shadowed_candidates: probes
2485                .iter()
2486                .map(|(c, _)| c.item)
2487                .filter(|item| item.def_id != child_candidate.item.def_id)
2488                .collect(),
2489            receiver_steps: None,
2490        })
2491    }
2492
2493    /// Similarly to `probe_for_return_type`, this method attempts to find the best matching
2494    /// candidate method where the method name may have been misspelled. Similarly to other
2495    /// edit distance based suggestions, we provide at most one such suggestion.
2496    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/method/probe.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2496u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::probe"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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