]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/callee.rs
Rollup merge of #58717 - hellow554:nonzero_parse, r=oli-obk
[rust.git] / src / librustc_typeck / check / callee.rs
1 use super::autoderef::Autoderef;
2 use super::method::MethodCallee;
3 use super::{Expectation, FnCtxt, Needs, TupleArgumentsFlag};
4
5 use errors::{Applicability, DiagnosticBuilder};
6 use hir::def::Def;
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;
14 use syntax_pos::Span;
15
16 use rustc::hir;
17
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")
25             .emit();
26     }
27 }
28
29 enum CallStep<'tcx> {
30     Builtin(Ty<'tcx>),
31     DeferredClosure(ty::FnSig<'tcx>),
32     /// E.g., enum variant constructors.
33     Overloaded(MethodCallee<'tcx>),
34 }
35
36 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
37     pub fn check_call(
38         &self,
39         call_expr: &'gcx hir::Expr,
40         callee_expr: &'gcx hir::Expr,
41         arg_exprs: &'gcx [hir::Expr],
42         expected: Expectation<'tcx>,
43     ) -> Ty<'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);
46
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);
51         }
52         autoderef.finalize(self);
53
54         let output = match result {
55             None => {
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)
58             }
59
60             Some(CallStep::Builtin(callee_ty)) => {
61                 self.confirm_builtin_call(call_expr, callee_ty, arg_exprs, expected)
62             }
63
64             Some(CallStep::DeferredClosure(fn_sig)) => {
65                 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, fn_sig)
66             }
67
68             Some(CallStep::Overloaded(method_callee)) => {
69                 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
70             }
71         };
72
73         // we must check that return type of called functions is WF:
74         self.register_wf_obligation(output, call_expr.span, traits::MiscObligation);
75
76         output
77     }
78
79     fn try_overloaded_call_step(
80         &self,
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);
87         debug!(
88             "try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
89             call_expr, adjusted_ty
90         );
91
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));
98             }
99
100             ty::Closure(def_id, substs) => {
101                 assert_eq!(def_id.krate, LOCAL_CRATE);
102
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);
108                     let fn_sig = self
109                         .replace_bound_vars_with_fresh_vars(
110                             call_expr.span,
111                             infer::FnCall,
112                             &closure_ty,
113                         )
114                         .0;
115                     let adjustments = autoderef.adjust_steps(self, Needs::None);
116                     self.record_deferred_call_resolution(
117                         def_id,
118                         DeferredCallResolution {
119                             call_expr,
120                             callee_expr,
121                             adjusted_ty,
122                             adjustments,
123                             fn_sig,
124                             closure_def_id: def_id,
125                             closure_substs: substs,
126                         },
127                     );
128                     return Some(CallStep::DeferredClosure(fn_sig));
129                 }
130             }
131
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 => {
141                 return None;
142             }
143
144             _ => {}
145         }
146
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)
161             })
162     }
163
164     fn try_overloaded_call_traits(
165         &self,
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 &[
172             (
173                 self.tcx.lang_items().fn_trait(),
174                 Ident::from_str("call"),
175                 true,
176             ),
177             (
178                 self.tcx.lang_items().fn_mut_trait(),
179                 Ident::from_str("call_mut"),
180                 true,
181             ),
182             (
183                 self.tcx.lang_items().fn_once_trait(),
184                 Ident::from_str("call_once"),
185                 false,
186             ),
187         ] {
188             let trait_def_id = match opt_trait_def_id {
189                 Some(def_id) => def_id,
190                 None => continue,
191             };
192
193             let opt_input_types = opt_arg_exprs.map(|arg_exprs| [self.tcx.mk_tup(
194                 arg_exprs
195                 .iter()
196                 .map(|e| self.next_ty_var(
197                     TypeVariableOrigin::TypeInference(e.span)
198                 ))
199             )]);
200             let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
201
202             if let Some(ok) = self.lookup_method_in_trait(
203                 call_expr.span,
204                 method_name,
205                 trait_def_id,
206                 adjusted_ty,
207                 opt_input_types,
208             ) {
209                 let method = self.register_infer_ok_obligations(ok);
210                 let mut autoref = None;
211                 if borrow {
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,
220                             },
221                         };
222                         autoref = Some(Adjustment {
223                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
224                             target: method.sig.inputs()[0],
225                         });
226                     }
227                 }
228                 return Some((autoref, method));
229             }
230         }
231
232         None
233     }
234
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(
238         &self,
239         err: &mut DiagnosticBuilder<'a>,
240         hir_id: hir::HirId,
241         callee_node: &hir::ExprKind,
242         callee_span: Span,
243     ) {
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);
246         if let (
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,
257             );
258         }
259     }
260
261     fn confirm_builtin_call(
262         &self,
263         call_expr: &hir::Expr,
264         callee_ty: Ty<'tcx>,
265         arg_exprs: &'gcx [hir::Expr],
266         expected: Expectation<'tcx>,
267     ) -> Ty<'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),
272             ),
273             ty::FnPtr(sig) => (sig, None),
274             ref t => {
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))
280                         }
281                     }
282                 }
283
284                 if let hir::ExprKind::Call(ref callee, _) = call_expr.node {
285                     let mut err = type_error_struct!(
286                         self.tcx.sess,
287                         callee.span,
288                         callee_ty,
289                         E0618,
290                         "expected function, found {}",
291                         match unit_variant {
292                             Some(ref path) => format!("enum variant `{}`", path),
293                             None => format!("`{}`", callee_ty),
294                         }
295                     );
296
297                     self.identify_bad_closure_def_and_call(
298                         &mut err,
299                         call_expr.hir_id,
300                         &callee.node,
301                         callee.span,
302                     );
303
304                     if let Some(ref path) = unit_variant {
305                         err.span_suggestion(
306                             call_expr.span,
307                             &format!(
308                                 "`{}` is a unit variant, you need to write it \
309                                  without the parenthesis",
310                                 path
311                             ),
312                             path.to_string(),
313                             Applicability::MachineApplicable,
314                         );
315                     }
316
317                     let mut inner_callee_path = None;
318                     let def = match callee.node {
319                         hir::ExprKind::Path(ref qpath) => {
320                             self.tables.borrow().qpath_def(qpath, callee.hir_id)
321                         }
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);
330                                 err.span_suggestion(
331                                     span,
332                                     "try adding a semicolon",
333                                     ";".to_owned(),
334                                     Applicability::MaybeIncorrect,
335                                 );
336                             }
337                             if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.node {
338                                 inner_callee_path = Some(inner_qpath);
339                                 self.tables
340                                     .borrow()
341                                     .qpath_def(inner_qpath, inner_callee.hir_id)
342                             } else {
343                                 Def::Err
344                             }
345                         }
346                         _ => Def::Err,
347                     };
348
349                     err.span_label(call_expr.span, "call expression requires function");
350
351                     let def_span = match def {
352                         Def::Err => None,
353                         Def::Local(id) | Def::Upvar(id, ..) => Some(self.tcx.hir().span(id)),
354                         _ => def
355                             .opt_def_id()
356                             .and_then(|did| self.tcx.hir().span_if_local(did)),
357                     };
358                     if let Some(span) = def_span {
359                         let label = match (unit_variant, inner_callee_path) {
360                             (Some(path), _) => format!("`{}` defined here", path),
361                             (_, Some(hir::QPath::Resolved(_, path))) => format!(
362                                 "`{}` defined here returns `{}`",
363                                 path,
364                                 callee_ty.to_string()
365                             ),
366                             _ => format!("`{}` defined here", callee_ty.to_string()),
367                         };
368                         err.span_label(span, label);
369                     }
370                     err.emit();
371                 } else {
372                     bug!(
373                         "call_expr.node should be an ExprKind::Call, got {:?}",
374                         call_expr.node
375                     );
376                 }
377
378                 // This is the "default" function signature, used in case of error.
379                 // In that case, we check each argument against "error" in order to
380                 // set up all the node type bindings.
381                 (
382                     ty::Binder::bind(self.tcx.mk_fn_sig(
383                         self.err_args(arg_exprs.len()).into_iter(),
384                         self.tcx.types.err,
385                         false,
386                         hir::Unsafety::Normal,
387                         abi::Abi::Rust,
388                     )),
389                     None,
390                 )
391             }
392         };
393
394         // Replace any late-bound regions that appear in the function
395         // signature with region variables. We also have to
396         // renormalize the associated types at this point, since they
397         // previously appeared within a `Binder<>` and hence would not
398         // have been normalized before.
399         let fn_sig = self
400             .replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig)
401             .0;
402         let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
403
404         let inputs = if fn_sig.c_variadic {
405             if fn_sig.inputs().len() > 1 {
406                 &fn_sig.inputs()[..fn_sig.inputs().len() - 1]
407             } else {
408                 span_bug!(call_expr.span,
409                           "C-variadic functions are only valid with one or more fixed arguments");
410             }
411         } else {
412             &fn_sig.inputs()[..]
413         };
414         // Call the generic checker.
415         let expected_arg_tys = self.expected_inputs_for_expected_output(
416             call_expr.span,
417             expected,
418             fn_sig.output(),
419             inputs,
420         );
421         self.check_argument_types(
422             call_expr.span,
423             call_expr.span,
424             inputs,
425             &expected_arg_tys[..],
426             arg_exprs,
427             fn_sig.c_variadic,
428             TupleArgumentsFlag::DontTupleArguments,
429             def_span,
430         );
431
432         fn_sig.output()
433     }
434
435     fn confirm_deferred_closure_call(
436         &self,
437         call_expr: &hir::Expr,
438         arg_exprs: &'gcx [hir::Expr],
439         expected: Expectation<'tcx>,
440         fn_sig: ty::FnSig<'tcx>,
441     ) -> Ty<'tcx> {
442         // `fn_sig` is the *signature* of the cosure being called. We
443         // don't know the full details yet (`Fn` vs `FnMut` etc), but we
444         // do know the types expected for each argument and the return
445         // type.
446
447         let expected_arg_tys = self.expected_inputs_for_expected_output(
448             call_expr.span,
449             expected,
450             fn_sig.output().clone(),
451             fn_sig.inputs(),
452         );
453
454         self.check_argument_types(
455             call_expr.span,
456             call_expr.span,
457             fn_sig.inputs(),
458             &expected_arg_tys,
459             arg_exprs,
460             fn_sig.c_variadic,
461             TupleArgumentsFlag::TupleArguments,
462             None,
463         );
464
465         fn_sig.output()
466     }
467
468     fn confirm_overloaded_call(
469         &self,
470         call_expr: &hir::Expr,
471         arg_exprs: &'gcx [hir::Expr],
472         expected: Expectation<'tcx>,
473         method_callee: MethodCallee<'tcx>,
474     ) -> Ty<'tcx> {
475         let output_type = self.check_method_argument_types(
476             call_expr.span,
477             call_expr.span,
478             Ok(method_callee),
479             arg_exprs,
480             TupleArgumentsFlag::TupleArguments,
481             expected,
482         );
483
484         self.write_method_call(call_expr.hir_id, method_callee);
485         output_type
486     }
487 }
488
489 #[derive(Debug)]
490 pub struct DeferredCallResolution<'gcx: 'tcx, 'tcx> {
491     call_expr: &'gcx hir::Expr,
492     callee_expr: &'gcx hir::Expr,
493     adjusted_ty: Ty<'tcx>,
494     adjustments: Vec<Adjustment<'tcx>>,
495     fn_sig: ty::FnSig<'tcx>,
496     closure_def_id: DefId,
497     closure_substs: ty::ClosureSubsts<'tcx>,
498 }
499
500 impl<'a, 'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> {
501     pub fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
502         debug!("DeferredCallResolution::resolve() {:?}", self);
503
504         // we should not be invoked until the closure kind has been
505         // determined by upvar inference
506         assert!(fcx
507             .closure_kind(self.closure_def_id, self.closure_substs)
508             .is_some());
509
510         // We may now know enough to figure out fn vs fnmut etc.
511         match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
512             Some((autoref, method_callee)) => {
513                 // One problem is that when we get here, we are going
514                 // to have a newly instantiated function signature
515                 // from the call trait. This has to be reconciled with
516                 // the older function signature we had before. In
517                 // principle we *should* be able to fn_sigs(), but we
518                 // can't because of the annoying need for a TypeTrace.
519                 // (This always bites me, should find a way to
520                 // refactor it.)
521                 let method_sig = method_callee.sig;
522
523                 debug!("attempt_resolution: method_callee={:?}", method_callee);
524
525                 for (method_arg_ty, self_arg_ty) in
526                     method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
527                 {
528                     fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
529                 }
530
531                 fcx.demand_eqtype(
532                     self.call_expr.span,
533                     method_sig.output(),
534                     self.fn_sig.output(),
535                 );
536
537                 let mut adjustments = self.adjustments;
538                 adjustments.extend(autoref);
539                 fcx.apply_adjustments(self.callee_expr, adjustments);
540
541                 fcx.write_method_call(self.call_expr.hir_id, method_callee);
542             }
543             None => {
544                 span_bug!(
545                     self.call_expr.span,
546                     "failed to find an overloaded call trait for closure call"
547                 );
548             }
549         }
550     }
551 }