1 use super::method::MethodCallee;
2 use super::{Expectation, FnCtxt, TupleArgumentsFlag};
3 use crate::type_error_struct;
5 use rustc_errors::{struct_span_err, Applicability, Diagnostic};
7 use rustc_hir::def::{Namespace, Res};
8 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
11 traits::{self, Obligation},
14 infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
15 traits::ObligationCause,
17 use rustc_middle::ty::adjustment::{
18 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
20 use rustc_middle::ty::subst::{Subst, SubstsRef};
21 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
22 use rustc_span::symbol::{sym, Ident};
24 use rustc_target::spec::abi;
25 use rustc_trait_selection::autoderef::Autoderef;
26 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
29 /// Checks that it is legal to call methods of the trait corresponding
30 /// to `trait_id` (this only cares about the trait, not the specific
31 /// method that is called).
32 pub fn check_legal_trait_for_method_call(
35 receiver: Option<Span>,
39 if tcx.lang_items().drop_trait() == Some(trait_id) {
40 let mut err = struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
41 err.span_label(span, "explicit destructor calls not allowed");
43 let (sp, suggestion) = receiver
44 .and_then(|s| tcx.sess.source_map().span_to_snippet(s).ok())
45 .filter(|snippet| !snippet.is_empty())
46 .map(|snippet| (expr_span, format!("drop({snippet})")))
47 .unwrap_or_else(|| (span, "drop".to_string()));
51 "consider using `drop` function",
53 Applicability::MaybeIncorrect,
62 DeferredClosure(DefId, ty::FnSig<'tcx>),
63 /// E.g., enum variant constructors.
64 Overloaded(MethodCallee<'tcx>),
67 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
70 call_expr: &'tcx hir::Expr<'tcx>,
71 callee_expr: &'tcx hir::Expr<'tcx>,
72 arg_exprs: &'tcx [hir::Expr<'tcx>],
73 expected: Expectation<'tcx>,
75 let original_callee_ty = match &callee_expr.kind {
76 hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
77 .check_expr_with_expectation_and_args(
79 Expectation::NoExpectation,
82 _ => self.check_expr(callee_expr),
85 let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty);
87 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
88 let mut result = None;
89 while result.is_none() && autoderef.next().is_some() {
90 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
92 self.register_predicates(autoderef.into_obligations());
94 let output = match result {
96 // this will report an error since original_callee_ty is not a fn
97 self.confirm_builtin_call(
106 Some(CallStep::Builtin(callee_ty)) => {
107 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
110 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
111 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
114 Some(CallStep::Overloaded(method_callee)) => {
115 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
119 // we must check that return type of called functions is WF:
120 self.register_wf_obligation(output.into(), call_expr.span, traits::MiscObligation);
125 fn try_overloaded_call_step(
127 call_expr: &'tcx hir::Expr<'tcx>,
128 callee_expr: &'tcx hir::Expr<'tcx>,
129 arg_exprs: &'tcx [hir::Expr<'tcx>],
130 autoderef: &Autoderef<'a, 'tcx>,
131 ) -> Option<CallStep<'tcx>> {
133 self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
135 "try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
136 call_expr, adjusted_ty
139 // If the callee is a bare function or a closure, then we're all set.
140 match *adjusted_ty.kind() {
141 ty::FnDef(..) | ty::FnPtr(_) => {
142 let adjustments = self.adjust_steps(autoderef);
143 self.apply_adjustments(callee_expr, adjustments);
144 return Some(CallStep::Builtin(adjusted_ty));
147 ty::Closure(def_id, substs) => {
148 assert_eq!(def_id.krate, LOCAL_CRATE);
150 // Check whether this is a call to a closure where we
151 // haven't yet decided on whether the closure is fn vs
152 // fnmut vs fnonce. If so, we have to defer further processing.
153 if self.closure_kind(substs).is_none() {
154 let closure_sig = substs.as_closure().sig();
155 let closure_sig = self
156 .replace_bound_vars_with_fresh_vars(
162 let adjustments = self.adjust_steps(autoderef);
163 self.record_deferred_call_resolution(
165 DeferredCallResolution {
171 closure_substs: substs,
174 return Some(CallStep::DeferredClosure(def_id, closure_sig));
178 // Hack: we know that there are traits implementing Fn for &F
179 // where F:Fn and so forth. In the particular case of types
180 // like `x: &mut FnMut()`, if there is a call `x()`, we would
181 // normally translate to `FnMut::call_mut(&mut x, ())`, but
182 // that winds up requiring `mut x: &mut FnMut()`. A little
183 // over the top. The simplest fix by far is to just ignore
184 // this case and deref again, so we wind up with
185 // `FnMut::call_mut(&mut *x, ())`.
186 ty::Ref(..) if autoderef.step_count() == 0 => {
193 // Now, we look for the implementation of a Fn trait on the object's type.
194 // We first do it with the explicit instruction to look for an impl of
195 // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
196 // to the number of call parameters.
197 // If that fails (or_else branch), we try again without specifying the
198 // shape of the tuple (hence the None). This allows to detect an Fn trait
199 // is implemented, and use this information for diagnostic.
200 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
201 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
202 .map(|(autoref, method)| {
203 let mut adjustments = self.adjust_steps(autoderef);
204 adjustments.extend(autoref);
205 self.apply_adjustments(callee_expr, adjustments);
206 CallStep::Overloaded(method)
210 fn try_overloaded_call_traits(
212 call_expr: &hir::Expr<'_>,
213 adjusted_ty: Ty<'tcx>,
214 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
215 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
216 // Try the options that are least restrictive on the caller first.
217 for (opt_trait_def_id, method_name, borrow) in [
218 (self.tcx.lang_items().fn_trait(), Ident::with_dummy_span(sym::call), true),
219 (self.tcx.lang_items().fn_mut_trait(), Ident::with_dummy_span(sym::call_mut), true),
220 (self.tcx.lang_items().fn_once_trait(), Ident::with_dummy_span(sym::call_once), false),
222 let Some(trait_def_id) = opt_trait_def_id else { continue };
224 let opt_input_types = opt_arg_exprs.map(|arg_exprs| {
225 [self.tcx.mk_tup(arg_exprs.iter().map(|e| {
226 self.next_ty_var(TypeVariableOrigin {
227 kind: TypeVariableOriginKind::TypeInference,
232 let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
234 if let Some(ok) = self.lookup_method_in_trait(
241 let method = self.register_infer_ok_obligations(ok);
242 let mut autoref = None;
244 // Check for &self vs &mut self in the method signature. Since this is either
245 // the Fn or FnMut trait, it should be one of those.
246 let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind() else {
247 // The `fn`/`fn_mut` lang item is ill-formed, which should have
248 // caused an error elsewhere.
251 .delay_span_bug(call_expr.span, "input to call/call_mut is not a ref?");
255 let mutbl = match mutbl {
256 hir::Mutability::Not => AutoBorrowMutability::Not,
257 hir::Mutability::Mut => AutoBorrowMutability::Mut {
258 // For initial two-phase borrow
259 // deployment, conservatively omit
260 // overloaded function call ops.
261 allow_two_phase_borrow: AllowTwoPhase::No,
264 autoref = Some(Adjustment {
265 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
266 target: method.sig.inputs()[0],
269 return Some((autoref, method));
276 /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
277 /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
278 fn identify_bad_closure_def_and_call(
280 err: &mut Diagnostic,
282 callee_node: &hir::ExprKind<'_>,
285 let hir_id = self.tcx.hir().get_parent_node(hir_id);
286 let parent_node = self.tcx.hir().get(hir_id);
288 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, _, _, sp, ..), .. }),
289 hir::ExprKind::Block(..),
290 ) = (parent_node, callee_node)
292 let start = sp.shrink_to_lo();
293 let end = callee_span.shrink_to_hi();
294 err.multipart_suggestion(
295 "if you meant to create this closure and immediately call it, surround the \
296 closure with parentheses",
297 vec![(start, "(".to_string()), (end, ")".to_string())],
298 Applicability::MaybeIncorrect,
303 /// Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the
304 /// likely intention is to create an array containing tuples.
305 fn maybe_suggest_bad_array_definition(
307 err: &mut Diagnostic,
308 call_expr: &'tcx hir::Expr<'tcx>,
309 callee_expr: &'tcx hir::Expr<'tcx>,
311 let hir_id = self.tcx.hir().get_parent_node(call_expr.hir_id);
312 let parent_node = self.tcx.hir().get(hir_id);
314 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
315 hir::ExprKind::Tup(exp),
316 hir::ExprKind::Call(_, args),
317 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
318 && args.len() == exp.len()
320 let start = callee_expr.span.shrink_to_hi();
323 "consider separating array elements with a comma",
325 Applicability::MaybeIncorrect,
332 fn confirm_builtin_call(
334 call_expr: &'tcx hir::Expr<'tcx>,
335 callee_expr: &'tcx hir::Expr<'tcx>,
337 arg_exprs: &'tcx [hir::Expr<'tcx>],
338 expected: Expectation<'tcx>,
340 let (fn_sig, def_id) = match *callee_ty.kind() {
341 ty::FnDef(def_id, subst) => {
342 let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, subst);
344 // Unit testing: function items annotated with
345 // `#[rustc_evaluate_where_clauses]` trigger special output
346 // to let us test the trait evaluation system.
347 if self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses) {
348 let predicates = self.tcx.predicates_of(def_id);
349 let predicates = predicates.instantiate(self.tcx, subst);
350 for (predicate, predicate_span) in
351 predicates.predicates.iter().zip(&predicates.spans)
353 let obligation = Obligation::new(
354 ObligationCause::dummy_with_span(callee_expr.span),
358 let result = self.infcx.evaluate_obligation(&obligation);
363 &format!("evaluate({:?}) = {:?}", predicate, result),
365 .span_label(*predicate_span, "predicate")
369 (fn_sig, Some(def_id))
371 ty::FnPtr(sig) => (sig, None),
373 let mut unit_variant = None;
374 let mut removal_span = call_expr.span;
375 if let ty::Adt(adt_def, ..) = t
377 && let hir::ExprKind::Call(expr, _) = call_expr.kind
380 expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
382 self.tcx.sess.source_map().span_to_snippet(expr.span).ok();
385 let callee_ty = self.resolve_vars_if_possible(callee_ty);
386 let mut err = type_error_struct!(
391 "expected function, found {}",
393 Some(ref path) => format!("enum variant `{path}`"),
394 None => format!("`{callee_ty}`"),
398 self.identify_bad_closure_def_and_call(
405 if let Some(ref path) = unit_variant {
406 err.span_suggestion_verbose(
409 "`{path}` is a unit variant, you need to write it without the parentheses",
412 Applicability::MachineApplicable,
416 let mut inner_callee_path = None;
417 let def = match callee_expr.kind {
418 hir::ExprKind::Path(ref qpath) => {
419 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
421 hir::ExprKind::Call(ref inner_callee, _) => {
422 // If the call spans more than one line and the callee kind is
423 // itself another `ExprCall`, that's a clue that we might just be
424 // missing a semicolon (Issue #51055)
425 let call_is_multiline =
426 self.tcx.sess.source_map().is_multiline(call_expr.span);
427 if call_is_multiline {
429 callee_expr.span.shrink_to_hi(),
430 "consider using a semicolon here",
432 Applicability::MaybeIncorrect,
435 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
436 inner_callee_path = Some(inner_qpath);
437 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
445 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
446 err.span_label(call_expr.span, "call expression requires function");
449 if let Some(span) = self.tcx.hir().res_span(def) {
450 let callee_ty = callee_ty.to_string();
451 let label = match (unit_variant, inner_callee_path) {
452 (Some(path), _) => Some(format!("`{path}` defined here")),
453 (_, Some(hir::QPath::Resolved(_, path))) => self
457 .span_to_snippet(path.span)
459 .map(|p| format!("`{p}` defined here returns `{callee_ty}`")),
462 // Emit a different diagnostic for local variables, as they are not
463 // type definitions themselves, but rather variables *of* that type.
464 Res::Local(hir_id) => Some(format!(
465 "`{}` has type `{}`",
466 self.tcx.hir().name(hir_id),
469 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
472 self.tcx.def_path_str(def_id),
475 _ => Some(format!("`{callee_ty}` defined here")),
479 if let Some(label) = label {
480 err.span_label(span, label);
485 // This is the "default" function signature, used in case of error.
486 // In that case, we check each argument against "error" in order to
487 // set up all the node type bindings.
489 ty::Binder::dummy(self.tcx.mk_fn_sig(
490 self.err_args(arg_exprs.len()).into_iter(),
493 hir::Unsafety::Normal,
501 // Replace any late-bound regions that appear in the function
502 // signature with region variables. We also have to
503 // renormalize the associated types at this point, since they
504 // previously appeared within a `Binder<>` and hence would not
505 // have been normalized before.
507 self.replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, fn_sig).0;
508 let fn_sig = self.normalize_associated_types_in(call_expr.span, fn_sig);
510 // Call the generic checker.
511 let expected_arg_tys = self.expected_inputs_for_expected_output(
517 self.check_argument_types(
524 TupleArgumentsFlag::DontTupleArguments,
531 fn confirm_deferred_closure_call(
533 call_expr: &'tcx hir::Expr<'tcx>,
534 arg_exprs: &'tcx [hir::Expr<'tcx>],
535 expected: Expectation<'tcx>,
536 closure_def_id: DefId,
537 fn_sig: ty::FnSig<'tcx>,
539 // `fn_sig` is the *signature* of the closure being called. We
540 // don't know the full details yet (`Fn` vs `FnMut` etc), but we
541 // do know the types expected for each argument and the return
544 let expected_arg_tys = self.expected_inputs_for_expected_output(
551 self.check_argument_types(
558 TupleArgumentsFlag::TupleArguments,
559 Some(closure_def_id),
565 fn confirm_overloaded_call(
567 call_expr: &'tcx hir::Expr<'tcx>,
568 arg_exprs: &'tcx [hir::Expr<'tcx>],
569 expected: Expectation<'tcx>,
570 method_callee: MethodCallee<'tcx>,
572 let output_type = self.check_method_argument_types(
577 TupleArgumentsFlag::TupleArguments,
581 self.write_method_call(call_expr.hir_id, method_callee);
587 pub struct DeferredCallResolution<'tcx> {
588 call_expr: &'tcx hir::Expr<'tcx>,
589 callee_expr: &'tcx hir::Expr<'tcx>,
590 adjusted_ty: Ty<'tcx>,
591 adjustments: Vec<Adjustment<'tcx>>,
592 fn_sig: ty::FnSig<'tcx>,
593 closure_substs: SubstsRef<'tcx>,
596 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
597 pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
598 debug!("DeferredCallResolution::resolve() {:?}", self);
600 // we should not be invoked until the closure kind has been
601 // determined by upvar inference
602 assert!(fcx.closure_kind(self.closure_substs).is_some());
604 // We may now know enough to figure out fn vs fnmut etc.
605 match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
606 Some((autoref, method_callee)) => {
607 // One problem is that when we get here, we are going
608 // to have a newly instantiated function signature
609 // from the call trait. This has to be reconciled with
610 // the older function signature we had before. In
611 // principle we *should* be able to fn_sigs(), but we
612 // can't because of the annoying need for a TypeTrace.
613 // (This always bites me, should find a way to
615 let method_sig = method_callee.sig;
617 debug!("attempt_resolution: method_callee={:?}", method_callee);
619 for (method_arg_ty, self_arg_ty) in
620 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
622 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
625 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
627 let mut adjustments = self.adjustments;
628 adjustments.extend(autoref);
629 fcx.apply_adjustments(self.callee_expr, adjustments);
631 fcx.write_method_call(self.call_expr.hir_id, method_callee);
634 // This can happen if `#![no_core]` is used and the `fn/fn_mut/fn_once`
635 // lang items are not defined (issue #86238).
636 let mut err = fcx.inh.tcx.sess.struct_span_err(
638 "failed to find an overloaded call trait for closure call",
641 "make sure the `fn`/`fn_mut`/`fn_once` lang items are defined \
642 and have associated `call`/`call_mut`/`call_once` functions",