1 use super::autoderef::Autoderef;
2 use super::method::MethodCallee;
3 use super::{Expectation, FnCtxt, Needs, TupleArgumentsFlag};
5 use errors::{Applicability, DiagnosticBuilder};
7 use hir::def_id::{DefId, LOCAL_CRATE};
8 use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
9 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
10 use rustc::ty::subst::SubstsRef;
11 use rustc::{infer, traits};
12 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
13 use rustc_target::spec::abi;
14 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,
41 callee_expr: &'tcx hir::Expr,
42 arg_exprs: &'tcx [hir::Expr],
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,
83 callee_expr: &'tcx hir::Expr,
84 arg_exprs: &'tcx [hir::Expr],
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]>,
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 &[
174 self.tcx.lang_items().fn_trait(),
175 Ident::from_str("call"),
179 self.tcx.lang_items().fn_mut_trait(),
180 Ident::from_str("call_mut"),
184 self.tcx.lang_items().fn_once_trait(),
185 Ident::from_str("call_once"),
189 let trait_def_id = match opt_trait_def_id {
190 Some(def_id) => def_id,
194 let opt_input_types = opt_arg_exprs.map(|arg_exprs| [self.tcx.mk_tup(
198 self.next_ty_var(TypeVariableOrigin {
199 kind: TypeVariableOriginKind::TypeInference,
204 let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
206 if let Some(ok) = self.lookup_method_in_trait(
213 let method = self.register_infer_ok_obligations(ok);
214 let mut autoref = None;
216 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
217 let mutbl = match mutbl {
218 hir::MutImmutable => AutoBorrowMutability::Immutable,
219 hir::MutMutable => AutoBorrowMutability::Mutable {
220 // For initial two-phase borrow
221 // deployment, conservatively omit
222 // overloaded function call ops.
223 allow_two_phase_borrow: AllowTwoPhase::No,
226 autoref = Some(Adjustment {
227 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
228 target: method.sig.inputs()[0],
232 return Some((autoref, method));
239 /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
240 /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
241 fn identify_bad_closure_def_and_call(
243 err: &mut DiagnosticBuilder<'a>,
245 callee_node: &hir::ExprKind,
248 let hir_id = self.tcx.hir().get_parent_node(hir_id);
249 let parent_node = self.tcx.hir().get(hir_id);
251 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, _, _, sp, ..), .. }),
252 hir::ExprKind::Block(..),
253 ) = (parent_node, callee_node) {
254 let start = sp.shrink_to_lo();
255 let end = self.tcx.sess.source_map().next_point(callee_span);
256 err.multipart_suggestion(
257 "if you meant to create this closure and immediately call it, surround the \
258 closure with parenthesis",
259 vec![(start, "(".to_string()), (end, ")".to_string())],
260 Applicability::MaybeIncorrect,
265 fn confirm_builtin_call(
267 call_expr: &'tcx hir::Expr,
269 arg_exprs: &'tcx [hir::Expr],
270 expected: Expectation<'tcx>,
272 let (fn_sig, def_span) = match callee_ty.kind {
273 ty::FnDef(def_id, _) => (
274 callee_ty.fn_sig(self.tcx),
275 self.tcx.hir().span_if_local(def_id),
277 ty::FnPtr(sig) => (sig, None),
279 let mut unit_variant = None;
280 if let &ty::Adt(adt_def, ..) = t {
281 if adt_def.is_enum() {
282 if let hir::ExprKind::Call(ref expr, _) = call_expr.kind {
283 unit_variant = Some(self.tcx.hir().hir_to_pretty_string(expr.hir_id))
288 if let hir::ExprKind::Call(ref callee, _) = call_expr.kind {
289 let mut err = type_error_struct!(
294 "expected function, found {}",
296 Some(ref path) => format!("enum variant `{}`", path),
297 None => format!("`{}`", callee_ty),
301 self.identify_bad_closure_def_and_call(
308 if let Some(ref path) = unit_variant {
312 "`{}` is a unit variant, you need to write it \
313 without the parenthesis",
317 Applicability::MachineApplicable,
321 let mut inner_callee_path = None;
322 let def = match callee.kind {
323 hir::ExprKind::Path(ref qpath) => {
324 self.tables.borrow().qpath_res(qpath, callee.hir_id)
326 hir::ExprKind::Call(ref inner_callee, _) => {
327 // If the call spans more than one line and the callee kind is
328 // itself another `ExprCall`, that's a clue that we might just be
329 // missing a semicolon (Issue #51055)
330 let call_is_multiline =
331 self.tcx.sess.source_map().is_multiline(call_expr.span);
332 if call_is_multiline {
333 let span = self.tcx.sess.source_map().next_point(callee.span);
336 "try adding a semicolon",
338 Applicability::MaybeIncorrect,
341 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
342 inner_callee_path = Some(inner_qpath);
345 .qpath_res(inner_qpath, inner_callee.hir_id)
353 err.span_label(call_expr.span, "call expression requires function");
355 if let Some(span) = self.tcx.hir().res_span(def) {
356 let label = match (unit_variant, inner_callee_path) {
357 (Some(path), _) => format!("`{}` defined here", path),
358 (_, Some(hir::QPath::Resolved(_, path))) => format!(
359 "`{}` defined here returns `{}`",
361 callee_ty.to_string()
363 _ => format!("`{}` defined here", callee_ty.to_string()),
365 err.span_label(span, label);
370 "call_expr.kind should be an ExprKind::Call, got {:?}",
375 // This is the "default" function signature, used in case of error.
376 // In that case, we check each argument against "error" in order to
377 // set up all the node type bindings.
379 ty::Binder::bind(self.tcx.mk_fn_sig(
380 self.err_args(arg_exprs.len()).into_iter(),
383 hir::Unsafety::Normal,
391 // Replace any late-bound regions that appear in the function
392 // signature with region variables. We also have to
393 // renormalize the associated types at this point, since they
394 // previously appeared within a `Binder<>` and hence would not
395 // have been normalized before.
397 .replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig)
399 let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
401 // Call the generic checker.
402 let expected_arg_tys = self.expected_inputs_for_expected_output(
408 self.check_argument_types(
412 &expected_arg_tys[..],
415 TupleArgumentsFlag::DontTupleArguments,
422 fn confirm_deferred_closure_call(
424 call_expr: &'tcx hir::Expr,
425 arg_exprs: &'tcx [hir::Expr],
426 expected: Expectation<'tcx>,
427 fn_sig: ty::FnSig<'tcx>,
429 // `fn_sig` is the *signature* of the cosure being called. We
430 // don't know the full details yet (`Fn` vs `FnMut` etc), but we
431 // do know the types expected for each argument and the return
434 let expected_arg_tys = self.expected_inputs_for_expected_output(
437 fn_sig.output().clone(),
441 self.check_argument_types(
448 TupleArgumentsFlag::TupleArguments,
455 fn confirm_overloaded_call(
457 call_expr: &'tcx hir::Expr,
458 arg_exprs: &'tcx [hir::Expr],
459 expected: Expectation<'tcx>,
460 method_callee: MethodCallee<'tcx>,
462 let output_type = self.check_method_argument_types(
467 TupleArgumentsFlag::TupleArguments,
471 self.write_method_call(call_expr.hir_id, method_callee);
477 pub struct DeferredCallResolution<'tcx> {
478 call_expr: &'tcx hir::Expr,
479 callee_expr: &'tcx hir::Expr,
480 adjusted_ty: Ty<'tcx>,
481 adjustments: Vec<Adjustment<'tcx>>,
482 fn_sig: ty::FnSig<'tcx>,
483 closure_def_id: DefId,
484 closure_substs: SubstsRef<'tcx>,
487 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
488 pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
489 debug!("DeferredCallResolution::resolve() {:?}", self);
491 // we should not be invoked until the closure kind has been
492 // determined by upvar inference
494 .closure_kind(self.closure_def_id, self.closure_substs)
497 // We may now know enough to figure out fn vs fnmut etc.
498 match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
499 Some((autoref, method_callee)) => {
500 // One problem is that when we get here, we are going
501 // to have a newly instantiated function signature
502 // from the call trait. This has to be reconciled with
503 // the older function signature we had before. In
504 // principle we *should* be able to fn_sigs(), but we
505 // can't because of the annoying need for a TypeTrace.
506 // (This always bites me, should find a way to
508 let method_sig = method_callee.sig;
510 debug!("attempt_resolution: method_callee={:?}", method_callee);
512 for (method_arg_ty, self_arg_ty) in
513 method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
515 fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
521 self.fn_sig.output(),
524 let mut adjustments = self.adjustments;
525 adjustments.extend(autoref);
526 fcx.apply_adjustments(self.callee_expr, adjustments);
528 fcx.write_method_call(self.call_expr.hir_id, method_callee);
533 "failed to find an overloaded call trait for closure call"