rustc_hir_typeck/method/
confirm.rs

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