Skip to main content

rustc_hir_typeck/method/
confirm.rs

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