Skip to main content

rustc_hir_typeck/method/
confirm.rs

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