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_call, 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, 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 = self.normalize(self.span, method_sig.inputs()[0]);
141        {
    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:141",
                        "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(141u32),
                        ::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!(
142            "confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}",
143            self_ty, method_sig_rcvr, method_sig, method_predicates
144        );
145        self.unify_receivers(self_ty, method_sig_rcvr, pick);
146
147        let (method_sig, method_predicates) =
148            self.normalize(self.span, (method_sig, method_predicates));
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_call(
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                        )
466                        .into(),
467                    (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
468                        self.cfcx.ct_infer(Some(param), inf.span).into()
469                    }
470                    (kind, arg) => {
471                        ::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:?}")
472                    }
473                }
474            }
475
476            fn inferred_kind(
477                &mut self,
478                _preceding_args: &[ty::GenericArg<'tcx>],
479                param: &ty::GenericParamDef,
480                _infer_args: bool,
481            ) -> ty::GenericArg<'tcx> {
482                self.cfcx.var_for_def(self.cfcx.span, param)
483            }
484        }
485
486        let args = lower_generic_args(
487            self.fcx,
488            pick.item.def_id,
489            parent_args,
490            false,
491            None,
492            &arg_count_correct,
493            &mut GenericArgsCtxt { cfcx: self, pick, seg },
494        );
495
496        // When the method is confirmed, the `args` includes
497        // parameters from not just the method, but also the impl of
498        // the method -- in particular, the `Self` type will be fully
499        // resolved. However, those are not something that the "user
500        // specified" -- i.e., those types come from the inferred type
501        // of the receiver, not something the user wrote. So when we
502        // create the user-args, we want to replace those earlier
503        // types with just the types that the user actually wrote --
504        // that is, those that appear on the *method itself*.
505        //
506        // As an example, if the user wrote something like
507        // `foo.bar::<u32>(...)` -- the `Self` type here will be the
508        // type of `foo` (possibly adjusted), but we don't want to
509        // include that. We want just the `[_, u32]` part.
510        if !args.is_empty() && !generics.is_own_empty() {
511            let user_type_annotation = self.probe(|_| {
512                let user_args = UserArgs {
513                    args: GenericArgs::for_item(self.tcx, pick.item.def_id, |param, _| {
514                        let i = param.index as usize;
515                        if i < generics.parent_count {
516                            self.fcx.var_for_def(DUMMY_SP, param)
517                        } else {
518                            args[i]
519                        }
520                    }),
521                    user_self_ty: None, // not relevant here
522                };
523
524                self.fcx.canonicalize_user_type_annotation(ty::UserType::new(
525                    ty::UserTypeKind::TypeOf(pick.item.def_id, user_args),
526                ))
527            });
528
529            {
    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:529",
                        "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(529u32),
                        ::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);
530
531            if !self.skip_record_for_diagnostics {
532                self.fcx.write_user_type_annotation(self.call_expr.hir_id, user_type_annotation);
533            }
534        }
535
536        self.normalize(self.span, args)
537    }
538
539    fn unify_receivers(
540        &mut self,
541        self_ty: Ty<'tcx>,
542        method_self_ty: Ty<'tcx>,
543        pick: &probe::Pick<'tcx>,
544    ) {
545        {
    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:545",
                        "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(545u32),
                        ::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!(
546            "unify_receivers: self_ty={:?} method_self_ty={:?} span={:?} pick={:?}",
547            self_ty, method_self_ty, self.span, pick
548        );
549        let cause = self.cause(self.self_expr.span, ObligationCauseCode::Misc);
550        match self.at(&cause, self.param_env).sup(DefineOpaqueTypes::Yes, method_self_ty, self_ty) {
551            Ok(InferOk { obligations, value: () }) => {
552                self.register_predicates(obligations);
553            }
554            Err(terr) => {
555                if self.tcx.features().arbitrary_self_types() {
556                    self.err_ctxt()
557                        .report_mismatched_types(
558                            &cause,
559                            self.param_env,
560                            method_self_ty,
561                            self_ty,
562                            terr,
563                        )
564                        .emit();
565                } else {
566                    // This has/will have errored in wfcheck, which we cannot depend on from here, as typeck on functions
567                    // may run before wfcheck if the function is used in const eval.
568                    self.dcx().span_delayed_bug(
569                        cause.span,
570                        ::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?"),
571                    );
572                }
573            }
574        }
575    }
576
577    // NOTE: this returns the *unnormalized* predicates and method sig. Because of
578    // inference guessing, the predicates and method signature can't be normalized
579    // until we unify the `Self` type.
580    fn instantiate_method_sig(
581        &mut self,
582        pick: &probe::Pick<'tcx>,
583        all_args: GenericArgsRef<'tcx>,
584    ) -> (ty::FnSig<'tcx>, ty::InstantiatedPredicates<'tcx>) {
585        {
    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:585",
                        "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(585u32),
                        ::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);
586
587        // Instantiate the bounds on the method with the
588        // type/early-bound-regions instantiations performed. There can
589        // be no late-bound regions appearing here.
590        let def_id = pick.item.def_id;
591        let method_predicates = self.tcx.predicates_of(def_id).instantiate(self.tcx, all_args);
592
593        {
    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:593",
                        "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(593u32),
                        ::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);
594
595        let sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, all_args);
596        {
    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:596",
                        "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(596u32),
                        ::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);
597
598        let sig = self.instantiate_binder_with_fresh_vars(sig);
599        {
    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:599",
                        "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(599u32),
                        ::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);
600
601        (sig, method_predicates)
602    }
603
604    fn add_obligations(
605        &mut self,
606        sig: ty::FnSig<'tcx>,
607        all_args: GenericArgsRef<'tcx>,
608        method_predicates: ty::InstantiatedPredicates<'tcx>,
609        def_id: DefId,
610    ) {
611        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/confirm.rs:611",
                        "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(611u32),
                        ::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!(
612            "add_obligations: sig={:?} all_args={:?} method_predicates={:?} def_id={:?}",
613            sig, all_args, method_predicates, def_id
614        );
615
616        // FIXME: could replace with the following, but we already calculated `method_predicates`,
617        // so we just call `predicates_for_generics` directly to avoid redoing work.
618        // `self.add_required_obligations(self.span, def_id, &all_args);`
619        for obligation in traits::predicates_for_generics(
620            |idx, span| {
621                let code = ObligationCauseCode::WhereClauseInExpr(
622                    def_id,
623                    span,
624                    self.call_expr.hir_id,
625                    idx,
626                );
627                self.cause(self.span, code)
628            },
629            self.param_env,
630            method_predicates,
631        ) {
632            self.register_predicate(obligation);
633        }
634
635        // this is a projection from a trait reference, so we have to
636        // make sure that the trait reference inputs are well-formed.
637        self.add_wf_bounds(all_args, self.call_expr.span);
638
639        // the function type must also be well-formed (this is not
640        // implied by the args being well-formed because of inherent
641        // impls and late-bound regions - see issue #28609).
642        for ty in sig.inputs_and_output {
643            self.register_wf_obligation(
644                ty.into(),
645                self.span,
646                ObligationCauseCode::WellFormed(None),
647            );
648        }
649    }
650
651    ///////////////////////////////////////////////////////////////////////////
652    // MISCELLANY
653
654    fn predicates_require_illegal_sized_bound(
655        &self,
656        predicates: ty::InstantiatedPredicates<'tcx>,
657    ) -> Option<Span> {
658        let sized_def_id = self.tcx.lang_items().sized_trait()?;
659
660        traits::elaborate(self.tcx, predicates.predicates.iter().copied())
661            // We don't care about regions here.
662            .filter_map(|pred| match pred.kind().skip_binder() {
663                ty::ClauseKind::Trait(trait_pred) if trait_pred.def_id() == sized_def_id => {
664                    let span = predicates
665                        .iter()
666                        .find_map(|(p, span)| if p == pred { Some(span) } else { None })
667                        .unwrap_or(DUMMY_SP);
668                    Some((trait_pred, span))
669                }
670                _ => None,
671            })
672            .find_map(|(trait_pred, span)| match trait_pred.self_ty().kind() {
673                ty::Dynamic(..) => Some(span),
674                _ => None,
675            })
676    }
677
678    fn check_for_illegal_method_calls(&self, pick: &probe::Pick<'_>) {
679        // Disallow calls to the method `drop` defined in the `Drop` trait.
680        if let Some(trait_def_id) = pick.item.trait_container(self.tcx)
681            && let Err(e) = callee::check_legal_trait_for_method_call(
682                self.tcx,
683                self.span,
684                Some(self.self_expr.span),
685                self.call_expr.span,
686                trait_def_id,
687                self.body_id.to_def_id(),
688            )
689        {
690            self.set_tainted_by_errors(e);
691        }
692    }
693
694    fn lint_shadowed_supertrait_items(
695        &self,
696        pick: &probe::Pick<'_>,
697        segment: &hir::PathSegment<'tcx>,
698    ) {
699        if pick.shadowed_candidates.is_empty() {
700            return;
701        }
702
703        let shadower_span = self.tcx.def_span(pick.item.def_id);
704        let subtrait = self.tcx.item_name(pick.item.trait_container(self.tcx).unwrap());
705        let shadower = SupertraitItemShadower { span: shadower_span, subtrait };
706
707        let shadowee = if let [shadowee] = &pick.shadowed_candidates[..] {
708            let shadowee_span = self.tcx.def_span(shadowee.def_id);
709            let supertrait = self.tcx.item_name(shadowee.trait_container(self.tcx).unwrap());
710            SupertraitItemShadowee::Labeled { span: shadowee_span, supertrait }
711        } else {
712            let (traits, spans): (Vec<_>, Vec<_>) = pick
713                .shadowed_candidates
714                .iter()
715                .map(|item| {
716                    (
717                        self.tcx.item_name(item.trait_container(self.tcx).unwrap()),
718                        self.tcx.def_span(item.def_id),
719                    )
720                })
721                .unzip();
722            SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
723        };
724
725        self.tcx.emit_node_span_lint(
726            RESOLVING_TO_ITEMS_SHADOWING_SUPERTRAIT_ITEMS,
727            segment.hir_id,
728            segment.ident.span,
729            SupertraitItemShadowing { shadower, shadowee, item: segment.ident.name, subtrait },
730        );
731    }
732
733    fn lint_ambiguously_glob_imported_traits(
734        &self,
735        pick: &probe::Pick<'_>,
736        segment: &hir::PathSegment<'tcx>,
737    ) {
738        if pick.kind != probe::PickKind::TraitPick(true) {
739            return;
740        }
741        let trait_name = self.tcx.item_name(pick.item.container_id(self.tcx));
742        let import_span = self.tcx.hir_span_if_local(pick.import_ids[0].to_def_id()).unwrap();
743
744        self.tcx.emit_node_lint(
745            AMBIGUOUS_GLOB_IMPORTED_TRAITS,
746            segment.hir_id,
747            rustc_errors::DiagDecorator(|diag| {
748                diag.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Use of ambiguously glob imported trait `{0}`",
                trait_name))
    })format!(
749                    "Use of ambiguously glob imported trait `{trait_name}`"
750                ))
751                .span(segment.ident.span)
752                .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"))
753                .help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Import `{0}` explicitly",
                trait_name))
    })format!("Import `{trait_name}` explicitly"));
754            }),
755        );
756    }
757
758    fn upcast(
759        &mut self,
760        source_trait_ref: ty::PolyTraitRef<'tcx>,
761        target_trait_def_id: DefId,
762    ) -> ty::PolyTraitRef<'tcx> {
763        let upcast_trait_refs =
764            traits::upcast_choices(self.tcx, source_trait_ref, target_trait_def_id);
765
766        // must be exactly one trait ref or we'd get an ambig error etc
767        if let &[upcast_trait_ref] = upcast_trait_refs.as_slice() {
768            upcast_trait_ref
769        } else {
770            self.dcx().span_delayed_bug(
771                self.span,
772                ::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!(
773                    "cannot uniquely upcast `{:?}` to `{:?}`: `{:?}`",
774                    source_trait_ref, target_trait_def_id, upcast_trait_refs
775                ),
776            );
777
778            ty::Binder::dummy(ty::TraitRef::new_from_args(
779                self.tcx,
780                target_trait_def_id,
781                ty::GenericArgs::extend_with_error(self.tcx, target_trait_def_id, &[]),
782            ))
783        }
784    }
785
786    fn instantiate_binder_with_fresh_vars<T>(&self, value: ty::Binder<'tcx, T>) -> T
787    where
788        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
789    {
790        self.fcx.instantiate_binder_with_fresh_vars(
791            self.span,
792            BoundRegionConversionTime::FnCall,
793            value,
794        )
795    }
796}