Skip to main content

rustc_hir_typeck/method/
confirm.rs

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