1 use super::{probe, MethodCallee};
3 use crate::{callee, FnCtxt};
5 use rustc_hir::def_id::DefId;
6 use rustc_hir::GenericArg;
7 use rustc_hir_analysis::astconv::{AstConv, CreateSubstsForGenericArgsCtxt, IsMethodCall};
8 use rustc_infer::infer::{self, InferOk};
9 use rustc_middle::traits::{ObligationCauseCode, UnifyReceiverContext};
10 use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCast};
11 use rustc_middle::ty::adjustment::{AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
12 use rustc_middle::ty::fold::TypeFoldable;
13 use rustc_middle::ty::subst::{self, SubstsRef};
14 use rustc_middle::ty::{self, GenericParamDefKind, Ty};
15 use rustc_middle::ty::{InternalSubsts, UserSubsts, UserType};
16 use rustc_span::{Span, DUMMY_SP};
17 use rustc_trait_selection::traits;
22 struct ConfirmContext<'a, 'tcx> {
23 fcx: &'a FnCtxt<'a, 'tcx>,
25 self_expr: &'tcx hir::Expr<'tcx>,
26 call_expr: &'tcx hir::Expr<'tcx>,
29 impl<'a, 'tcx> Deref for ConfirmContext<'a, 'tcx> {
30 type Target = FnCtxt<'a, 'tcx>;
31 fn deref(&self) -> &Self::Target {
37 pub struct ConfirmResult<'tcx> {
38 pub callee: MethodCallee<'tcx>,
39 pub illegal_sized_bound: Option<Span>,
42 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43 pub fn confirm_method(
46 self_expr: &'tcx hir::Expr<'tcx>,
47 call_expr: &'tcx hir::Expr<'tcx>,
48 unadjusted_self_ty: Ty<'tcx>,
49 pick: &probe::Pick<'tcx>,
50 segment: &hir::PathSegment<'_>,
51 ) -> ConfirmResult<'tcx> {
53 "confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})",
54 unadjusted_self_ty, pick, segment.args,
57 let mut confirm_cx = ConfirmContext::new(self, span, self_expr, call_expr);
58 confirm_cx.confirm(unadjusted_self_ty, pick, segment)
62 impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
64 fcx: &'a FnCtxt<'a, 'tcx>,
66 self_expr: &'tcx hir::Expr<'tcx>,
67 call_expr: &'tcx hir::Expr<'tcx>,
68 ) -> ConfirmContext<'a, 'tcx> {
69 ConfirmContext { fcx, span, self_expr, call_expr }
74 unadjusted_self_ty: Ty<'tcx>,
75 pick: &probe::Pick<'tcx>,
76 segment: &hir::PathSegment<'_>,
77 ) -> ConfirmResult<'tcx> {
78 // Adjust the self expression the user provided and obtain the adjusted type.
79 let self_ty = self.adjust_self_ty(unadjusted_self_ty, &pick);
81 // Create substitutions for the method's type parameters.
82 let rcvr_substs = self.fresh_receiver_substs(self_ty, &pick);
83 let all_substs = self.instantiate_method_substs(&pick, segment, rcvr_substs);
85 debug!("rcvr_substs={rcvr_substs:?}, all_substs={all_substs:?}");
87 // Create the final signature for the method, replacing late-bound regions.
88 let (method_sig, method_predicates) = self.instantiate_method_sig(&pick, all_substs);
90 // If there is a `Self: Sized` bound and `Self` is a trait object, it is possible that
91 // something which derefs to `Self` actually implements the trait and the caller
92 // wanted to make a static dispatch on it but forgot to import the trait.
93 // See test `src/test/ui/issue-35976.rs`.
95 // In that case, we'll error anyway, but we'll also re-run the search with all traits
96 // in scope, and if we find another method which can be used, we'll output an
97 // appropriate hint suggesting to import the trait.
98 let filler_substs = rcvr_substs
99 .extend_to(self.tcx, pick.item.def_id, |def, _| self.tcx.mk_param_from_def(def));
100 let illegal_sized_bound = self.predicates_require_illegal_sized_bound(
101 &self.tcx.predicates_of(pick.item.def_id).instantiate(self.tcx, filler_substs),
104 // Unify the (adjusted) self type with what the method expects.
106 // SUBTLE: if we want good error messages, because of "guessing" while matching
107 // traits, no trait system method can be called before this point because they
108 // could alter our Self-type, except for normalizing the receiver from the
109 // signature (which is also done during probing).
110 let method_sig_rcvr = self.normalize(self.span, method_sig.inputs()[0]);
112 "confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}",
113 self_ty, method_sig_rcvr, method_sig, method_predicates
115 self.unify_receivers(self_ty, method_sig_rcvr, &pick, all_substs);
117 let (method_sig, method_predicates) =
118 self.normalize(self.span, (method_sig, method_predicates));
119 let method_sig = ty::Binder::dummy(method_sig);
121 // Make sure nobody calls `drop()` explicitly.
122 self.enforce_illegal_method_limitations(&pick);
124 // Add any trait/regions obligations specified on the method's type parameters.
125 // We won't add these if we encountered an illegal sized bound, so that we can use
126 // a custom error in that case.
127 if illegal_sized_bound.is_none() {
128 self.add_obligations(
129 self.tcx.mk_fn_ptr(method_sig),
136 // Create the final `MethodCallee`.
137 let callee = MethodCallee {
138 def_id: pick.item.def_id,
140 sig: method_sig.skip_binder(),
142 ConfirmResult { callee, illegal_sized_bound }
145 ///////////////////////////////////////////////////////////////////////////
150 unadjusted_self_ty: Ty<'tcx>,
151 pick: &probe::Pick<'tcx>,
153 // Commit the autoderefs by calling `autoderef` again, but this
154 // time writing the results into the various typeck results.
155 let mut autoderef = self.autoderef(self.call_expr.span, unadjusted_self_ty);
156 let Some((ty, n)) = autoderef.nth(pick.autoderefs) else {
157 return self.tcx.ty_error_with_message(
158 rustc_span::DUMMY_SP,
159 &format!("failed autoderef {}", pick.autoderefs),
162 assert_eq!(n, pick.autoderefs);
164 let mut adjustments = self.adjust_steps(&autoderef);
165 let mut target = self.structurally_resolved_type(autoderef.span(), ty);
167 match pick.autoref_or_ptr_adjustment {
168 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl, unsize }) => {
169 let region = self.next_region_var(infer::Autoref(self.span));
170 // Type we're wrapping in a reference, used later for unsizing
171 let base_ty = target;
173 target = self.tcx.mk_ref(region, ty::TypeAndMut { mutbl, ty: target });
175 // Method call receivers are the primary use case
176 // for two-phase borrows.
177 let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::Yes);
179 adjustments.push(Adjustment {
180 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
185 let unsized_ty = if let ty::Array(elem_ty, _) = base_ty.kind() {
186 self.tcx.mk_slice(*elem_ty)
189 "AutorefOrPtrAdjustment's unsize flag should only be set for array ty, found {}",
195 .mk_ref(region, ty::TypeAndMut { mutbl: mutbl.into(), ty: unsized_ty });
197 .push(Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target });
200 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) => {
201 target = match target.kind() {
202 &ty::RawPtr(ty::TypeAndMut { ty, mutbl }) => {
203 assert!(mutbl.is_mut());
204 self.tcx.mk_ptr(ty::TypeAndMut { mutbl: hir::Mutability::Not, ty })
206 other => panic!("Cannot adjust receiver type {:?} to const ptr", other),
209 adjustments.push(Adjustment {
210 kind: Adjust::Pointer(PointerCast::MutToConstPointer),
217 self.register_predicates(autoderef.into_obligations());
219 // Write out the final adjustments.
220 self.apply_adjustments(self.self_expr, adjustments);
225 /// Returns a set of substitutions for the method *receiver* where all type and region
226 /// parameters are instantiated with fresh variables. This substitution does not include any
227 /// parameters declared on the method itself.
229 /// Note that this substitution may include late-bound regions from the impl level. If so,
230 /// these are instantiated later in the `instantiate_method_sig` routine.
231 fn fresh_receiver_substs(
234 pick: &probe::Pick<'tcx>,
235 ) -> SubstsRef<'tcx> {
237 probe::InherentImplPick => {
238 let impl_def_id = pick.item.container_id(self.tcx);
240 self.tcx.impl_trait_ref(impl_def_id).is_none(),
241 "impl {:?} is not an inherent impl",
244 self.fresh_substs_for_item(self.span, impl_def_id)
247 probe::ObjectPick => {
248 let trait_def_id = pick.item.container_id(self.tcx);
249 self.extract_existential_trait_ref(self_ty, |this, object_ty, principal| {
250 // The object data has no entry for the Self
251 // Type. For the purposes of this method call, we
252 // substitute the object type itself. This
253 // wouldn't be a sound substitution in all cases,
254 // since each instance of the object type is a
255 // different existential and hence could match
256 // distinct types (e.g., if `Self` appeared as an
257 // argument type), but those cases have already
258 // been ruled out when we deemed the trait to be
260 let original_poly_trait_ref = principal.with_self_ty(this.tcx, object_ty);
261 let upcast_poly_trait_ref = this.upcast(original_poly_trait_ref, trait_def_id);
262 let upcast_trait_ref =
263 this.replace_bound_vars_with_fresh_vars(upcast_poly_trait_ref);
265 "original_poly_trait_ref={:?} upcast_trait_ref={:?} target_trait={:?}",
266 original_poly_trait_ref, upcast_trait_ref, trait_def_id
268 upcast_trait_ref.substs
272 probe::TraitPick => {
273 let trait_def_id = pick.item.container_id(self.tcx);
275 // Make a trait reference `$0 : Trait<$1...$n>`
276 // consisting entirely of type variables. Later on in
277 // the process we will unify the transformed-self-type
278 // of the method with the actual type in order to
279 // unify some of these variables.
280 self.fresh_substs_for_item(self.span, trait_def_id)
283 probe::WhereClausePick(poly_trait_ref) => {
284 // Where clauses can have bound regions in them. We need to instantiate
285 // those to convert from a poly-trait-ref to a trait-ref.
286 self.replace_bound_vars_with_fresh_vars(poly_trait_ref).substs
291 fn extract_existential_trait_ref<R, F>(&mut self, self_ty: Ty<'tcx>, mut closure: F) -> R
293 F: FnMut(&mut ConfirmContext<'a, 'tcx>, Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>) -> R,
295 // If we specified that this is an object method, then the
296 // self-type ought to be something that can be dereferenced to
297 // yield an object-type (e.g., `&Object` or `Box<Object>`
300 // FIXME: this feels, like, super dubious
302 .autoderef(self.span, self_ty)
303 .include_raw_pointers()
304 .find_map(|(ty, _)| match ty.kind() {
305 ty::Dynamic(data, ..) => Some(closure(
308 data.principal().unwrap_or_else(|| {
309 span_bug!(self.span, "calling trait method on empty object?")
317 "self-type `{}` for ObjectPick never dereferenced to an object",
323 fn instantiate_method_substs(
325 pick: &probe::Pick<'tcx>,
326 seg: &hir::PathSegment<'_>,
327 parent_substs: SubstsRef<'tcx>,
328 ) -> SubstsRef<'tcx> {
329 // Determine the values for the generic parameters of the method.
330 // If they were not explicitly supplied, just construct fresh
332 let generics = self.tcx.generics_of(pick.item.def_id);
334 let arg_count_correct = <dyn AstConv<'_>>::check_generic_arg_count_for_call(
343 // Create subst for early-bound lifetime parameters, combining
344 // parameters from the type and those from the method.
345 assert_eq!(generics.parent_count, parent_substs.len());
347 struct MethodSubstsCtxt<'a, 'tcx> {
348 cfcx: &'a ConfirmContext<'a, 'tcx>,
349 pick: &'a probe::Pick<'tcx>,
350 seg: &'a hir::PathSegment<'a>,
352 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for MethodSubstsCtxt<'a, 'tcx> {
356 ) -> (Option<&'a hir::GenericArgs<'a>>, bool) {
357 if def_id == self.pick.item.def_id {
358 if let Some(data) = self.seg.args {
359 return (Some(data), false);
367 param: &ty::GenericParamDef,
368 arg: &GenericArg<'_>,
369 ) -> subst::GenericArg<'tcx> {
370 match (¶m.kind, arg) {
371 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
372 <dyn AstConv<'_>>::ast_region_to_region(self.cfcx.fcx, lt, Some(param))
375 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
376 self.cfcx.to_ty(ty).raw.into()
378 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
379 self.cfcx.const_arg_to_const(&ct.value, param.def_id).into()
381 (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
382 self.cfcx.ty_infer(Some(param), inf.span).into()
384 (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
385 let tcx = self.cfcx.tcx();
386 self.cfcx.ct_infer(tcx.type_of(param.def_id), Some(param), inf.span).into()
394 _substs: Option<&[subst::GenericArg<'tcx>]>,
395 param: &ty::GenericParamDef,
397 ) -> subst::GenericArg<'tcx> {
398 self.cfcx.var_for_def(self.cfcx.span, param)
402 let substs = <dyn AstConv<'_>>::create_substs_for_generic_args(
409 &mut MethodSubstsCtxt { cfcx: self, pick, seg },
412 // When the method is confirmed, the `substs` includes
413 // parameters from not just the method, but also the impl of
414 // the method -- in particular, the `Self` type will be fully
415 // resolved. However, those are not something that the "user
416 // specified" -- i.e., those types come from the inferred type
417 // of the receiver, not something the user wrote. So when we
418 // create the user-substs, we want to replace those earlier
419 // types with just the types that the user actually wrote --
420 // that is, those that appear on the *method itself*.
422 // As an example, if the user wrote something like
423 // `foo.bar::<u32>(...)` -- the `Self` type here will be the
424 // type of `foo` (possibly adjusted), but we don't want to
425 // include that. We want just the `[_, u32]` part.
426 if !substs.is_empty() && !generics.params.is_empty() {
427 let user_type_annotation = self.probe(|_| {
428 let user_substs = UserSubsts {
429 substs: InternalSubsts::for_item(self.tcx, pick.item.def_id, |param, _| {
430 let i = param.index as usize;
431 if i < generics.parent_count {
432 self.fcx.var_for_def(DUMMY_SP, param)
437 user_self_ty: None, // not relevant here
440 self.fcx.canonicalize_user_type_annotation(UserType::TypeOf(
446 debug!("instantiate_method_substs: user_type_annotation={:?}", user_type_annotation);
447 self.fcx.write_user_type_annotation(self.call_expr.hir_id, user_type_annotation);
450 self.normalize(self.span, substs)
456 method_self_ty: Ty<'tcx>,
457 pick: &probe::Pick<'tcx>,
458 substs: SubstsRef<'tcx>,
461 "unify_receivers: self_ty={:?} method_self_ty={:?} span={:?} pick={:?}",
462 self_ty, method_self_ty, self.span, pick
464 let cause = self.cause(
466 ObligationCauseCode::UnifyReceiver(Box::new(UnifyReceiverContext {
467 assoc_item: pick.item,
468 param_env: self.param_env,
472 match self.at(&cause, self.param_env).sup(method_self_ty, self_ty) {
473 Ok(InferOk { obligations, value: () }) => {
474 self.register_predicates(obligations);
479 "{} was a subtype of {} but now is not?",
487 // NOTE: this returns the *unnormalized* predicates and method sig. Because of
488 // inference guessing, the predicates and method signature can't be normalized
489 // until we unify the `Self` type.
490 fn instantiate_method_sig(
492 pick: &probe::Pick<'tcx>,
493 all_substs: SubstsRef<'tcx>,
494 ) -> (ty::FnSig<'tcx>, ty::InstantiatedPredicates<'tcx>) {
495 debug!("instantiate_method_sig(pick={:?}, all_substs={:?})", pick, all_substs);
497 // Instantiate the bounds on the method with the
498 // type/early-bound-regions substitutions performed. There can
499 // be no late-bound regions appearing here.
500 let def_id = pick.item.def_id;
501 let method_predicates = self.tcx.predicates_of(def_id).instantiate(self.tcx, all_substs);
503 debug!("method_predicates after subst = {:?}", method_predicates);
505 let sig = self.tcx.bound_fn_sig(def_id);
507 let sig = sig.subst(self.tcx, all_substs);
508 debug!("type scheme substituted, sig={:?}", sig);
510 let sig = self.replace_bound_vars_with_fresh_vars(sig);
511 debug!("late-bound lifetimes from method instantiated, sig={:?}", sig);
513 (sig, method_predicates)
519 all_substs: SubstsRef<'tcx>,
520 method_predicates: ty::InstantiatedPredicates<'tcx>,
524 "add_obligations: fty={:?} all_substs={:?} method_predicates={:?} def_id={:?}",
525 fty, all_substs, method_predicates, def_id
528 // FIXME: could replace with the following, but we already calculated `method_predicates`,
529 // so we just call `predicates_for_generics` directly to avoid redoing work.
530 // `self.add_required_obligations(self.span, def_id, &all_substs);`
531 for obligation in traits::predicates_for_generics(
533 let code = if span.is_dummy() {
534 ObligationCauseCode::ExprItemObligation(def_id, self.call_expr.hir_id, idx)
536 ObligationCauseCode::ExprBindingObligation(
539 self.call_expr.hir_id,
543 traits::ObligationCause::new(self.span, self.body_id, code)
548 self.register_predicate(obligation);
551 // this is a projection from a trait reference, so we have to
552 // make sure that the trait reference inputs are well-formed.
553 self.add_wf_bounds(all_substs, self.call_expr);
555 // the function type must also be well-formed (this is not
556 // implied by the substs being well-formed because of inherent
557 // impls and late-bound regions - see issue #28609).
558 self.register_wf_obligation(fty.into(), self.span, traits::WellFormed(None));
561 ///////////////////////////////////////////////////////////////////////////
564 fn predicates_require_illegal_sized_bound(
566 predicates: &ty::InstantiatedPredicates<'tcx>,
568 let sized_def_id = self.tcx.lang_items().sized_trait()?;
570 traits::elaborate_predicates(self.tcx, predicates.predicates.iter().copied())
571 // We don't care about regions here.
572 .filter_map(|obligation| match obligation.predicate.kind().skip_binder() {
573 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
574 if trait_pred.def_id() == sized_def_id =>
576 let span = iter::zip(&predicates.predicates, &predicates.spans)
579 if *p == obligation.predicate { Some(*span) } else { None }
582 .unwrap_or(rustc_span::DUMMY_SP);
583 Some((trait_pred, span))
587 .find_map(|(trait_pred, span)| match trait_pred.self_ty().kind() {
588 ty::Dynamic(..) => Some(span),
593 fn enforce_illegal_method_limitations(&self, pick: &probe::Pick<'_>) {
594 // Disallow calls to the method `drop` defined in the `Drop` trait.
595 if let Some(trait_def_id) = pick.item.trait_container(self.tcx) {
596 callee::check_legal_trait_for_method_call(
599 Some(self.self_expr.span),
608 source_trait_ref: ty::PolyTraitRef<'tcx>,
609 target_trait_def_id: DefId,
610 ) -> ty::PolyTraitRef<'tcx> {
611 let upcast_trait_refs =
612 traits::upcast_choices(self.tcx, source_trait_ref, target_trait_def_id);
614 // must be exactly one trait ref or we'd get an ambig error etc
615 if upcast_trait_refs.len() != 1 {
618 "cannot uniquely upcast `{:?}` to `{:?}`: `{:?}`",
625 upcast_trait_refs.into_iter().next().unwrap()
628 fn replace_bound_vars_with_fresh_vars<T>(&self, value: ty::Binder<'tcx, T>) -> T
630 T: TypeFoldable<'tcx> + Copy,
632 self.fcx.replace_bound_vars_with_fresh_vars(self.span, infer::FnCall, value)