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;
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, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
39 call_expr: &'gcx hir::Expr,
40 callee_expr: &'gcx hir::Expr,
41 arg_exprs: &'gcx [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: &'gcx hir::Expr,
82 callee_expr: &'gcx hir::Expr,
83 arg_exprs: &'gcx [hir::Expr],
84 autoderef: &Autoderef<'a, 'gcx, '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.sty {
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<&'gcx [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(
196 .map(|e| self.next_ty_var(
197 TypeVariableOrigin::TypeInference(e.span)
200 let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
202 if let Some(ok) = self.lookup_method_in_trait(
209 let method = self.register_infer_ok_obligations(ok);
210 let mut autoref = None;
212 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].sty {
213 let mutbl = match mutbl {
214 hir::MutImmutable => AutoBorrowMutability::Immutable,
215 hir::MutMutable => AutoBorrowMutability::Mutable {
216 // For initial two-phase borrow
217 // deployment, conservatively omit
218 // overloaded function call ops.
219 allow_two_phase_borrow: AllowTwoPhase::No,
222 autoref = Some(Adjustment {
223 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
224 target: method.sig.inputs()[0],
228 return Some((autoref, method));
235 /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
236 /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
237 fn identify_bad_closure_def_and_call(
239 err: &mut DiagnosticBuilder<'a>,
241 callee_node: &hir::ExprKind,
244 let hir_id = self.tcx.hir().get_parent_node_by_hir_id(hir_id);
245 let parent_node = self.tcx.hir().get_by_hir_id(hir_id);
247 hir::Node::Expr(hir::Expr { node: hir::ExprKind::Closure(_, _, _, sp, ..), .. }),
248 hir::ExprKind::Block(..),
249 ) = (parent_node, callee_node) {
250 let start = sp.shrink_to_lo();
251 let end = self.tcx.sess.source_map().next_point(callee_span);
252 err.multipart_suggestion(
253 "if you meant to create this closure and immediately call it, surround the \
254 closure with parenthesis",
255 vec![(start, "(".to_string()), (end, ")".to_string())],
256 Applicability::MaybeIncorrect,
261 fn confirm_builtin_call(
263 call_expr: &hir::Expr,
265 arg_exprs: &'gcx [hir::Expr],
266 expected: Expectation<'tcx>,
268 let (fn_sig, def_span) = match callee_ty.sty {
269 ty::FnDef(def_id, _) => (
270 callee_ty.fn_sig(self.tcx),
271 self.tcx.hir().span_if_local(def_id),
273 ty::FnPtr(sig) => (sig, None),
275 let mut unit_variant = None;
276 if let &ty::Adt(adt_def, ..) = t {
277 if adt_def.is_enum() {
278 if let hir::ExprKind::Call(ref expr, _) = call_expr.node {
279 unit_variant = Some(self.tcx.hir().hir_to_pretty_string(expr.hir_id))
284 if let hir::ExprKind::Call(ref callee, _) = call_expr.node {
285 let mut err = type_error_struct!(
290 "expected function, found {}",
292 Some(ref path) => format!("enum variant `{}`", path),
293 None => format!("`{}`", callee_ty),
297 self.identify_bad_closure_def_and_call(
304 if let Some(ref path) = unit_variant {
308 "`{}` is a unit variant, you need to write it \
309 without the parenthesis",
313 Applicability::MachineApplicable,
317 let mut inner_callee_path = None;
318 let def = match callee.node {
319 hir::ExprKind::Path(ref qpath) => {
320 self.tables.borrow().qpath_res(qpath, callee.hir_id)
322 hir::ExprKind::Call(ref inner_callee, _) => {
323 // If the call spans more than one line and the callee kind is
324 // itself another `ExprCall`, that's a clue that we might just be
325 // missing a semicolon (Issue #51055)
326 let call_is_multiline =
327 self.tcx.sess.source_map().is_multiline(call_expr.span);
328 if call_is_multiline {
329 let span = self.tcx.sess.source_map().next_point(callee.span);
332 "try adding a semicolon",
334 Applicability::MaybeIncorrect,
337 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.node {
338 inner_callee_path = Some(inner_qpath);
341 .qpath_res(inner_qpath, inner_callee.hir_id)
349 err.span_label(call_expr.span, "call expression requires function");
351 let def_span = match def {
354 Some(self.tcx.hir().span_by_hir_id(id))
358 .and_then(|did| self.tcx.hir().span_if_local(did)),
360 if let Some(span) = def_span {
361 let label = match (unit_variant, inner_callee_path) {
362 (Some(path), _) => format!("`{}` defined here", path),
363 (_, Some(hir::QPath::Resolved(_, path))) => format!(
364 "`{}` defined here returns `{}`",
366 callee_ty.to_string()
368 _ => format!("`{}` defined here", callee_ty.to_string()),
370 err.span_label(span, label);
375 "call_expr.node should be an ExprKind::Call, got {:?}",
380 // This is the "default" function signature, used in case of error.
381 // In that case, we check each argument against "error" in order to
382 // set up all the node type bindings.
384 ty::Binder::bind(self.tcx.mk_fn_sig(
385 self.err_args(arg_exprs.len()).into_iter(),
388 hir::Unsafety::Normal,
396 // Replace any late-bound regions that appear in the function
397 // signature with region variables. We also have to
398 // renormalize the associated types at this point, since they
399 // previously appeared within a `Binder<>` and hence would not
400 // have been normalized before.
402 .replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig)
404 let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
406 let inputs = if fn_sig.c_variadic {
407 if fn_sig.inputs().len() > 1 {
408 &fn_sig.inputs()[..fn_sig.inputs().len() - 1]
410 span_bug!(call_expr.span,
411 "C-variadic functions are only valid with one or more fixed arguments");
416 // Call the generic checker.
417 let expected_arg_tys = self.expected_inputs_for_expected_output(
423 self.check_argument_types(
427 &expected_arg_tys[..],
430 TupleArgumentsFlag::DontTupleArguments,
437 fn confirm_deferred_closure_call(
439 call_expr: &hir::Expr,
440 arg_exprs: &'gcx [hir::Expr],
441 expected: Expectation<'tcx>,
442 fn_sig: ty::FnSig<'tcx>,
444 // `fn_sig` is the *signature* of the cosure being called. We
445 // don't know the full details yet (`Fn` vs `FnMut` etc), but we
446 // do know the types expected for each argument and the return
449 let expected_arg_tys = self.expected_inputs_for_expected_output(
452 fn_sig.output().clone(),
456 self.check_argument_types(
463 TupleArgumentsFlag::TupleArguments,
470 fn confirm_overloaded_call(
472 call_expr: &hir::Expr,
473 arg_exprs: &'gcx [hir::Expr],
474 expected: Expectation<'tcx>,
475 method_callee: MethodCallee<'tcx>,
477 let output_type = self.check_method_argument_types(
482 TupleArgumentsFlag::TupleArguments,
486 self.write_method_call(call_expr.hir_id, method_callee);
492 pub struct DeferredCallResolution<'gcx: 'tcx, 'tcx> {
493 call_expr: &'gcx hir::Expr,
494 callee_expr: &'gcx hir::Expr,
495 adjusted_ty: Ty<'tcx>,
496 adjustments: Vec<Adjustment<'tcx>>,
497 fn_sig: ty::FnSig<'tcx>,
498 closure_def_id: DefId,
499 closure_substs: ty::ClosureSubsts<'tcx>,
502 impl<'a, 'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> {
503 pub fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
504 debug!("DeferredCallResolution::resolve() {:?}", self);
506 // we should not be invoked until the closure kind has been
507 // determined by upvar inference
509 .closure_kind(self.closure_def_id, self.closure_substs)
512 // We may now know enough to figure out fn vs fnmut etc.
513 match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
514 Some((autoref, method_callee)) => {
515 // One problem is that when we get here, we are going
516 // to have a newly instantiated function signature
517 // from the call trait. This has to be reconciled with
518 // the older function signature we had before. In
519 // principle we *should* be able to fn_sigs(), but we
520 // can't because of the annoying need for a TypeTrace.
521 // (This always bites me, should find a way to
523 let method_sig = method_callee.sig;
525 debug!("attempt_resolution: method_callee={:?}", method_callee);
527 for (method_arg_ty, self_arg_ty) in
528 method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
530 fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
536 self.fn_sig.output(),
539 let mut adjustments = self.adjustments;
540 adjustments.extend(autoref);
541 fcx.apply_adjustments(self.callee_expr, adjustments);
543 fcx.write_method_call(self.call_expr.hir_id, method_callee);
548 "failed to find an overloaded call trait for closure call"