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::{infer, traits};
11 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
12 use rustc_target::spec::abi;
13 use syntax::ast::Ident;
18 /// Checks that it is legal to call methods of the trait corresponding
19 /// to `trait_id` (this only cares about the trait, not the specific
20 /// method that is called).
21 pub fn check_legal_trait_for_method_call(tcx: TyCtxt<'_>, span: Span, trait_id: DefId) {
22 if tcx.lang_items().drop_trait() == Some(trait_id) {
23 struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method")
24 .span_label(span, "explicit destructor calls not allowed")
31 DeferredClosure(ty::FnSig<'tcx>),
32 /// E.g., enum variant constructors.
33 Overloaded(MethodCallee<'tcx>),
36 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
39 call_expr: &'tcx hir::Expr,
40 callee_expr: &'tcx hir::Expr,
41 arg_exprs: &'tcx [hir::Expr],
42 expected: Expectation<'tcx>,
44 let original_callee_ty = self.check_expr(callee_expr);
45 let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty);
47 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
48 let mut result = None;
49 while result.is_none() && autoderef.next().is_some() {
50 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
52 autoderef.finalize(self);
54 let output = match result {
56 // this will report an error since original_callee_ty is not a fn
57 self.confirm_builtin_call(call_expr, original_callee_ty, arg_exprs, expected)
60 Some(CallStep::Builtin(callee_ty)) => {
61 self.confirm_builtin_call(call_expr, callee_ty, arg_exprs, expected)
64 Some(CallStep::DeferredClosure(fn_sig)) => {
65 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, fn_sig)
68 Some(CallStep::Overloaded(method_callee)) => {
69 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
73 // we must check that return type of called functions is WF:
74 self.register_wf_obligation(output, call_expr.span, traits::MiscObligation);
79 fn try_overloaded_call_step(
81 call_expr: &'tcx hir::Expr,
82 callee_expr: &'tcx hir::Expr,
83 arg_exprs: &'tcx [hir::Expr],
84 autoderef: &Autoderef<'a, 'tcx>,
85 ) -> Option<CallStep<'tcx>> {
86 let adjusted_ty = autoderef.unambiguous_final_ty(self);
88 "try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
89 call_expr, adjusted_ty
92 // If the callee is a bare function or a closure, then we're all set.
93 match adjusted_ty.kind {
94 ty::FnDef(..) | ty::FnPtr(_) => {
95 let adjustments = autoderef.adjust_steps(self, Needs::None);
96 self.apply_adjustments(callee_expr, adjustments);
97 return Some(CallStep::Builtin(adjusted_ty));
100 ty::Closure(def_id, substs) => {
101 assert_eq!(def_id.krate, LOCAL_CRATE);
103 // Check whether this is a call to a closure where we
104 // haven't yet decided on whether the closure is fn vs
105 // fnmut vs fnonce. If so, we have to defer further processing.
106 if self.closure_kind(def_id, substs).is_none() {
107 let closure_ty = self.closure_sig(def_id, substs);
109 .replace_bound_vars_with_fresh_vars(
115 let adjustments = autoderef.adjust_steps(self, Needs::None);
116 self.record_deferred_call_resolution(
118 DeferredCallResolution {
124 closure_def_id: def_id,
125 closure_substs: substs,
128 return Some(CallStep::DeferredClosure(fn_sig));
132 // Hack: we know that there are traits implementing Fn for &F
133 // where F:Fn and so forth. In the particular case of types
134 // like `x: &mut FnMut()`, if there is a call `x()`, we would
135 // normally translate to `FnMut::call_mut(&mut x, ())`, but
136 // that winds up requiring `mut x: &mut FnMut()`. A little
137 // over the top. The simplest fix by far is to just ignore
138 // this case and deref again, so we wind up with
139 // `FnMut::call_mut(&mut *x, ())`.
140 ty::Ref(..) if autoderef.step_count() == 0 => {
147 // Now, we look for the implementation of a Fn trait on the object's type.
148 // We first do it with the explicit instruction to look for an impl of
149 // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
150 // to the number of call parameters.
151 // If that fails (or_else branch), we try again without specifying the
152 // shape of the tuple (hence the None). This allows to detect an Fn trait
153 // is implemented, and use this information for diagnostic.
154 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
155 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
156 .map(|(autoref, method)| {
157 let mut adjustments = autoderef.adjust_steps(self, Needs::None);
158 adjustments.extend(autoref);
159 self.apply_adjustments(callee_expr, adjustments);
160 CallStep::Overloaded(method)
164 fn try_overloaded_call_traits(
166 call_expr: &hir::Expr,
167 adjusted_ty: Ty<'tcx>,
168 opt_arg_exprs: Option<&'tcx [hir::Expr]>,
169 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
170 // Try the options that are least restrictive on the caller first.
171 for &(opt_trait_def_id, method_name, borrow) in &[
173 self.tcx.lang_items().fn_trait(),
174 Ident::from_str("call"),
178 self.tcx.lang_items().fn_mut_trait(),
179 Ident::from_str("call_mut"),
183 self.tcx.lang_items().fn_once_trait(),
184 Ident::from_str("call_once"),
188 let trait_def_id = match opt_trait_def_id {
189 Some(def_id) => def_id,
193 let opt_input_types = opt_arg_exprs.map(|arg_exprs| [self.tcx.mk_tup(
197 self.next_ty_var(TypeVariableOrigin {
198 kind: TypeVariableOriginKind::TypeInference,
203 let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
205 if let Some(ok) = self.lookup_method_in_trait(
212 let method = self.register_infer_ok_obligations(ok);
213 let mut autoref = None;
215 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
216 let mutbl = match mutbl {
217 hir::MutImmutable => AutoBorrowMutability::Immutable,
218 hir::MutMutable => AutoBorrowMutability::Mutable {
219 // For initial two-phase borrow
220 // deployment, conservatively omit
221 // overloaded function call ops.
222 allow_two_phase_borrow: AllowTwoPhase::No,
225 autoref = Some(Adjustment {
226 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
227 target: method.sig.inputs()[0],
231 return Some((autoref, method));
238 /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
239 /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
240 fn identify_bad_closure_def_and_call(
242 err: &mut DiagnosticBuilder<'a>,
244 callee_node: &hir::ExprKind,
247 let hir_id = self.tcx.hir().get_parent_node(hir_id);
248 let parent_node = self.tcx.hir().get(hir_id);
250 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, _, _, sp, ..), .. }),
251 hir::ExprKind::Block(..),
252 ) = (parent_node, callee_node) {
253 let start = sp.shrink_to_lo();
254 let end = self.tcx.sess.source_map().next_point(callee_span);
255 err.multipart_suggestion(
256 "if you meant to create this closure and immediately call it, surround the \
257 closure with parenthesis",
258 vec![(start, "(".to_string()), (end, ")".to_string())],
259 Applicability::MaybeIncorrect,
264 fn confirm_builtin_call(
266 call_expr: &'tcx hir::Expr,
268 arg_exprs: &'tcx [hir::Expr],
269 expected: Expectation<'tcx>,
271 let (fn_sig, def_span) = match callee_ty.kind {
272 ty::FnDef(def_id, _) => (
273 callee_ty.fn_sig(self.tcx),
274 self.tcx.hir().span_if_local(def_id),
276 ty::FnPtr(sig) => (sig, None),
278 let mut unit_variant = None;
279 if let &ty::Adt(adt_def, ..) = t {
280 if adt_def.is_enum() {
281 if let hir::ExprKind::Call(ref expr, _) = call_expr.kind {
282 unit_variant = Some(self.tcx.hir().hir_to_pretty_string(expr.hir_id))
287 if let hir::ExprKind::Call(ref callee, _) = call_expr.kind {
288 let mut err = type_error_struct!(
293 "expected function, found {}",
295 Some(ref path) => format!("enum variant `{}`", path),
296 None => format!("`{}`", callee_ty),
300 self.identify_bad_closure_def_and_call(
307 if let Some(ref path) = unit_variant {
311 "`{}` is a unit variant, you need to write it \
312 without the parenthesis",
316 Applicability::MachineApplicable,
320 let mut inner_callee_path = None;
321 let def = match callee.kind {
322 hir::ExprKind::Path(ref qpath) => {
323 self.tables.borrow().qpath_res(qpath, callee.hir_id)
325 hir::ExprKind::Call(ref inner_callee, _) => {
326 // If the call spans more than one line and the callee kind is
327 // itself another `ExprCall`, that's a clue that we might just be
328 // missing a semicolon (Issue #51055)
329 let call_is_multiline =
330 self.tcx.sess.source_map().is_multiline(call_expr.span);
331 if call_is_multiline {
332 let span = self.tcx.sess.source_map().next_point(callee.span);
335 "try adding a semicolon",
337 Applicability::MaybeIncorrect,
340 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
341 inner_callee_path = Some(inner_qpath);
344 .qpath_res(inner_qpath, inner_callee.hir_id)
352 err.span_label(call_expr.span, "call expression requires function");
354 if let Some(span) = self.tcx.hir().res_span(def) {
355 let label = match (unit_variant, inner_callee_path) {
356 (Some(path), _) => format!("`{}` defined here", path),
357 (_, Some(hir::QPath::Resolved(_, path))) => format!(
358 "`{}` defined here returns `{}`",
360 callee_ty.to_string()
362 _ => format!("`{}` defined here", callee_ty.to_string()),
364 err.span_label(span, label);
369 "call_expr.kind should be an ExprKind::Call, got {:?}",
374 // This is the "default" function signature, used in case of error.
375 // In that case, we check each argument against "error" in order to
376 // set up all the node type bindings.
378 ty::Binder::bind(self.tcx.mk_fn_sig(
379 self.err_args(arg_exprs.len()).into_iter(),
382 hir::Unsafety::Normal,
390 // Replace any late-bound regions that appear in the function
391 // signature with region variables. We also have to
392 // renormalize the associated types at this point, since they
393 // previously appeared within a `Binder<>` and hence would not
394 // have been normalized before.
396 .replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig)
398 let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
400 // Call the generic checker.
401 let expected_arg_tys = self.expected_inputs_for_expected_output(
407 self.check_argument_types(
411 &expected_arg_tys[..],
414 TupleArgumentsFlag::DontTupleArguments,
421 fn confirm_deferred_closure_call(
423 call_expr: &'tcx hir::Expr,
424 arg_exprs: &'tcx [hir::Expr],
425 expected: Expectation<'tcx>,
426 fn_sig: ty::FnSig<'tcx>,
428 // `fn_sig` is the *signature* of the cosure being called. We
429 // don't know the full details yet (`Fn` vs `FnMut` etc), but we
430 // do know the types expected for each argument and the return
433 let expected_arg_tys = self.expected_inputs_for_expected_output(
436 fn_sig.output().clone(),
440 self.check_argument_types(
447 TupleArgumentsFlag::TupleArguments,
454 fn confirm_overloaded_call(
456 call_expr: &'tcx hir::Expr,
457 arg_exprs: &'tcx [hir::Expr],
458 expected: Expectation<'tcx>,
459 method_callee: MethodCallee<'tcx>,
461 let output_type = self.check_method_argument_types(
466 TupleArgumentsFlag::TupleArguments,
470 self.write_method_call(call_expr.hir_id, method_callee);
476 pub struct DeferredCallResolution<'tcx> {
477 call_expr: &'tcx hir::Expr,
478 callee_expr: &'tcx hir::Expr,
479 adjusted_ty: Ty<'tcx>,
480 adjustments: Vec<Adjustment<'tcx>>,
481 fn_sig: ty::FnSig<'tcx>,
482 closure_def_id: DefId,
483 closure_substs: ty::ClosureSubsts<'tcx>,
486 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
487 pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
488 debug!("DeferredCallResolution::resolve() {:?}", self);
490 // we should not be invoked until the closure kind has been
491 // determined by upvar inference
493 .closure_kind(self.closure_def_id, self.closure_substs)
496 // We may now know enough to figure out fn vs fnmut etc.
497 match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
498 Some((autoref, method_callee)) => {
499 // One problem is that when we get here, we are going
500 // to have a newly instantiated function signature
501 // from the call trait. This has to be reconciled with
502 // the older function signature we had before. In
503 // principle we *should* be able to fn_sigs(), but we
504 // can't because of the annoying need for a TypeTrace.
505 // (This always bites me, should find a way to
507 let method_sig = method_callee.sig;
509 debug!("attempt_resolution: method_callee={:?}", method_callee);
511 for (method_arg_ty, self_arg_ty) in
512 method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
514 fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
520 self.fn_sig.output(),
523 let mut adjustments = self.adjustments;
524 adjustments.extend(autoref);
525 fcx.apply_adjustments(self.callee_expr, adjustments);
527 fcx.write_method_call(self.call_expr.hir_id, method_callee);
532 "failed to find an overloaded call trait for closure call"