]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/callee.rs
Rollup merge of #63416 - RalfJung:apfloat, r=eddyb
[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, TypeVariableOriginKind};
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, 'tcx> FnCtxt<'a, 'tcx> {
37     pub fn check_call(
38         &self,
39         call_expr: &'tcx hir::Expr,
40         callee_expr: &'tcx hir::Expr,
41         arg_exprs: &'tcx [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: &'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);
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.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));
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<&'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 &[
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| {
197                     self.next_ty_var(TypeVariableOrigin {
198                         kind: TypeVariableOriginKind::TypeInference,
199                         span: e.span,
200                     })
201                 })
202             )]);
203             let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
204
205             if let Some(ok) = self.lookup_method_in_trait(
206                 call_expr.span,
207                 method_name,
208                 trait_def_id,
209                 adjusted_ty,
210                 opt_input_types,
211             ) {
212                 let method = self.register_infer_ok_obligations(ok);
213                 let mut autoref = None;
214                 if borrow {
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,
223                             },
224                         };
225                         autoref = Some(Adjustment {
226                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
227                             target: method.sig.inputs()[0],
228                         });
229                     }
230                 }
231                 return Some((autoref, method));
232             }
233         }
234
235         None
236     }
237
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(
241         &self,
242         err: &mut DiagnosticBuilder<'a>,
243         hir_id: hir::HirId,
244         callee_node: &hir::ExprKind,
245         callee_span: Span,
246     ) {
247         let hir_id = self.tcx.hir().get_parent_node(hir_id);
248         let parent_node = self.tcx.hir().get(hir_id);
249         if let (
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,
260             );
261         }
262     }
263
264     fn confirm_builtin_call(
265         &self,
266         call_expr: &'tcx hir::Expr,
267         callee_ty: Ty<'tcx>,
268         arg_exprs: &'tcx [hir::Expr],
269         expected: Expectation<'tcx>,
270     ) -> Ty<'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),
275             ),
276             ty::FnPtr(sig) => (sig, None),
277             ref t => {
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))
283                         }
284                     }
285                 }
286
287                 if let hir::ExprKind::Call(ref callee, _) = call_expr.kind {
288                     let mut err = type_error_struct!(
289                         self.tcx.sess,
290                         callee.span,
291                         callee_ty,
292                         E0618,
293                         "expected function, found {}",
294                         match unit_variant {
295                             Some(ref path) => format!("enum variant `{}`", path),
296                             None => format!("`{}`", callee_ty),
297                         }
298                     );
299
300                     self.identify_bad_closure_def_and_call(
301                         &mut err,
302                         call_expr.hir_id,
303                         &callee.kind,
304                         callee.span,
305                     );
306
307                     if let Some(ref path) = unit_variant {
308                         err.span_suggestion(
309                             call_expr.span,
310                             &format!(
311                                 "`{}` is a unit variant, you need to write it \
312                                  without the parenthesis",
313                                 path
314                             ),
315                             path.to_string(),
316                             Applicability::MachineApplicable,
317                         );
318                     }
319
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)
324                         }
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);
333                                 err.span_suggestion(
334                                     span,
335                                     "try adding a semicolon",
336                                     ";".to_owned(),
337                                     Applicability::MaybeIncorrect,
338                                 );
339                             }
340                             if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
341                                 inner_callee_path = Some(inner_qpath);
342                                 self.tables
343                                     .borrow()
344                                     .qpath_res(inner_qpath, inner_callee.hir_id)
345                             } else {
346                                 Res::Err
347                             }
348                         }
349                         _ => Res::Err,
350                     };
351
352                     err.span_label(call_expr.span, "call expression requires function");
353
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 `{}`",
359                                 path,
360                                 callee_ty.to_string()
361                             ),
362                             _ => format!("`{}` defined here", callee_ty.to_string()),
363                         };
364                         err.span_label(span, label);
365                     }
366                     err.emit();
367                 } else {
368                     bug!(
369                         "call_expr.kind should be an ExprKind::Call, got {:?}",
370                         call_expr.kind
371                     );
372                 }
373
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.
377                 (
378                     ty::Binder::bind(self.tcx.mk_fn_sig(
379                         self.err_args(arg_exprs.len()).into_iter(),
380                         self.tcx.types.err,
381                         false,
382                         hir::Unsafety::Normal,
383                         abi::Abi::Rust,
384                     )),
385                     None,
386                 )
387             }
388         };
389
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.
395         let fn_sig = self
396             .replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig)
397             .0;
398         let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
399
400         // Call the generic checker.
401         let expected_arg_tys = self.expected_inputs_for_expected_output(
402             call_expr.span,
403             expected,
404             fn_sig.output(),
405             fn_sig.inputs(),
406         );
407         self.check_argument_types(
408             call_expr.span,
409             call_expr,
410             fn_sig.inputs(),
411             &expected_arg_tys[..],
412             arg_exprs,
413             fn_sig.c_variadic,
414             TupleArgumentsFlag::DontTupleArguments,
415             def_span,
416         );
417
418         fn_sig.output()
419     }
420
421     fn confirm_deferred_closure_call(
422         &self,
423         call_expr: &'tcx hir::Expr,
424         arg_exprs: &'tcx [hir::Expr],
425         expected: Expectation<'tcx>,
426         fn_sig: ty::FnSig<'tcx>,
427     ) -> Ty<'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
431         // type.
432
433         let expected_arg_tys = self.expected_inputs_for_expected_output(
434             call_expr.span,
435             expected,
436             fn_sig.output().clone(),
437             fn_sig.inputs(),
438         );
439
440         self.check_argument_types(
441             call_expr.span,
442             call_expr,
443             fn_sig.inputs(),
444             &expected_arg_tys,
445             arg_exprs,
446             fn_sig.c_variadic,
447             TupleArgumentsFlag::TupleArguments,
448             None,
449         );
450
451         fn_sig.output()
452     }
453
454     fn confirm_overloaded_call(
455         &self,
456         call_expr: &'tcx hir::Expr,
457         arg_exprs: &'tcx [hir::Expr],
458         expected: Expectation<'tcx>,
459         method_callee: MethodCallee<'tcx>,
460     ) -> Ty<'tcx> {
461         let output_type = self.check_method_argument_types(
462             call_expr.span,
463             call_expr,
464             Ok(method_callee),
465             arg_exprs,
466             TupleArgumentsFlag::TupleArguments,
467             expected,
468         );
469
470         self.write_method_call(call_expr.hir_id, method_callee);
471         output_type
472     }
473 }
474
475 #[derive(Debug)]
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>,
484 }
485
486 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
487     pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
488         debug!("DeferredCallResolution::resolve() {:?}", self);
489
490         // we should not be invoked until the closure kind has been
491         // determined by upvar inference
492         assert!(fcx
493             .closure_kind(self.closure_def_id, self.closure_substs)
494             .is_some());
495
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
506                 // refactor it.)
507                 let method_sig = method_callee.sig;
508
509                 debug!("attempt_resolution: method_callee={:?}", method_callee);
510
511                 for (method_arg_ty, self_arg_ty) in
512                     method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
513                 {
514                     fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
515                 }
516
517                 fcx.demand_eqtype(
518                     self.call_expr.span,
519                     method_sig.output(),
520                     self.fn_sig.output(),
521                 );
522
523                 let mut adjustments = self.adjustments;
524                 adjustments.extend(autoref);
525                 fcx.apply_adjustments(self.callee_expr, adjustments);
526
527                 fcx.write_method_call(self.call_expr.hir_id, method_callee);
528             }
529             None => {
530                 span_bug!(
531                     self.call_expr.span,
532                     "failed to find an overloaded call trait for closure call"
533                 );
534             }
535         }
536     }
537 }