1 use super::autoderef::Autoderef;
2 use super::method::MethodCallee;
3 use super::{Expectation, FnCtxt, Needs, TupleArgumentsFlag};
4 use crate::type_error_struct;
6 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
7 use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
8 use rustc::ty::subst::SubstsRef;
9 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
10 use rustc::{infer, traits};
11 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
13 use rustc_hir::def::Res;
14 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc_target::spec::abi;
17 use syntax::ast::Ident;
19 /// Checks that it is legal to call methods of the trait corresponding
20 /// to `trait_id` (this only cares about the trait, not the specific
21 /// method that is called).
22 pub fn check_legal_trait_for_method_call(tcx: TyCtxt<'_>, span: Span, trait_id: DefId) {
23 if tcx.lang_items().drop_trait() == Some(trait_id) {
24 struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method")
25 .span_label(span, "explicit destructor calls not allowed")
32 DeferredClosure(ty::FnSig<'tcx>),
33 /// E.g., enum variant constructors.
34 Overloaded(MethodCallee<'tcx>),
37 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40 call_expr: &'tcx hir::Expr<'tcx>,
41 callee_expr: &'tcx hir::Expr<'tcx>,
42 arg_exprs: &'tcx [hir::Expr<'tcx>],
43 expected: Expectation<'tcx>,
45 let original_callee_ty = self.check_expr(callee_expr);
46 let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty);
48 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
49 let mut result = None;
50 while result.is_none() && autoderef.next().is_some() {
51 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
53 autoderef.finalize(self);
55 let output = match result {
57 // this will report an error since original_callee_ty is not a fn
58 self.confirm_builtin_call(call_expr, original_callee_ty, arg_exprs, expected)
61 Some(CallStep::Builtin(callee_ty)) => {
62 self.confirm_builtin_call(call_expr, callee_ty, arg_exprs, expected)
65 Some(CallStep::DeferredClosure(fn_sig)) => {
66 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, fn_sig)
69 Some(CallStep::Overloaded(method_callee)) => {
70 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
74 // we must check that return type of called functions is WF:
75 self.register_wf_obligation(output, call_expr.span, traits::MiscObligation);
80 fn try_overloaded_call_step(
82 call_expr: &'tcx hir::Expr<'tcx>,
83 callee_expr: &'tcx hir::Expr<'tcx>,
84 arg_exprs: &'tcx [hir::Expr<'tcx>],
85 autoderef: &Autoderef<'a, 'tcx>,
86 ) -> Option<CallStep<'tcx>> {
87 let adjusted_ty = autoderef.unambiguous_final_ty(self);
89 "try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
90 call_expr, adjusted_ty
93 // If the callee is a bare function or a closure, then we're all set.
94 match adjusted_ty.kind {
95 ty::FnDef(..) | ty::FnPtr(_) => {
96 let adjustments = autoderef.adjust_steps(self, Needs::None);
97 self.apply_adjustments(callee_expr, adjustments);
98 return Some(CallStep::Builtin(adjusted_ty));
101 ty::Closure(def_id, substs) => {
102 assert_eq!(def_id.krate, LOCAL_CRATE);
104 // Check whether this is a call to a closure where we
105 // haven't yet decided on whether the closure is fn vs
106 // fnmut vs fnonce. If so, we have to defer further processing.
107 if self.closure_kind(def_id, substs).is_none() {
108 let closure_ty = self.closure_sig(def_id, substs);
110 .replace_bound_vars_with_fresh_vars(
116 let adjustments = autoderef.adjust_steps(self, Needs::None);
117 self.record_deferred_call_resolution(
119 DeferredCallResolution {
125 closure_def_id: def_id,
126 closure_substs: substs,
129 return Some(CallStep::DeferredClosure(fn_sig));
133 // Hack: we know that there are traits implementing Fn for &F
134 // where F:Fn and so forth. In the particular case of types
135 // like `x: &mut FnMut()`, if there is a call `x()`, we would
136 // normally translate to `FnMut::call_mut(&mut x, ())`, but
137 // that winds up requiring `mut x: &mut FnMut()`. A little
138 // over the top. The simplest fix by far is to just ignore
139 // this case and deref again, so we wind up with
140 // `FnMut::call_mut(&mut *x, ())`.
141 ty::Ref(..) if autoderef.step_count() == 0 => {
148 // Now, we look for the implementation of a Fn trait on the object's type.
149 // We first do it with the explicit instruction to look for an impl of
150 // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
151 // to the number of call parameters.
152 // If that fails (or_else branch), we try again without specifying the
153 // shape of the tuple (hence the None). This allows to detect an Fn trait
154 // is implemented, and use this information for diagnostic.
155 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
156 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
157 .map(|(autoref, method)| {
158 let mut adjustments = autoderef.adjust_steps(self, Needs::None);
159 adjustments.extend(autoref);
160 self.apply_adjustments(callee_expr, adjustments);
161 CallStep::Overloaded(method)
165 fn try_overloaded_call_traits(
167 call_expr: &hir::Expr<'_>,
168 adjusted_ty: Ty<'tcx>,
169 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
170 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
171 // Try the options that are least restrictive on the caller first.
172 for &(opt_trait_def_id, method_name, borrow) in &[
173 (self.tcx.lang_items().fn_trait(), Ident::from_str("call"), true),
174 (self.tcx.lang_items().fn_mut_trait(), Ident::from_str("call_mut"), true),
175 (self.tcx.lang_items().fn_once_trait(), Ident::from_str("call_once"), false),
177 let trait_def_id = match opt_trait_def_id {
178 Some(def_id) => def_id,
182 let opt_input_types = opt_arg_exprs.map(|arg_exprs| {
183 [self.tcx.mk_tup(arg_exprs.iter().map(|e| {
184 self.next_ty_var(TypeVariableOrigin {
185 kind: TypeVariableOriginKind::TypeInference,
190 let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
192 if let Some(ok) = self.lookup_method_in_trait(
199 let method = self.register_infer_ok_obligations(ok);
200 let mut autoref = None;
202 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
203 let mutbl = match mutbl {
204 hir::Mutability::Not => AutoBorrowMutability::Not,
205 hir::Mutability::Mut => AutoBorrowMutability::Mut {
206 // For initial two-phase borrow
207 // deployment, conservatively omit
208 // overloaded function call ops.
209 allow_two_phase_borrow: AllowTwoPhase::No,
212 autoref = Some(Adjustment {
213 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
214 target: method.sig.inputs()[0],
218 return Some((autoref, method));
225 /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
226 /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
227 fn identify_bad_closure_def_and_call(
229 err: &mut DiagnosticBuilder<'a>,
231 callee_node: &hir::ExprKind<'_>,
234 let hir_id = self.tcx.hir().get_parent_node(hir_id);
235 let parent_node = self.tcx.hir().get(hir_id);
237 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, _, _, sp, ..), .. }),
238 hir::ExprKind::Block(..),
239 ) = (parent_node, callee_node)
241 let start = sp.shrink_to_lo();
242 let end = callee_span.shrink_to_hi();
243 err.multipart_suggestion(
244 "if you meant to create this closure and immediately call it, surround the \
245 closure with parenthesis",
246 vec![(start, "(".to_string()), (end, ")".to_string())],
247 Applicability::MaybeIncorrect,
252 fn confirm_builtin_call(
254 call_expr: &'tcx hir::Expr<'tcx>,
256 arg_exprs: &'tcx [hir::Expr<'tcx>],
257 expected: Expectation<'tcx>,
259 let (fn_sig, def_span) = match callee_ty.kind {
260 ty::FnDef(def_id, _) => {
261 (callee_ty.fn_sig(self.tcx), self.tcx.hir().span_if_local(def_id))
263 ty::FnPtr(sig) => (sig, None),
265 let mut unit_variant = None;
266 if let &ty::Adt(adt_def, ..) = t {
267 if adt_def.is_enum() {
268 if let hir::ExprKind::Call(ref expr, _) = call_expr.kind {
269 unit_variant = Some(self.tcx.hir().hir_to_pretty_string(expr.hir_id))
274 if let hir::ExprKind::Call(ref callee, _) = call_expr.kind {
275 let mut err = type_error_struct!(
280 "expected function, found {}",
282 Some(ref path) => format!("enum variant `{}`", path),
283 None => format!("`{}`", callee_ty),
287 self.identify_bad_closure_def_and_call(
294 if let Some(ref path) = unit_variant {
298 "`{}` is a unit variant, you need to write it \
299 without the parenthesis",
303 Applicability::MachineApplicable,
307 let mut inner_callee_path = None;
308 let def = match callee.kind {
309 hir::ExprKind::Path(ref qpath) => {
310 self.tables.borrow().qpath_res(qpath, callee.hir_id)
312 hir::ExprKind::Call(ref inner_callee, _) => {
313 // If the call spans more than one line and the callee kind is
314 // itself another `ExprCall`, that's a clue that we might just be
315 // missing a semicolon (Issue #51055)
316 let call_is_multiline =
317 self.tcx.sess.source_map().is_multiline(call_expr.span);
318 if call_is_multiline {
320 callee.span.shrink_to_hi(),
321 "try adding a semicolon",
323 Applicability::MaybeIncorrect,
326 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
327 inner_callee_path = Some(inner_qpath);
328 self.tables.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
336 err.span_label(call_expr.span, "call expression requires function");
338 if let Some(span) = self.tcx.hir().res_span(def) {
339 let label = match (unit_variant, inner_callee_path) {
340 (Some(path), _) => format!("`{}` defined here", path),
341 (_, Some(hir::QPath::Resolved(_, path))) => format!(
342 "`{}` defined here returns `{}`",
344 callee_ty.to_string()
346 _ => format!("`{}` defined here", callee_ty.to_string()),
348 err.span_label(span, label);
352 bug!("call_expr.kind should be an ExprKind::Call, got {:?}", call_expr.kind);
355 // This is the "default" function signature, used in case of error.
356 // In that case, we check each argument against "error" in order to
357 // set up all the node type bindings.
359 ty::Binder::bind(self.tcx.mk_fn_sig(
360 self.err_args(arg_exprs.len()).into_iter(),
363 hir::Unsafety::Normal,
371 // Replace any late-bound regions that appear in the function
372 // signature with region variables. We also have to
373 // renormalize the associated types at this point, since they
374 // previously appeared within a `Binder<>` and hence would not
375 // have been normalized before.
377 self.replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig).0;
378 let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
380 // Call the generic checker.
381 let expected_arg_tys = self.expected_inputs_for_expected_output(
387 self.check_argument_types(
391 &expected_arg_tys[..],
394 TupleArgumentsFlag::DontTupleArguments,
401 fn confirm_deferred_closure_call(
403 call_expr: &'tcx hir::Expr<'tcx>,
404 arg_exprs: &'tcx [hir::Expr<'tcx>],
405 expected: Expectation<'tcx>,
406 fn_sig: ty::FnSig<'tcx>,
408 // `fn_sig` is the *signature* of the cosure being called. We
409 // don't know the full details yet (`Fn` vs `FnMut` etc), but we
410 // do know the types expected for each argument and the return
413 let expected_arg_tys = self.expected_inputs_for_expected_output(
416 fn_sig.output().clone(),
420 self.check_argument_types(
427 TupleArgumentsFlag::TupleArguments,
434 fn confirm_overloaded_call(
436 call_expr: &'tcx hir::Expr<'tcx>,
437 arg_exprs: &'tcx [hir::Expr<'tcx>],
438 expected: Expectation<'tcx>,
439 method_callee: MethodCallee<'tcx>,
441 let output_type = self.check_method_argument_types(
446 TupleArgumentsFlag::TupleArguments,
450 self.write_method_call(call_expr.hir_id, method_callee);
456 pub struct DeferredCallResolution<'tcx> {
457 call_expr: &'tcx hir::Expr<'tcx>,
458 callee_expr: &'tcx hir::Expr<'tcx>,
459 adjusted_ty: Ty<'tcx>,
460 adjustments: Vec<Adjustment<'tcx>>,
461 fn_sig: ty::FnSig<'tcx>,
462 closure_def_id: DefId,
463 closure_substs: SubstsRef<'tcx>,
466 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
467 pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
468 debug!("DeferredCallResolution::resolve() {:?}", self);
470 // we should not be invoked until the closure kind has been
471 // determined by upvar inference
472 assert!(fcx.closure_kind(self.closure_def_id, self.closure_substs).is_some());
474 // We may now know enough to figure out fn vs fnmut etc.
475 match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
476 Some((autoref, method_callee)) => {
477 // One problem is that when we get here, we are going
478 // to have a newly instantiated function signature
479 // from the call trait. This has to be reconciled with
480 // the older function signature we had before. In
481 // principle we *should* be able to fn_sigs(), but we
482 // can't because of the annoying need for a TypeTrace.
483 // (This always bites me, should find a way to
485 let method_sig = method_callee.sig;
487 debug!("attempt_resolution: method_callee={:?}", method_callee);
489 for (method_arg_ty, self_arg_ty) in
490 method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
492 fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
495 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
497 let mut adjustments = self.adjustments;
498 adjustments.extend(autoref);
499 fcx.apply_adjustments(self.callee_expr, adjustments);
501 fcx.write_method_call(self.call_expr.hir_id, method_callee);
506 "failed to find an overloaded call trait for closure call"