Skip to main content

rustc_hir_typeck/method/
confirm.rs

1use std::fmt::Debug;
2use std::ops::Deref;
3
4use rustc_hir as hir;
5use rustc_hir::GenericArg;
6use rustc_hir::def_id::DefId;
7use rustc_hir_analysis::hir_ty_lowering::generics::{
8    check_generic_arg_count_for_value_path, lower_generic_args,
9};
10use rustc_hir_analysis::hir_ty_lowering::{
11    GenericArgsLowerer, HirTyLowerer, IsMethodCall, RegionInferReason,
12};
13use rustc_infer::infer::{
14    BoundRegionConversionTime, DefineOpaqueTypes, InferOk, RegionVariableOrigin,
15};
16use rustc_lint::builtin::{
17    AMBIGUOUS_GLOB_IMPORTED_TRAITS, RESOLVING_TO_ITEMS_SHADOWING_SUPERTRAIT_ITEMS,
18};
19use rustc_middle::traits::ObligationCauseCode;
20use rustc_middle::ty::adjustment::{
21    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
22    PointerCoercion,
23};
24use rustc_middle::ty::{
25    self, AssocContainer, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt,
26    TypeFoldable, TypeVisitableExt, Unnormalized, UserArgs,
27};
28use rustc_middle::{bug, span_bug};
29use rustc_span::{DUMMY_SP, Span};
30use rustc_trait_selection::traits;
31use tracing::debug;
32
33use super::{MethodCallee, probe};
34use crate::errors::{SupertraitItemShadowee, SupertraitItemShadower, SupertraitItemShadowing};
35use crate::{FnCtxt, callee};
36
37struct ConfirmContext<'a, 'tcx> {
38    fcx: &'a FnCtxt<'a, 'tcx>,
39    span: Span,
40    self_expr: &'tcx hir::Expr<'tcx>,
41    call_expr: &'tcx hir::Expr<'tcx>,
42    skip_record_for_diagnostics: bool,
43}
44
45impl<'a, 'tcx> Deref for ConfirmContext<'a, 'tcx> {
46    type Target = FnCtxt<'a, 'tcx>;
47    fn deref(&self) -> &Self::Target {
48        self.fcx
49    }
50}
51
52#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ConfirmResult<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "ConfirmResult",
            "callee", &self.callee, "illegal_sized_bound",
            &&self.illegal_sized_bound)
    }
}Debug)]
53pub(crate) struct ConfirmResult<'tcx> {
54    pub callee: MethodCallee<'tcx>,
55    pub illegal_sized_bound: Option<Span>,
56}
57
58impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
59    pub(crate) fn confirm_method(
60        &self,
61        span: Span,
62        self_expr: &'tcx hir::Expr<'tcx>,
63        call_expr: &'tcx hir::Expr<'tcx>,
64        unadjusted_self_ty: Ty<'tcx>,
65        pick: &probe::Pick<'tcx>,
66        segment: &'tcx hir::PathSegment<'tcx>,
67    ) -> ConfirmResult<'tcx> {
68        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:68",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(68u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("confirm(unadjusted_self_ty={0:?}, pick={1:?}, generic_args={2:?})",
                                                    unadjusted_self_ty, pick, segment.args) as &dyn Value))])
            });
    } else { ; }
};debug!(
69            "confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})",
70            unadjusted_self_ty, pick, segment.args,
71        );
72
73        let mut confirm_cx = ConfirmContext::new(self, span, self_expr, call_expr);
74        confirm_cx.confirm(unadjusted_self_ty, pick, segment)
75    }
76
77    pub(crate) fn confirm_method_for_diagnostic(
78        &self,
79        span: Span,
80        self_expr: &'tcx hir::Expr<'tcx>,
81        call_expr: &'tcx hir::Expr<'tcx>,
82        unadjusted_self_ty: Ty<'tcx>,
83        pick: &probe::Pick<'tcx>,
84        segment: &hir::PathSegment<'tcx>,
85    ) -> ConfirmResult<'tcx> {
86        let mut confirm_cx = ConfirmContext::new(self, span, self_expr, call_expr);
87        confirm_cx.skip_record_for_diagnostics = true;
88        confirm_cx.confirm(unadjusted_self_ty, pick, segment)
89    }
90}
91
92impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
93    fn new(
94        fcx: &'a FnCtxt<'a, 'tcx>,
95        span: Span,
96        self_expr: &'tcx hir::Expr<'tcx>,
97        call_expr: &'tcx hir::Expr<'tcx>,
98    ) -> ConfirmContext<'a, 'tcx> {
99        ConfirmContext { fcx, span, self_expr, call_expr, skip_record_for_diagnostics: false }
100    }
101
102    fn confirm(
103        &mut self,
104        unadjusted_self_ty: Ty<'tcx>,
105        pick: &probe::Pick<'tcx>,
106        segment: &hir::PathSegment<'tcx>,
107    ) -> ConfirmResult<'tcx> {
108        // Adjust the self expression the user provided and obtain the adjusted type.
109        let self_ty = self.adjust_self_ty(unadjusted_self_ty, pick);
110
111        // Create generic args for the method's type parameters.
112        let rcvr_args = self.fresh_receiver_args(self_ty, pick);
113        let all_args = self.instantiate_method_args(pick, segment, rcvr_args);
114
115        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:115",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(115u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("rcvr_args={0:?}, all_args={1:?}",
                                                    rcvr_args, all_args) as &dyn Value))])
            });
    } else { ; }
};debug!("rcvr_args={rcvr_args:?}, all_args={all_args:?}");
116
117        // Create the final signature for the method, replacing late-bound regions.
118        let (method_sig, method_predicates) = self.instantiate_method_sig(pick, all_args);
119
120        // If there is a `Self: Sized` bound and `Self` is a trait object, it is possible that
121        // something which derefs to `Self` actually implements the trait and the caller
122        // wanted to make a static dispatch on it but forgot to import the trait.
123        // See test `tests/ui/issues/issue-35976.rs`.
124        //
125        // In that case, we'll error anyway, but we'll also re-run the search with all traits
126        // in scope, and if we find another method which can be used, we'll output an
127        // appropriate hint suggesting to import the trait.
128        let filler_args = rcvr_args
129            .extend_to(self.tcx, pick.item.def_id, |def, _| self.tcx.mk_param_from_def(def));
130        let illegal_sized_bound = self.predicates_require_illegal_sized_bound(
131            self.tcx.predicates_of(pick.item.def_id).instantiate(self.tcx, filler_args),
132        );
133
134        // Unify the (adjusted) self type with what the method expects.
135        //
136        // SUBTLE: if we want good error messages, because of "guessing" while matching
137        // traits, no trait system method can be called before this point because they
138        // could alter our Self-type, except for normalizing the receiver from the
139        // signature (which is also done during probing).
140        let method_sig_rcvr =
141            self.normalize(self.span, Unnormalized::new_wip(method_sig.inputs()[0]));
142        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:142",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(142u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("confirm: self_ty={0:?} method_sig_rcvr={1:?} method_sig={2:?} method_predicates={3:?}",
                                                    self_ty, method_sig_rcvr, method_sig, method_predicates) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
143            "confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}",
144            self_ty, method_sig_rcvr, method_sig, method_predicates
145        );
146        self.unify_receivers(self_ty, method_sig_rcvr, pick);
147
148        let method_sig = self.normalize(self.span, Unnormalized::new_wip(method_sig));
149
150        // Make sure nobody calls `drop()` explicitly.
151        self.check_for_illegal_method_calls(pick);
152
153        // Lint when an item is shadowing a supertrait item.
154        self.lint_shadowed_supertrait_items(pick, segment);
155
156        // Lint when a trait is ambiguously imported
157        self.lint_ambiguously_glob_imported_traits(pick, segment);
158
159        // Add any trait/regions obligations specified on the method's type parameters.
160        // We won't add these if we encountered an illegal sized bound, so that we can use
161        // a custom error in that case.
162        if illegal_sized_bound.is_none() {
163            self.add_obligations(method_sig, all_args, method_predicates, pick.item.def_id);
164        }
165
166        // Create the final `MethodCallee`.
167        let callee = MethodCallee { def_id: pick.item.def_id, args: all_args, sig: method_sig };
168        ConfirmResult { callee, illegal_sized_bound }
169    }
170
171    ///////////////////////////////////////////////////////////////////////////
172    // ADJUSTMENTS
173
174    fn adjust_self_ty(
175        &mut self,
176        unadjusted_self_ty: Ty<'tcx>,
177        pick: &probe::Pick<'tcx>,
178    ) -> Ty<'tcx> {
179        // Commit the autoderefs by calling `autoderef` again, but this
180        // time writing the results into the various typeck results.
181        let mut autoderef = self.autoderef(self.call_expr.span, unadjusted_self_ty);
182        let Some((mut target, n)) = autoderef.nth(pick.autoderefs) else {
183            return Ty::new_error_with_message(
184                self.tcx,
185                DUMMY_SP,
186                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed autoderef {0}",
                pick.autoderefs))
    })format!("failed autoderef {}", pick.autoderefs),
187            );
188        };
189        match (&n, &pick.autoderefs) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(n, pick.autoderefs);
190
191        let mut adjustments = self.adjust_steps(&autoderef);
192        match pick.autoref_or_ptr_adjustment {
193            Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl, unsize }) => {
194                let region = self.next_region_var(RegionVariableOrigin::Autoref(self.span));
195                // Type we're wrapping in a reference, used later for unsizing
196                let base_ty = target;
197
198                target = Ty::new_ref(self.tcx, region, target, mutbl);
199
200                // Method call receivers are the primary use case
201                // for two-phase borrows.
202                let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::Yes);
203
204                adjustments
205                    .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target });
206
207                if unsize {
208                    let unsized_ty = if let ty::Array(elem_ty, _) = base_ty.kind() {
209                        Ty::new_slice(self.tcx, *elem_ty)
210                    } else {
211                        ::rustc_middle::util::bug::bug_fmt(format_args!("AutorefOrPtrAdjustment\'s unsize flag should only be set for array ty, found {0}",
        base_ty))bug!(
212                            "AutorefOrPtrAdjustment's unsize flag should only be set for array ty, found {}",
213                            base_ty
214                        )
215                    };
216                    target = Ty::new_ref(self.tcx, region, unsized_ty, mutbl.into());
217                    adjustments.push(Adjustment {
218                        kind: Adjust::Pointer(PointerCoercion::Unsize),
219                        target,
220                    });
221                }
222            }
223            Some(probe::AutorefOrPtrAdjustment::ToConstPtr) => {
224                target = match target.kind() {
225                    &ty::RawPtr(ty, mutbl) => {
226                        if !mutbl.is_mut() {
    ::core::panicking::panic("assertion failed: mutbl.is_mut()")
};assert!(mutbl.is_mut());
227                        Ty::new_imm_ptr(self.tcx, ty)
228                    }
229                    other => {
    ::core::panicking::panic_fmt(format_args!("Cannot adjust receiver type {0:?} to const ptr",
            other));
}panic!("Cannot adjust receiver type {other:?} to const ptr"),
230                };
231
232                adjustments.push(Adjustment {
233                    kind: Adjust::Pointer(PointerCoercion::MutToConstPointer),
234                    target,
235                });
236            }
237
238            Some(probe::AutorefOrPtrAdjustment::ReborrowPin(mutbl)) => {
239                let region = self.next_region_var(RegionVariableOrigin::Autoref(self.span));
240
241                target = match target.kind() {
242                    ty::Adt(pin, args) if self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => {
243                        let inner_ty = match args[0].expect_ty().kind() {
244                            ty::Ref(_, ty, _) => *ty,
245                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Expected a reference type for argument to Pin"))bug!("Expected a reference type for argument to Pin"),
246                        };
247                        adjustments.push(Adjustment {
248                            kind: Adjust::Deref(DerefAdjustKind::Pin),
249                            target: inner_ty,
250                        });
251                        Ty::new_pinned_ref(self.tcx, region, inner_ty, mutbl)
252                    }
253                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Cannot adjust receiver type for reborrowing pin of {0:?}",
        target))bug!("Cannot adjust receiver type for reborrowing pin of {target:?}"),
254                };
255                adjustments
256                    .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Pin(mutbl)), target });
257            }
258            None => {}
259        }
260
261        self.register_predicates(autoderef.into_obligations());
262
263        // Write out the final adjustments.
264        if !self.skip_record_for_diagnostics {
265            self.apply_adjustments(self.self_expr, adjustments);
266        }
267
268        target
269    }
270
271    /// Returns a set of generic parameters for the method *receiver* where all type and region
272    /// parameters are instantiated with fresh variables. This generic parameters does not include any
273    /// parameters declared on the method itself.
274    ///
275    /// Note that this generic parameters may include late-bound regions from the impl level. If so,
276    /// these are instantiated later in the `instantiate_method_sig` routine.
277    fn fresh_receiver_args(
278        &mut self,
279        self_ty: Ty<'tcx>,
280        pick: &probe::Pick<'tcx>,
281    ) -> GenericArgsRef<'tcx> {
282        match pick.kind {
283            probe::InherentImplPick => {
284                let impl_def_id = pick.item.container_id(self.tcx);
285                if !#[allow(non_exhaustive_omitted_patterns)] match pick.item.container {
            AssocContainer::InherentImpl => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("impl {0:?} is not an inherent impl",
                impl_def_id));
    }
};assert!(
286                    matches!(pick.item.container, AssocContainer::InherentImpl),
287                    "impl {impl_def_id:?} is not an inherent impl"
288                );
289                self.fresh_args_for_item(self.span, impl_def_id)
290            }
291
292            probe::ObjectPick => {
293                let trait_def_id = pick.item.container_id(self.tcx);
294
295                // If the trait is not object safe (specifically, we care about when
296                // the receiver is not valid), then there's a chance that we will not
297                // actually be able to recover the object by derefing the receiver like
298                // we should if it were valid.
299                if !self.tcx.is_dyn_compatible(trait_def_id) {
300                    return ty::GenericArgs::extend_with_error(self.tcx, trait_def_id, &[]);
301                }
302
303                // This shouldn't happen for non-region error kinds, but may occur
304                // when we have error regions. Specifically, since we canonicalize
305                // during method steps, we may successfully deref when we assemble
306                // the pick, but fail to deref when we try to extract the object
307                // type from the pick during confirmation. This is fine, we're basically
308                // already doomed by this point.
309                if self_ty.references_error() {
310                    return ty::GenericArgs::extend_with_error(self.tcx, trait_def_id, &[]);
311                }
312
313                self.extract_existential_trait_ref(self_ty, |this, object_ty, principal| {
314                    // The object data has no entry for the Self
315                    // Type. For the purposes of this method call, we
316                    // instantiate the object type itself. This
317                    // wouldn't be a sound instantiation in all cases,
318                    // since each instance of the object type is a
319                    // different existential and hence could match
320                    // distinct types (e.g., if `Self` appeared as an
321                    // argument type), but those cases have already
322                    // been ruled out when we deemed the trait to be
323                    // "dyn-compatible".
324                    let original_poly_trait_ref = principal.with_self_ty(this.tcx, object_ty);
325                    let upcast_poly_trait_ref = this.upcast(original_poly_trait_ref, trait_def_id);
326                    let upcast_trait_ref =
327                        this.instantiate_binder_with_fresh_vars(upcast_poly_trait_ref);
328                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:328",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(328u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("original_poly_trait_ref={0:?} upcast_trait_ref={1:?} target_trait={2:?}",
                                                    original_poly_trait_ref, upcast_trait_ref, trait_def_id) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
329                        "original_poly_trait_ref={:?} upcast_trait_ref={:?} target_trait={:?}",
330                        original_poly_trait_ref, upcast_trait_ref, trait_def_id
331                    );
332                    upcast_trait_ref.args
333                })
334            }
335
336            probe::TraitPick(_) => {
337                let trait_def_id = pick.item.container_id(self.tcx);
338
339                // Make a trait reference `$0 : Trait<$1...$n>`
340                // consisting entirely of type variables. Later on in
341                // the process we will unify the transformed-self-type
342                // of the method with the actual type in order to
343                // unify some of these variables.
344                self.fresh_args_for_item(self.span, trait_def_id)
345            }
346
347            probe::WhereClausePick(poly_trait_ref) => {
348                // Where clauses can have bound regions in them. We need to instantiate
349                // those to convert from a poly-trait-ref to a trait-ref.
350                self.instantiate_binder_with_fresh_vars(poly_trait_ref).args
351            }
352        }
353    }
354
355    fn extract_existential_trait_ref<R, F>(&mut self, self_ty: Ty<'tcx>, mut closure: F) -> R
356    where
357        F: FnMut(&mut ConfirmContext<'a, 'tcx>, Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>) -> R,
358    {
359        // If we specified that this is an object method, then the
360        // self-type ought to be something that can be dereferenced to
361        // yield an object-type (e.g., `&Object` or `Box<Object>`
362        // etc).
363
364        let mut autoderef = self.fcx.autoderef(self.span, self_ty);
365
366        // We don't need to gate this behind arbitrary self types
367        // per se, but it does make things a bit more gated.
368        if self.tcx.features().arbitrary_self_types()
369            || self.tcx.features().arbitrary_self_types_pointers()
370        {
371            autoderef = autoderef.use_receiver_trait();
372        }
373
374        autoderef
375            .include_raw_pointers()
376            .find_map(|(ty, _)| match ty.kind() {
377                ty::Dynamic(data, ..) => Some(closure(
378                    self,
379                    ty,
380                    data.principal().unwrap_or_else(|| {
381                        ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("calling trait method on empty object?"))span_bug!(self.span, "calling trait method on empty object?")
382                    }),
383                )),
384                _ => None,
385            })
386            .unwrap_or_else(|| {
387                ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("self-type `{0}` for ObjectPick never dereferenced to an object",
        self_ty))span_bug!(
388                    self.span,
389                    "self-type `{}` for ObjectPick never dereferenced to an object",
390                    self_ty
391                )
392            })
393    }
394
395    fn instantiate_method_args(
396        &mut self,
397        pick: &probe::Pick<'tcx>,
398        seg: &hir::PathSegment<'tcx>,
399        parent_args: GenericArgsRef<'tcx>,
400    ) -> GenericArgsRef<'tcx> {
401        // Determine the values for the generic parameters of the method.
402        // If they were not explicitly supplied, just construct fresh
403        // variables.
404        let generics = self.tcx.generics_of(pick.item.def_id);
405
406        let arg_count_correct = check_generic_arg_count_for_value_path(
407            self.fcx,
408            pick.item.def_id,
409            generics,
410            seg,
411            IsMethodCall::Yes,
412        );
413
414        // Create generic parameters for early-bound lifetime parameters,
415        // combining parameters from the type and those from the method.
416        match (&generics.parent_count, &parent_args.len()) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(generics.parent_count, parent_args.len());
417
418        struct GenericArgsCtxt<'a, 'tcx> {
419            cfcx: &'a ConfirmContext<'a, 'tcx>,
420            pick: &'a probe::Pick<'tcx>,
421            seg: &'a hir::PathSegment<'tcx>,
422        }
423        impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
424            fn args_for_def_id(
425                &mut self,
426                def_id: DefId,
427            ) -> (Option<&'a hir::GenericArgs<'tcx>>, bool) {
428                if def_id == self.pick.item.def_id {
429                    if let Some(data) = self.seg.args {
430                        return (Some(data), false);
431                    }
432                }
433                (None, false)
434            }
435
436            fn provided_kind(
437                &mut self,
438                preceding_args: &[ty::GenericArg<'tcx>],
439                param: &ty::GenericParamDef,
440                arg: &GenericArg<'tcx>,
441            ) -> ty::GenericArg<'tcx> {
442                match (&param.kind, arg) {
443                    (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => self
444                        .cfcx
445                        .fcx
446                        .lowerer()
447                        .lower_lifetime(lt, RegionInferReason::Param(param))
448                        .into(),
449                    (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
450                        // We handle the ambig portions of `Ty` in the match arms below
451                        self.cfcx.lower_ty(ty.as_unambig_ty()).raw.into()
452                    }
453                    (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
454                        self.cfcx.lower_ty(&inf.to_ty()).raw.into()
455                    }
456                    (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
457                        .cfcx
458                        // We handle the ambig portions of `ConstArg` in the match arms below
459                        .lower_const_arg(
460                            ct.as_unambig_ct(),
461                            self.cfcx
462                                .tcx
463                                .type_of(param.def_id)
464                                .instantiate(self.cfcx.tcx, preceding_args)
465                                .skip_norm_wip(),
466                        )
467                        .into(),
468                    (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
469                        self.cfcx.ct_infer(Some(param), inf.span).into()
470                    }
471                    (kind, arg) => {
472                        ::rustc_middle::util::bug::bug_fmt(format_args!("mismatched method arg kind {0:?} in turbofish: {1:?}",
        kind, arg))bug!("mismatched method arg kind {kind:?} in turbofish: {arg:?}")
473                    }
474                }
475            }
476
477            fn inferred_kind(
478                &mut self,
479                _preceding_args: &[ty::GenericArg<'tcx>],
480                param: &ty::GenericParamDef,
481                _infer_args: bool,
482            ) -> ty::GenericArg<'tcx> {
483                self.cfcx.var_for_def(self.cfcx.span, param)
484            }
485        }
486
487        let args = lower_generic_args(
488            self.fcx,
489            pick.item.def_id,
490            parent_args,
491            false,
492            None,
493            &arg_count_correct,
494            &mut GenericArgsCtxt { cfcx: self, pick, seg },
495        );
496
497        // When the method is confirmed, the `args` includes
498        // parameters from not just the method, but also the impl of
499        // the method -- in particular, the `Self` type will be fully
500        // resolved. However, those are not something that the "user
501        // specified" -- i.e., those types come from the inferred type
502        // of the receiver, not something the user wrote. So when we
503        // create the user-args, we want to replace those earlier
504        // types with just the types that the user actually wrote --
505        // that is, those that appear on the *method itself*.
506        //
507        // As an example, if the user wrote something like
508        // `foo.bar::<u32>(...)` -- the `Self` type here will be the
509        // type of `foo` (possibly adjusted), but we don't want to
510        // include that. We want just the `[_, u32]` part.
511        if !args.is_empty() && !generics.is_own_empty() {
512            let user_type_annotation = self.probe(|_| {
513                let user_args = UserArgs {
514                    args: GenericArgs::for_item(self.tcx, pick.item.def_id, |param, _| {
515                        let i = param.index as usize;
516                        if i < generics.parent_count {
517                            self.fcx.var_for_def(DUMMY_SP, param)
518                        } else {
519                            args[i]
520                        }
521                    }),
522                    user_self_ty: None, // not relevant here
523                };
524
525                self.fcx.canonicalize_user_type_annotation(ty::UserType::new(
526                    ty::UserTypeKind::TypeOf(pick.item.def_id, user_args),
527                ))
528            });
529
530            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:530",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(530u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("instantiate_method_args: user_type_annotation={0:?}",
                                                    user_type_annotation) as &dyn Value))])
            });
    } else { ; }
};debug!("instantiate_method_args: user_type_annotation={:?}", user_type_annotation);
531
532            if !self.skip_record_for_diagnostics {
533                self.fcx.write_user_type_annotation(self.call_expr.hir_id, user_type_annotation);
534            }
535        }
536
537        self.normalize(self.span, Unnormalized::new_wip(args))
538    }
539
540    fn unify_receivers(
541        &mut self,
542        self_ty: Ty<'tcx>,
543        method_self_ty: Ty<'tcx>,
544        pick: &probe::Pick<'tcx>,
545    ) {
546        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:546",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(546u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("unify_receivers: self_ty={0:?} method_self_ty={1:?} span={2:?} pick={3:?}",
                                                    self_ty, method_self_ty, self.span, pick) as &dyn Value))])
            });
    } else { ; }
};debug!(
547            "unify_receivers: self_ty={:?} method_self_ty={:?} span={:?} pick={:?}",
548            self_ty, method_self_ty, self.span, pick
549        );
550        let cause = self.cause(self.self_expr.span, ObligationCauseCode::Misc);
551        match self.at(&cause, self.param_env).sup(DefineOpaqueTypes::Yes, method_self_ty, self_ty) {
552            Ok(InferOk { obligations, value: () }) => {
553                self.register_predicates(obligations);
554            }
555            Err(terr) => {
556                if self.tcx.features().arbitrary_self_types() {
557                    self.err_ctxt()
558                        .report_mismatched_types(
559                            &cause,
560                            self.param_env,
561                            method_self_ty,
562                            self_ty,
563                            terr,
564                        )
565                        .emit();
566                } else {
567                    // This has/will have errored in wfcheck, which we cannot depend on from here, as typeck on functions
568                    // may run before wfcheck if the function is used in const eval.
569                    self.dcx().span_delayed_bug(
570                        cause.span,
571                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} was a subtype of {1} but now is not?",
                self_ty, method_self_ty))
    })format!("{self_ty} was a subtype of {method_self_ty} but now is not?"),
572                    );
573                }
574            }
575        }
576    }
577
578    // NOTE: this returns the *unnormalized* predicates and method sig. Because of
579    // inference guessing, the predicates and method signature can't be normalized
580    // until we unify the `Self` type.
581    fn instantiate_method_sig(
582        &mut self,
583        pick: &probe::Pick<'tcx>,
584        all_args: GenericArgsRef<'tcx>,
585    ) -> (ty::FnSig<'tcx>, ty::InstantiatedPredicates<'tcx>) {
586        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:586",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(586u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("instantiate_method_sig(pick={0:?}, all_args={1:?})",
                                                    pick, all_args) as &dyn Value))])
            });
    } else { ; }
};debug!("instantiate_method_sig(pick={:?}, all_args={:?})", pick, all_args);
587
588        // Instantiate the bounds on the method with the
589        // type/early-bound-regions instantiations performed. There can
590        // be no late-bound regions appearing here.
591        let def_id = pick.item.def_id;
592        let method_predicates = self.tcx.predicates_of(def_id).instantiate(self.tcx, all_args);
593
594        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:594",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(594u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("method_predicates after instantiation = {0:?}",
                                                    method_predicates) as &dyn Value))])
            });
    } else { ; }
};debug!("method_predicates after instantiation = {:?}", method_predicates);
595
596        let sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, all_args).skip_norm_wip();
597        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:597",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(597u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("type scheme instantiated, sig={0:?}",
                                                    sig) as &dyn Value))])
            });
    } else { ; }
};debug!("type scheme instantiated, sig={:?}", sig);
598
599        let sig = self.instantiate_binder_with_fresh_vars(sig);
600        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:600",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(600u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("late-bound lifetimes from method instantiated, sig={0:?}",
                                                    sig) as &dyn Value))])
            });
    } else { ; }
};debug!("late-bound lifetimes from method instantiated, sig={:?}", sig);
601
602        (sig, method_predicates)
603    }
604
605    fn add_obligations(
606        &mut self,
607        sig: ty::FnSig<'tcx>,
608        all_args: GenericArgsRef<'tcx>,
609        method_predicates: ty::InstantiatedPredicates<'tcx>,
610        def_id: DefId,
611    ) {
612        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:612",
                        "rustc_hir_typeck::method::confirm",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/confirm.rs"),
                        ::tracing_core::__macro_support::Option::Some(612u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::confirm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("add_obligations: sig={0:?} all_args={1:?} method_predicates={2:?} def_id={3:?}",
                                                    sig, all_args, method_predicates, def_id) as &dyn Value))])
            });
    } else { ; }
};debug!(
613            "add_obligations: sig={:?} all_args={:?} method_predicates={:?} def_id={:?}",
614            sig, all_args, method_predicates, def_id
615        );
616
617        // FIXME: could replace with the following, but we already calculated `method_predicates`,
618        // so we just call `predicates_for_generics` directly to avoid redoing work.
619        // `self.add_required_obligations(self.span, def_id, &all_args);`
620        for obligation in traits::predicates_for_generics(
621            |idx, span| {
622                let code = ObligationCauseCode::WhereClauseInExpr(
623                    def_id,
624                    span,
625                    self.call_expr.hir_id,
626                    idx,
627                );
628                self.cause(self.span, code)
629            },
630            |pred| self.normalize(self.call_expr.span, pred),
631            self.param_env,
632            method_predicates,
633        ) {
634            self.register_predicate(obligation);
635        }
636
637        // this is a projection from a trait reference, so we have to
638        // make sure that the trait reference inputs are well-formed.
639        self.add_wf_bounds(all_args, self.call_expr.span);
640
641        // the function type must also be well-formed (this is not
642        // implied by the args being well-formed because of inherent
643        // impls and late-bound regions - see issue #28609).
644        for ty in sig.inputs_and_output {
645            self.register_wf_obligation(
646                ty.into(),
647                self.span,
648                ObligationCauseCode::WellFormed(None),
649            );
650        }
651    }
652
653    ///////////////////////////////////////////////////////////////////////////
654    // MISCELLANY
655
656    fn predicates_require_illegal_sized_bound(
657        &self,
658        predicates: ty::InstantiatedPredicates<'tcx>,
659    ) -> Option<Span> {
660        let sized_def_id = self.tcx.lang_items().sized_trait()?;
661
662        traits::elaborate(
663            self.tcx,
664            predicates.predicates.iter().copied().map(Unnormalized::skip_norm_wip),
665        )
666        // We don't care about regions here.
667        .filter_map(|pred| match pred.kind().skip_binder() {
668            ty::ClauseKind::Trait(trait_pred) if trait_pred.def_id() == sized_def_id => {
669                let span = predicates
670                    .iter()
671                    .find_map(|(p, span)| if p.skip_norm_wip() == pred { Some(span) } else { None })
672                    .unwrap_or(DUMMY_SP);
673                Some((trait_pred, span))
674            }
675            _ => None,
676        })
677        .find_map(|(trait_pred, span)| match trait_pred.self_ty().kind() {
678            ty::Dynamic(..) => Some(span),
679            _ => None,
680        })
681    }
682
683    fn check_for_illegal_method_calls(&self, pick: &probe::Pick<'_>) {
684        // Disallow calls to the method `drop` defined in the `Drop` trait.
685        if let Some(trait_def_id) = pick.item.trait_container(self.tcx)
686            && let Err(e) = callee::check_legal_trait_for_method_call(
687                self.tcx,
688                self.span,
689                Some(self.self_expr.span),
690                self.call_expr.span,
691                trait_def_id,
692                self.body_id.to_def_id(),
693            )
694        {
695            self.set_tainted_by_errors(e);
696        }
697    }
698
699    fn lint_shadowed_supertrait_items(
700        &self,
701        pick: &probe::Pick<'_>,
702        segment: &hir::PathSegment<'tcx>,
703    ) {
704        if pick.shadowed_candidates.is_empty() {
705            return;
706        }
707
708        let shadower_span = self.tcx.def_span(pick.item.def_id);
709        let subtrait = self.tcx.item_name(pick.item.trait_container(self.tcx).unwrap());
710        let shadower = SupertraitItemShadower { span: shadower_span, subtrait };
711
712        let shadowee = if let [shadowee] = &pick.shadowed_candidates[..] {
713            let shadowee_span = self.tcx.def_span(shadowee.def_id);
714            let supertrait = self.tcx.item_name(shadowee.trait_container(self.tcx).unwrap());
715            SupertraitItemShadowee::Labeled { span: shadowee_span, supertrait }
716        } else {
717            let (traits, spans): (Vec<_>, Vec<_>) = pick
718                .shadowed_candidates
719                .iter()
720                .map(|item| {
721                    (
722                        self.tcx.item_name(item.trait_container(self.tcx).unwrap()),
723                        self.tcx.def_span(item.def_id),
724                    )
725                })
726                .unzip();
727            SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
728        };
729
730        self.tcx.emit_node_span_lint(
731            RESOLVING_TO_ITEMS_SHADOWING_SUPERTRAIT_ITEMS,
732            segment.hir_id,
733            segment.ident.span,
734            SupertraitItemShadowing { shadower, shadowee, item: segment.ident.name, subtrait },
735        );
736    }
737
738    fn lint_ambiguously_glob_imported_traits(
739        &self,
740        pick: &probe::Pick<'_>,
741        segment: &hir::PathSegment<'tcx>,
742    ) {
743        if pick.kind != probe::PickKind::TraitPick(true) {
744            return;
745        }
746        let trait_name = self.tcx.item_name(pick.item.container_id(self.tcx));
747        let import_span = self.tcx.hir_span_if_local(pick.import_ids[0].to_def_id()).unwrap();
748
749        self.tcx.emit_node_lint(
750            AMBIGUOUS_GLOB_IMPORTED_TRAITS,
751            segment.hir_id,
752            rustc_errors::DiagDecorator(|diag| {
753                diag.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Use of ambiguously glob imported trait `{0}`",
                trait_name))
    })format!(
754                    "Use of ambiguously glob imported trait `{trait_name}`"
755                ))
756                .span(segment.ident.span)
757                .span_label(import_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` imported ambiguously here",
                trait_name))
    })format!("`{trait_name}` imported ambiguously here"))
758                .help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Import `{0}` explicitly",
                trait_name))
    })format!("Import `{trait_name}` explicitly"));
759            }),
760        );
761    }
762
763    fn upcast(
764        &mut self,
765        source_trait_ref: ty::PolyTraitRef<'tcx>,
766        target_trait_def_id: DefId,
767    ) -> ty::PolyTraitRef<'tcx> {
768        let upcast_trait_refs =
769            traits::upcast_choices(self.tcx, source_trait_ref, target_trait_def_id);
770
771        // must be exactly one trait ref or we'd get an ambig error etc
772        if let &[upcast_trait_ref] = upcast_trait_refs.as_slice() {
773            upcast_trait_ref
774        } else {
775            self.dcx().span_delayed_bug(
776                self.span,
777                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot uniquely upcast `{0:?}` to `{1:?}`: `{2:?}`",
                source_trait_ref, target_trait_def_id, upcast_trait_refs))
    })format!(
778                    "cannot uniquely upcast `{:?}` to `{:?}`: `{:?}`",
779                    source_trait_ref, target_trait_def_id, upcast_trait_refs
780                ),
781            );
782
783            ty::Binder::dummy(ty::TraitRef::new_from_args(
784                self.tcx,
785                target_trait_def_id,
786                ty::GenericArgs::extend_with_error(self.tcx, target_trait_def_id, &[]),
787            ))
788        }
789    }
790
791    fn instantiate_binder_with_fresh_vars<T>(&self, value: ty::Binder<'tcx, T>) -> T
792    where
793        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
794    {
795        self.fcx.instantiate_binder_with_fresh_vars(
796            self.span,
797            BoundRegionConversionTime::FnCall,
798            value,
799        )
800    }
801}