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