1 use super::method::probe::{IsSuggestion, Mode, ProbeScope};
2 use super::method::MethodCallee;
3 use super::{DefIdOrName, Expectation, FnCtxt, TupleArgumentsFlag};
4 use crate::type_error_struct;
6 use rustc_ast::util::parser::PREC_POSTFIX;
7 use rustc_errors::{struct_span_err, Applicability, Diagnostic, StashKey};
9 use rustc_hir::def::{self, Namespace, Res};
10 use rustc_hir::def_id::DefId;
13 traits::{self, Obligation},
16 infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
17 traits::ObligationCause,
19 use rustc_middle::ty::adjustment::{
20 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
22 use rustc_middle::ty::SubstsRef;
23 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable};
24 use rustc_span::def_id::LocalDefId;
25 use rustc_span::symbol::{sym, Ident};
27 use rustc_target::spec::abi;
28 use rustc_trait_selection::autoderef::Autoderef;
29 use rustc_trait_selection::infer::InferCtxtExt as _;
30 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
34 /// Checks that it is legal to call methods of the trait corresponding
35 /// to `trait_id` (this only cares about the trait, not the specific
36 /// method that is called).
37 pub fn check_legal_trait_for_method_call(
40 receiver: Option<Span>,
44 if tcx.lang_items().drop_trait() == Some(trait_id) {
45 let mut err = struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
46 err.span_label(span, "explicit destructor calls not allowed");
48 let (sp, suggestion) = receiver
49 .and_then(|s| tcx.sess.source_map().span_to_snippet(s).ok())
50 .filter(|snippet| !snippet.is_empty())
51 .map(|snippet| (expr_span, format!("drop({snippet})")))
52 .unwrap_or_else(|| (span, "drop".to_string()));
56 "consider using `drop` function",
58 Applicability::MaybeIncorrect,
68 DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
69 /// E.g., enum variant constructors.
70 Overloaded(MethodCallee<'tcx>),
73 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
76 call_expr: &'tcx hir::Expr<'tcx>,
77 callee_expr: &'tcx hir::Expr<'tcx>,
78 arg_exprs: &'tcx [hir::Expr<'tcx>],
79 expected: Expectation<'tcx>,
81 let original_callee_ty = match &callee_expr.kind {
82 hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
83 .check_expr_with_expectation_and_args(
85 Expectation::NoExpectation,
88 _ => self.check_expr(callee_expr),
91 let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty);
93 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
94 let mut result = None;
95 while result.is_none() && autoderef.next().is_some() {
96 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
98 self.register_predicates(autoderef.into_obligations());
100 let output = match result {
102 // this will report an error since original_callee_ty is not a fn
103 self.confirm_builtin_call(
112 Some(CallStep::Builtin(callee_ty)) => {
113 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
116 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
117 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
120 Some(CallStep::Overloaded(method_callee)) => {
121 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
125 // we must check that return type of called functions is WF:
126 self.register_wf_obligation(output.into(), call_expr.span, traits::WellFormed(None));
131 fn try_overloaded_call_step(
133 call_expr: &'tcx hir::Expr<'tcx>,
134 callee_expr: &'tcx hir::Expr<'tcx>,
135 arg_exprs: &'tcx [hir::Expr<'tcx>],
136 autoderef: &Autoderef<'a, 'tcx>,
137 ) -> Option<CallStep<'tcx>> {
139 self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
141 "try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
142 call_expr, adjusted_ty
145 // If the callee is a bare function or a closure, then we're all set.
146 match *adjusted_ty.kind() {
147 ty::FnDef(..) | ty::FnPtr(_) => {
148 let adjustments = self.adjust_steps(autoderef);
149 self.apply_adjustments(callee_expr, adjustments);
150 return Some(CallStep::Builtin(adjusted_ty));
153 ty::Closure(def_id, substs) => {
154 let def_id = def_id.expect_local();
156 // Check whether this is a call to a closure where we
157 // haven't yet decided on whether the closure is fn vs
158 // fnmut vs fnonce. If so, we have to defer further processing.
159 if self.closure_kind(substs).is_none() {
160 let closure_sig = substs.as_closure().sig();
161 let closure_sig = self.replace_bound_vars_with_fresh_vars(
166 let adjustments = self.adjust_steps(autoderef);
167 self.record_deferred_call_resolution(
169 DeferredCallResolution {
175 closure_substs: substs,
178 return Some(CallStep::DeferredClosure(def_id, closure_sig));
182 // Hack: we know that there are traits implementing Fn for &F
183 // where F:Fn and so forth. In the particular case of types
184 // like `x: &mut FnMut()`, if there is a call `x()`, we would
185 // normally translate to `FnMut::call_mut(&mut x, ())`, but
186 // that winds up requiring `mut x: &mut FnMut()`. A little
187 // over the top. The simplest fix by far is to just ignore
188 // this case and deref again, so we wind up with
189 // `FnMut::call_mut(&mut *x, ())`.
190 ty::Ref(..) if autoderef.step_count() == 0 => {
201 // Now, we look for the implementation of a Fn trait on the object's type.
202 // We first do it with the explicit instruction to look for an impl of
203 // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
204 // to the number of call parameters.
205 // If that fails (or_else branch), we try again without specifying the
206 // shape of the tuple (hence the None). This allows to detect an Fn trait
207 // is implemented, and use this information for diagnostic.
208 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
209 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
210 .map(|(autoref, method)| {
211 let mut adjustments = self.adjust_steps(autoderef);
212 adjustments.extend(autoref);
213 self.apply_adjustments(callee_expr, adjustments);
214 CallStep::Overloaded(method)
218 fn try_overloaded_call_traits(
220 call_expr: &hir::Expr<'_>,
221 adjusted_ty: Ty<'tcx>,
222 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
223 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
224 // Try the options that are least restrictive on the caller first.
225 for (opt_trait_def_id, method_name, borrow) in [
226 (self.tcx.lang_items().fn_trait(), Ident::with_dummy_span(sym::call), true),
227 (self.tcx.lang_items().fn_mut_trait(), Ident::with_dummy_span(sym::call_mut), true),
228 (self.tcx.lang_items().fn_once_trait(), Ident::with_dummy_span(sym::call_once), false),
230 let Some(trait_def_id) = opt_trait_def_id else { continue };
232 let opt_input_types = opt_arg_exprs.map(|arg_exprs| {
233 [self.tcx.mk_tup(arg_exprs.iter().map(|e| {
234 self.next_ty_var(TypeVariableOrigin {
235 kind: TypeVariableOriginKind::TypeInference,
240 let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
242 if let Some(ok) = self.lookup_method_in_trait(
249 let method = self.register_infer_ok_obligations(ok);
250 let mut autoref = None;
252 // Check for &self vs &mut self in the method signature. Since this is either
253 // the Fn or FnMut trait, it should be one of those.
254 let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind() else {
255 // The `fn`/`fn_mut` lang item is ill-formed, which should have
256 // caused an error elsewhere.
259 .delay_span_bug(call_expr.span, "input to call/call_mut is not a ref?");
263 let mutbl = match mutbl {
264 hir::Mutability::Not => AutoBorrowMutability::Not,
265 hir::Mutability::Mut => AutoBorrowMutability::Mut {
266 // For initial two-phase borrow
267 // deployment, conservatively omit
268 // overloaded function call ops.
269 allow_two_phase_borrow: AllowTwoPhase::No,
272 autoref = Some(Adjustment {
273 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
274 target: method.sig.inputs()[0],
277 return Some((autoref, method));
284 /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
285 /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
286 fn identify_bad_closure_def_and_call(
288 err: &mut Diagnostic,
290 callee_node: &hir::ExprKind<'_>,
293 let hir = self.tcx.hir();
294 let parent_hir_id = hir.get_parent_node(hir_id);
295 let parent_node = hir.get(parent_hir_id);
297 hir::Node::Expr(hir::Expr {
298 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, body, .. }),
301 hir::ExprKind::Block(..),
302 ) = (parent_node, callee_node)
304 let fn_decl_span = if hir.body(body).generator_kind
305 == Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure))
307 // Actually need to unwrap a few more layers of HIR to get to
308 // the _real_ closure...
309 let async_closure = hir.get_parent_node(hir.get_parent_node(parent_hir_id));
310 if let hir::Node::Expr(hir::Expr {
311 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
313 }) = hir.get(async_closure)
323 let start = fn_decl_span.shrink_to_lo();
324 let end = callee_span.shrink_to_hi();
325 err.multipart_suggestion(
326 "if you meant to create this closure and immediately call it, surround the \
327 closure with parentheses",
328 vec![(start, "(".to_string()), (end, ")".to_string())],
329 Applicability::MaybeIncorrect,
334 /// Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the
335 /// likely intention is to create an array containing tuples.
336 fn maybe_suggest_bad_array_definition(
338 err: &mut Diagnostic,
339 call_expr: &'tcx hir::Expr<'tcx>,
340 callee_expr: &'tcx hir::Expr<'tcx>,
342 let hir_id = self.tcx.hir().get_parent_node(call_expr.hir_id);
343 let parent_node = self.tcx.hir().get(hir_id);
345 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
346 hir::ExprKind::Tup(exp),
347 hir::ExprKind::Call(_, args),
348 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
349 && args.len() == exp.len()
351 let start = callee_expr.span.shrink_to_hi();
354 "consider separating array elements with a comma",
356 Applicability::MaybeIncorrect,
363 fn confirm_builtin_call(
365 call_expr: &'tcx hir::Expr<'tcx>,
366 callee_expr: &'tcx hir::Expr<'tcx>,
368 arg_exprs: &'tcx [hir::Expr<'tcx>],
369 expected: Expectation<'tcx>,
371 let (fn_sig, def_id) = match *callee_ty.kind() {
372 ty::FnDef(def_id, subst) => {
373 let fn_sig = self.tcx.bound_fn_sig(def_id).subst(self.tcx, subst);
375 // Unit testing: function items annotated with
376 // `#[rustc_evaluate_where_clauses]` trigger special output
377 // to let us test the trait evaluation system.
378 if self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses) {
379 let predicates = self.tcx.predicates_of(def_id);
380 let predicates = predicates.instantiate(self.tcx, subst);
381 for (predicate, predicate_span) in
382 predicates.predicates.iter().zip(&predicates.spans)
384 let obligation = Obligation::new(
385 ObligationCause::dummy_with_span(callee_expr.span),
389 let result = self.evaluate_obligation(&obligation);
394 &format!("evaluate({:?}) = {:?}", predicate, result),
396 .span_label(*predicate_span, "predicate")
400 (fn_sig, Some(def_id))
402 ty::FnPtr(sig) => (sig, None),
404 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
405 && let [segment] = path.segments
406 && let Some(mut diag) = self
410 .steal_diagnostic(segment.ident.span, StashKey::CallIntoMethod)
412 // Try suggesting `foo(a)` -> `a.foo()` if possible.
414 self.suggest_call_as_method(
429 self.report_invalid_callee(call_expr, callee_expr, callee_ty, arg_exprs);
431 // This is the "default" function signature, used in case of error.
432 // In that case, we check each argument against "error" in order to
433 // set up all the node type bindings.
435 ty::Binder::dummy(self.tcx.mk_fn_sig(
436 self.err_args(arg_exprs.len()).into_iter(),
439 hir::Unsafety::Normal,
447 // Replace any late-bound regions that appear in the function
448 // signature with region variables. We also have to
449 // renormalize the associated types at this point, since they
450 // previously appeared within a `Binder<>` and hence would not
451 // have been normalized before.
452 let fn_sig = self.replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, fn_sig);
453 let fn_sig = self.normalize_associated_types_in(call_expr.span, fn_sig);
455 // Call the generic checker.
456 let expected_arg_tys = self.expected_inputs_for_expected_output(
462 self.check_argument_types(
469 TupleArgumentsFlag::DontTupleArguments,
476 /// Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)`
477 /// and suggesting the fix if the method probe is successful.
478 fn suggest_call_as_method(
480 diag: &mut Diagnostic,
481 segment: &'tcx hir::PathSegment<'tcx>,
482 arg_exprs: &'tcx [hir::Expr<'tcx>],
483 call_expr: &'tcx hir::Expr<'tcx>,
484 expected: Expectation<'tcx>,
485 ) -> Option<Ty<'tcx>> {
486 if let [callee_expr, rest @ ..] = arg_exprs {
487 let callee_ty = self.check_expr(callee_expr);
488 // First, do a probe with `IsSuggestion(true)` to avoid emitting
489 // any strange errors. If it's successful, then we'll do a true
499 // We didn't record the in scope traits during late resolution
500 // so we need to probe AllTraits unfortunately
501 ProbeScope::AllTraits,
506 let pick = self.confirm_method(
514 if pick.illegal_sized_bound.is_some() {
518 let up_to_rcvr_span = segment.ident.span.until(callee_expr.span);
519 let rest_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
520 let rest_snippet = if let Some(first) = rest.first() {
524 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
529 if let Ok(rest_snippet) = rest_snippet {
530 let sugg = if callee_expr.precedence().order() >= PREC_POSTFIX {
532 (up_to_rcvr_span, "".to_string()),
533 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
537 (up_to_rcvr_span, "(".to_string()),
538 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
541 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
542 diag.multipart_suggestion(
544 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
546 .associated_item(pick.callee.def_id)
547 .trait_container(self.tcx)
550 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
555 Applicability::MaybeIncorrect,
558 // Let's check the method fully now
559 let return_ty = self.check_method_argument_types(
564 TupleArgumentsFlag::DontTupleArguments,
568 return Some(return_ty);
575 fn report_invalid_callee(
577 call_expr: &'tcx hir::Expr<'tcx>,
578 callee_expr: &'tcx hir::Expr<'tcx>,
580 arg_exprs: &'tcx [hir::Expr<'tcx>],
582 let mut unit_variant = None;
583 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
584 && let Res::Def(def::DefKind::Ctor(kind, def::CtorKind::Const), _)
585 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
586 // Only suggest removing parens if there are no arguments
587 && arg_exprs.is_empty()
589 let descr = match kind {
590 def::CtorOf::Struct => "struct",
591 def::CtorOf::Variant => "enum variant",
593 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
594 unit_variant = Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(qpath)));
597 let callee_ty = self.resolve_vars_if_possible(callee_ty);
598 let mut err = type_error_struct!(
603 "expected function, found {}",
604 match &unit_variant {
605 Some((_, kind, path)) => format!("{kind} `{path}`"),
606 None => format!("`{callee_ty}`"),
610 self.identify_bad_closure_def_and_call(
617 if let Some((removal_span, kind, path)) = &unit_variant {
618 err.span_suggestion_verbose(
621 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
624 Applicability::MachineApplicable,
628 let mut inner_callee_path = None;
629 let def = match callee_expr.kind {
630 hir::ExprKind::Path(ref qpath) => {
631 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
633 hir::ExprKind::Call(ref inner_callee, _) => {
634 // If the call spans more than one line and the callee kind is
635 // itself another `ExprCall`, that's a clue that we might just be
636 // missing a semicolon (Issue #51055)
637 let call_is_multiline = self.tcx.sess.source_map().is_multiline(call_expr.span);
638 if call_is_multiline {
640 callee_expr.span.shrink_to_hi(),
641 "consider using a semicolon here",
643 Applicability::MaybeIncorrect,
646 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
647 inner_callee_path = Some(inner_qpath);
648 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
656 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
657 if let Some((maybe_def, output_ty, _)) =
658 self.extract_callable_info(callee_expr, callee_ty)
659 && !self.type_is_sized_modulo_regions(self.param_env, output_ty, callee_expr.span)
661 let descr = match maybe_def {
662 DefIdOrName::DefId(def_id) => self.tcx.def_kind(def_id).descr(def_id),
663 DefIdOrName::Name(name) => name,
667 format!("this {descr} returns an unsized value `{output_ty}`, so it cannot be called")
669 if let DefIdOrName::DefId(def_id) = maybe_def
670 && let Some(def_span) = self.tcx.hir().span_if_local(def_id)
672 err.span_label(def_span, "the callable type is defined here");
675 err.span_label(call_expr.span, "call expression requires function");
679 if let Some(span) = self.tcx.hir().res_span(def) {
680 let callee_ty = callee_ty.to_string();
681 let label = match (unit_variant, inner_callee_path) {
682 (Some((_, kind, path)), _) => Some(format!("{kind} `{path}` defined here")),
683 (_, Some(hir::QPath::Resolved(_, path))) => self
687 .span_to_snippet(path.span)
689 .map(|p| format!("`{p}` defined here returns `{callee_ty}`")),
692 // Emit a different diagnostic for local variables, as they are not
693 // type definitions themselves, but rather variables *of* that type.
694 Res::Local(hir_id) => Some(format!(
695 "`{}` has type `{}`",
696 self.tcx.hir().name(hir_id),
699 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
700 Some(format!("`{}` defined here", self.tcx.def_path_str(def_id),))
702 _ => Some(format!("`{callee_ty}` defined here")),
706 if let Some(label) = label {
707 err.span_label(span, label);
713 fn confirm_deferred_closure_call(
715 call_expr: &'tcx hir::Expr<'tcx>,
716 arg_exprs: &'tcx [hir::Expr<'tcx>],
717 expected: Expectation<'tcx>,
718 closure_def_id: LocalDefId,
719 fn_sig: ty::FnSig<'tcx>,
721 // `fn_sig` is the *signature* of the closure being called. We
722 // don't know the full details yet (`Fn` vs `FnMut` etc), but we
723 // do know the types expected for each argument and the return
726 let expected_arg_tys = self.expected_inputs_for_expected_output(
733 self.check_argument_types(
740 TupleArgumentsFlag::TupleArguments,
741 Some(closure_def_id.to_def_id()),
747 fn confirm_overloaded_call(
749 call_expr: &'tcx hir::Expr<'tcx>,
750 arg_exprs: &'tcx [hir::Expr<'tcx>],
751 expected: Expectation<'tcx>,
752 method_callee: MethodCallee<'tcx>,
754 let output_type = self.check_method_argument_types(
759 TupleArgumentsFlag::TupleArguments,
763 self.write_method_call(call_expr.hir_id, method_callee);
769 pub struct DeferredCallResolution<'tcx> {
770 call_expr: &'tcx hir::Expr<'tcx>,
771 callee_expr: &'tcx hir::Expr<'tcx>,
772 adjusted_ty: Ty<'tcx>,
773 adjustments: Vec<Adjustment<'tcx>>,
774 fn_sig: ty::FnSig<'tcx>,
775 closure_substs: SubstsRef<'tcx>,
778 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
779 pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
780 debug!("DeferredCallResolution::resolve() {:?}", self);
782 // we should not be invoked until the closure kind has been
783 // determined by upvar inference
784 assert!(fcx.closure_kind(self.closure_substs).is_some());
786 // We may now know enough to figure out fn vs fnmut etc.
787 match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
788 Some((autoref, method_callee)) => {
789 // One problem is that when we get here, we are going
790 // to have a newly instantiated function signature
791 // from the call trait. This has to be reconciled with
792 // the older function signature we had before. In
793 // principle we *should* be able to fn_sigs(), but we
794 // can't because of the annoying need for a TypeTrace.
795 // (This always bites me, should find a way to
797 let method_sig = method_callee.sig;
799 debug!("attempt_resolution: method_callee={:?}", method_callee);
801 for (method_arg_ty, self_arg_ty) in
802 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
804 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
807 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
809 let mut adjustments = self.adjustments;
810 adjustments.extend(autoref);
811 fcx.apply_adjustments(self.callee_expr, adjustments);
813 fcx.write_method_call(self.call_expr.hir_id, method_callee);
816 // This can happen if `#![no_core]` is used and the `fn/fn_mut/fn_once`
817 // lang items are not defined (issue #86238).
818 let mut err = fcx.inh.tcx.sess.struct_span_err(
820 "failed to find an overloaded call trait for closure call",
823 "make sure the `fn`/`fn_mut`/`fn_once` lang items are defined \
824 and have associated `call`/`call_mut`/`call_once` functions",