]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/callee.rs
Auto merge of #60903 - nnethercote:mv-gensyms-from-Symbol-to-Ident, r=petrochenkov
[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::Res;
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_res(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_res(inner_qpath, inner_callee.hir_id)
342                             } else {
343                                 Res::Err
344                             }
345                         }
346                         _ => Res::Err,
347                     };
348
349                     err.span_label(call_expr.span, "call expression requires function");
350
351                     let def_span = match def {
352                         Res::Err => None,
353                         Res::Local(id) | Res::Upvar(id, ..) => {
354                             Some(self.tcx.hir().span_by_hir_id(id))
355                         },
356                         _ => def
357                             .opt_def_id()
358                             .and_then(|did| self.tcx.hir().span_if_local(did)),
359                     };
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 `{}`",
365                                 path,
366                                 callee_ty.to_string()
367                             ),
368                             _ => format!("`{}` defined here", callee_ty.to_string()),
369                         };
370                         err.span_label(span, label);
371                     }
372                     err.emit();
373                 } else {
374                     bug!(
375                         "call_expr.node should be an ExprKind::Call, got {:?}",
376                         call_expr.node
377                     );
378                 }
379
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.
383                 (
384                     ty::Binder::bind(self.tcx.mk_fn_sig(
385                         self.err_args(arg_exprs.len()).into_iter(),
386                         self.tcx.types.err,
387                         false,
388                         hir::Unsafety::Normal,
389                         abi::Abi::Rust,
390                     )),
391                     None,
392                 )
393             }
394         };
395
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.
401         let fn_sig = self
402             .replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig)
403             .0;
404         let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
405
406         let inputs = if fn_sig.c_variadic {
407             if fn_sig.inputs().len() > 1 {
408                 &fn_sig.inputs()[..fn_sig.inputs().len() - 1]
409             } else {
410                 span_bug!(call_expr.span,
411                           "C-variadic functions are only valid with one or more fixed arguments");
412             }
413         } else {
414             &fn_sig.inputs()[..]
415         };
416         // Call the generic checker.
417         let expected_arg_tys = self.expected_inputs_for_expected_output(
418             call_expr.span,
419             expected,
420             fn_sig.output(),
421             inputs,
422         );
423         self.check_argument_types(
424             call_expr.span,
425             call_expr.span,
426             inputs,
427             &expected_arg_tys[..],
428             arg_exprs,
429             fn_sig.c_variadic,
430             TupleArgumentsFlag::DontTupleArguments,
431             def_span,
432         );
433
434         fn_sig.output()
435     }
436
437     fn confirm_deferred_closure_call(
438         &self,
439         call_expr: &hir::Expr,
440         arg_exprs: &'gcx [hir::Expr],
441         expected: Expectation<'tcx>,
442         fn_sig: ty::FnSig<'tcx>,
443     ) -> Ty<'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
447         // type.
448
449         let expected_arg_tys = self.expected_inputs_for_expected_output(
450             call_expr.span,
451             expected,
452             fn_sig.output().clone(),
453             fn_sig.inputs(),
454         );
455
456         self.check_argument_types(
457             call_expr.span,
458             call_expr.span,
459             fn_sig.inputs(),
460             &expected_arg_tys,
461             arg_exprs,
462             fn_sig.c_variadic,
463             TupleArgumentsFlag::TupleArguments,
464             None,
465         );
466
467         fn_sig.output()
468     }
469
470     fn confirm_overloaded_call(
471         &self,
472         call_expr: &hir::Expr,
473         arg_exprs: &'gcx [hir::Expr],
474         expected: Expectation<'tcx>,
475         method_callee: MethodCallee<'tcx>,
476     ) -> Ty<'tcx> {
477         let output_type = self.check_method_argument_types(
478             call_expr.span,
479             call_expr.span,
480             Ok(method_callee),
481             arg_exprs,
482             TupleArgumentsFlag::TupleArguments,
483             expected,
484         );
485
486         self.write_method_call(call_expr.hir_id, method_callee);
487         output_type
488     }
489 }
490
491 #[derive(Debug)]
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>,
500 }
501
502 impl<'a, 'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> {
503     pub fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
504         debug!("DeferredCallResolution::resolve() {:?}", self);
505
506         // we should not be invoked until the closure kind has been
507         // determined by upvar inference
508         assert!(fcx
509             .closure_kind(self.closure_def_id, self.closure_substs)
510             .is_some());
511
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
522                 // refactor it.)
523                 let method_sig = method_callee.sig;
524
525                 debug!("attempt_resolution: method_callee={:?}", method_callee);
526
527                 for (method_arg_ty, self_arg_ty) in
528                     method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
529                 {
530                     fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
531                 }
532
533                 fcx.demand_eqtype(
534                     self.call_expr.span,
535                     method_sig.output(),
536                     self.fn_sig.output(),
537                 );
538
539                 let mut adjustments = self.adjustments;
540                 adjustments.extend(autoref);
541                 fcx.apply_adjustments(self.callee_expr, adjustments);
542
543                 fcx.write_method_call(self.call_expr.hir_id, method_callee);
544             }
545             None => {
546                 span_bug!(
547                     self.call_expr.span,
548                     "failed to find an overloaded call trait for closure call"
549                 );
550             }
551         }
552     }
553 }