]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/callee.rs
compiletest: Do not run debuginfo tests with gdb on msvc targets
[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 use crate::type_error_struct;
5
6 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
7 use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
8 use rustc::ty::subst::SubstsRef;
9 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
10 use rustc::{infer, traits};
11 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
12 use rustc_hir as hir;
13 use rustc_hir::def::Res;
14 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
15 use rustc_span::Span;
16 use rustc_target::spec::abi;
17 use syntax::ast::Ident;
18
19 /// Checks that it is legal to call methods of the trait corresponding
20 /// to `trait_id` (this only cares about the trait, not the specific
21 /// method that is called).
22 pub fn check_legal_trait_for_method_call(tcx: TyCtxt<'_>, span: Span, trait_id: DefId) {
23     if tcx.lang_items().drop_trait() == Some(trait_id) {
24         struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method")
25             .span_label(span, "explicit destructor calls not allowed")
26             .emit();
27     }
28 }
29
30 enum CallStep<'tcx> {
31     Builtin(Ty<'tcx>),
32     DeferredClosure(ty::FnSig<'tcx>),
33     /// E.g., enum variant constructors.
34     Overloaded(MethodCallee<'tcx>),
35 }
36
37 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
38     pub fn check_call(
39         &self,
40         call_expr: &'tcx hir::Expr<'tcx>,
41         callee_expr: &'tcx hir::Expr<'tcx>,
42         arg_exprs: &'tcx [hir::Expr<'tcx>],
43         expected: Expectation<'tcx>,
44     ) -> Ty<'tcx> {
45         let original_callee_ty = self.check_expr(callee_expr);
46         let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty);
47
48         let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
49         let mut result = None;
50         while result.is_none() && autoderef.next().is_some() {
51             result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
52         }
53         autoderef.finalize(self);
54
55         let output = match result {
56             None => {
57                 // this will report an error since original_callee_ty is not a fn
58                 self.confirm_builtin_call(call_expr, original_callee_ty, arg_exprs, expected)
59             }
60
61             Some(CallStep::Builtin(callee_ty)) => {
62                 self.confirm_builtin_call(call_expr, callee_ty, arg_exprs, expected)
63             }
64
65             Some(CallStep::DeferredClosure(fn_sig)) => {
66                 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, fn_sig)
67             }
68
69             Some(CallStep::Overloaded(method_callee)) => {
70                 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
71             }
72         };
73
74         // we must check that return type of called functions is WF:
75         self.register_wf_obligation(output, call_expr.span, traits::MiscObligation);
76
77         output
78     }
79
80     fn try_overloaded_call_step(
81         &self,
82         call_expr: &'tcx hir::Expr<'tcx>,
83         callee_expr: &'tcx hir::Expr<'tcx>,
84         arg_exprs: &'tcx [hir::Expr<'tcx>],
85         autoderef: &Autoderef<'a, 'tcx>,
86     ) -> Option<CallStep<'tcx>> {
87         let adjusted_ty = autoderef.unambiguous_final_ty(self);
88         debug!(
89             "try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
90             call_expr, adjusted_ty
91         );
92
93         // If the callee is a bare function or a closure, then we're all set.
94         match adjusted_ty.kind {
95             ty::FnDef(..) | ty::FnPtr(_) => {
96                 let adjustments = autoderef.adjust_steps(self, Needs::None);
97                 self.apply_adjustments(callee_expr, adjustments);
98                 return Some(CallStep::Builtin(adjusted_ty));
99             }
100
101             ty::Closure(def_id, substs) => {
102                 assert_eq!(def_id.krate, LOCAL_CRATE);
103
104                 // Check whether this is a call to a closure where we
105                 // haven't yet decided on whether the closure is fn vs
106                 // fnmut vs fnonce. If so, we have to defer further processing.
107                 if self.closure_kind(def_id, substs).is_none() {
108                     let closure_ty = self.closure_sig(def_id, substs);
109                     let fn_sig = self
110                         .replace_bound_vars_with_fresh_vars(
111                             call_expr.span,
112                             infer::FnCall,
113                             &closure_ty,
114                         )
115                         .0;
116                     let adjustments = autoderef.adjust_steps(self, Needs::None);
117                     self.record_deferred_call_resolution(
118                         def_id,
119                         DeferredCallResolution {
120                             call_expr,
121                             callee_expr,
122                             adjusted_ty,
123                             adjustments,
124                             fn_sig,
125                             closure_def_id: def_id,
126                             closure_substs: substs,
127                         },
128                     );
129                     return Some(CallStep::DeferredClosure(fn_sig));
130                 }
131             }
132
133             // Hack: we know that there are traits implementing Fn for &F
134             // where F:Fn and so forth. In the particular case of types
135             // like `x: &mut FnMut()`, if there is a call `x()`, we would
136             // normally translate to `FnMut::call_mut(&mut x, ())`, but
137             // that winds up requiring `mut x: &mut FnMut()`. A little
138             // over the top. The simplest fix by far is to just ignore
139             // this case and deref again, so we wind up with
140             // `FnMut::call_mut(&mut *x, ())`.
141             ty::Ref(..) if autoderef.step_count() == 0 => {
142                 return None;
143             }
144
145             _ => {}
146         }
147
148         // Now, we look for the implementation of a Fn trait on the object's type.
149         // We first do it with the explicit instruction to look for an impl of
150         // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
151         // to the number of call parameters.
152         // If that fails (or_else branch), we try again without specifying the
153         // shape of the tuple (hence the None). This allows to detect an Fn trait
154         // is implemented, and use this information for diagnostic.
155         self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
156             .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
157             .map(|(autoref, method)| {
158                 let mut adjustments = autoderef.adjust_steps(self, Needs::None);
159                 adjustments.extend(autoref);
160                 self.apply_adjustments(callee_expr, adjustments);
161                 CallStep::Overloaded(method)
162             })
163     }
164
165     fn try_overloaded_call_traits(
166         &self,
167         call_expr: &hir::Expr<'_>,
168         adjusted_ty: Ty<'tcx>,
169         opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
170     ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
171         // Try the options that are least restrictive on the caller first.
172         for &(opt_trait_def_id, method_name, borrow) in &[
173             (self.tcx.lang_items().fn_trait(), Ident::from_str("call"), true),
174             (self.tcx.lang_items().fn_mut_trait(), Ident::from_str("call_mut"), true),
175             (self.tcx.lang_items().fn_once_trait(), Ident::from_str("call_once"), false),
176         ] {
177             let trait_def_id = match opt_trait_def_id {
178                 Some(def_id) => def_id,
179                 None => continue,
180             };
181
182             let opt_input_types = opt_arg_exprs.map(|arg_exprs| {
183                 [self.tcx.mk_tup(arg_exprs.iter().map(|e| {
184                     self.next_ty_var(TypeVariableOrigin {
185                         kind: TypeVariableOriginKind::TypeInference,
186                         span: e.span,
187                     })
188                 }))]
189             });
190             let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
191
192             if let Some(ok) = self.lookup_method_in_trait(
193                 call_expr.span,
194                 method_name,
195                 trait_def_id,
196                 adjusted_ty,
197                 opt_input_types,
198             ) {
199                 let method = self.register_infer_ok_obligations(ok);
200                 let mut autoref = None;
201                 if borrow {
202                     if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
203                         let mutbl = match mutbl {
204                             hir::Mutability::Not => AutoBorrowMutability::Not,
205                             hir::Mutability::Mut => AutoBorrowMutability::Mut {
206                                 // For initial two-phase borrow
207                                 // deployment, conservatively omit
208                                 // overloaded function call ops.
209                                 allow_two_phase_borrow: AllowTwoPhase::No,
210                             },
211                         };
212                         autoref = Some(Adjustment {
213                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
214                             target: method.sig.inputs()[0],
215                         });
216                     }
217                 }
218                 return Some((autoref, method));
219             }
220         }
221
222         None
223     }
224
225     /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
226     /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
227     fn identify_bad_closure_def_and_call(
228         &self,
229         err: &mut DiagnosticBuilder<'a>,
230         hir_id: hir::HirId,
231         callee_node: &hir::ExprKind<'_>,
232         callee_span: Span,
233     ) {
234         let hir_id = self.tcx.hir().get_parent_node(hir_id);
235         let parent_node = self.tcx.hir().get(hir_id);
236         if let (
237             hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, _, _, sp, ..), .. }),
238             hir::ExprKind::Block(..),
239         ) = (parent_node, callee_node)
240         {
241             let start = sp.shrink_to_lo();
242             let end = callee_span.shrink_to_hi();
243             err.multipart_suggestion(
244                 "if you meant to create this closure and immediately call it, surround the \
245                 closure with parenthesis",
246                 vec![(start, "(".to_string()), (end, ")".to_string())],
247                 Applicability::MaybeIncorrect,
248             );
249         }
250     }
251
252     fn confirm_builtin_call(
253         &self,
254         call_expr: &'tcx hir::Expr<'tcx>,
255         callee_ty: Ty<'tcx>,
256         arg_exprs: &'tcx [hir::Expr<'tcx>],
257         expected: Expectation<'tcx>,
258     ) -> Ty<'tcx> {
259         let (fn_sig, def_span) = match callee_ty.kind {
260             ty::FnDef(def_id, _) => {
261                 (callee_ty.fn_sig(self.tcx), self.tcx.hir().span_if_local(def_id))
262             }
263             ty::FnPtr(sig) => (sig, None),
264             ref t => {
265                 let mut unit_variant = None;
266                 if let &ty::Adt(adt_def, ..) = t {
267                     if adt_def.is_enum() {
268                         if let hir::ExprKind::Call(ref expr, _) = call_expr.kind {
269                             unit_variant = Some(self.tcx.hir().hir_to_pretty_string(expr.hir_id))
270                         }
271                     }
272                 }
273
274                 if let hir::ExprKind::Call(ref callee, _) = call_expr.kind {
275                     let mut err = type_error_struct!(
276                         self.tcx.sess,
277                         callee.span,
278                         callee_ty,
279                         E0618,
280                         "expected function, found {}",
281                         match unit_variant {
282                             Some(ref path) => format!("enum variant `{}`", path),
283                             None => format!("`{}`", callee_ty),
284                         }
285                     );
286
287                     self.identify_bad_closure_def_and_call(
288                         &mut err,
289                         call_expr.hir_id,
290                         &callee.kind,
291                         callee.span,
292                     );
293
294                     if let Some(ref path) = unit_variant {
295                         err.span_suggestion(
296                             call_expr.span,
297                             &format!(
298                                 "`{}` is a unit variant, you need to write it \
299                                  without the parenthesis",
300                                 path
301                             ),
302                             path.to_string(),
303                             Applicability::MachineApplicable,
304                         );
305                     }
306
307                     let mut inner_callee_path = None;
308                     let def = match callee.kind {
309                         hir::ExprKind::Path(ref qpath) => {
310                             self.tables.borrow().qpath_res(qpath, callee.hir_id)
311                         }
312                         hir::ExprKind::Call(ref inner_callee, _) => {
313                             // If the call spans more than one line and the callee kind is
314                             // itself another `ExprCall`, that's a clue that we might just be
315                             // missing a semicolon (Issue #51055)
316                             let call_is_multiline =
317                                 self.tcx.sess.source_map().is_multiline(call_expr.span);
318                             if call_is_multiline {
319                                 err.span_suggestion(
320                                     callee.span.shrink_to_hi(),
321                                     "try adding a semicolon",
322                                     ";".to_owned(),
323                                     Applicability::MaybeIncorrect,
324                                 );
325                             }
326                             if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
327                                 inner_callee_path = Some(inner_qpath);
328                                 self.tables.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
329                             } else {
330                                 Res::Err
331                             }
332                         }
333                         _ => Res::Err,
334                     };
335
336                     err.span_label(call_expr.span, "call expression requires function");
337
338                     if let Some(span) = self.tcx.hir().res_span(def) {
339                         let label = match (unit_variant, inner_callee_path) {
340                             (Some(path), _) => format!("`{}` defined here", path),
341                             (_, Some(hir::QPath::Resolved(_, path))) => format!(
342                                 "`{}` defined here returns `{}`",
343                                 path,
344                                 callee_ty.to_string()
345                             ),
346                             _ => format!("`{}` defined here", callee_ty.to_string()),
347                         };
348                         err.span_label(span, label);
349                     }
350                     err.emit();
351                 } else {
352                     bug!("call_expr.kind should be an ExprKind::Call, got {:?}", call_expr.kind);
353                 }
354
355                 // This is the "default" function signature, used in case of error.
356                 // In that case, we check each argument against "error" in order to
357                 // set up all the node type bindings.
358                 (
359                     ty::Binder::bind(self.tcx.mk_fn_sig(
360                         self.err_args(arg_exprs.len()).into_iter(),
361                         self.tcx.types.err,
362                         false,
363                         hir::Unsafety::Normal,
364                         abi::Abi::Rust,
365                     )),
366                     None,
367                 )
368             }
369         };
370
371         // Replace any late-bound regions that appear in the function
372         // signature with region variables. We also have to
373         // renormalize the associated types at this point, since they
374         // previously appeared within a `Binder<>` and hence would not
375         // have been normalized before.
376         let fn_sig =
377             self.replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig).0;
378         let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
379
380         // Call the generic checker.
381         let expected_arg_tys = self.expected_inputs_for_expected_output(
382             call_expr.span,
383             expected,
384             fn_sig.output(),
385             fn_sig.inputs(),
386         );
387         self.check_argument_types(
388             call_expr.span,
389             call_expr,
390             fn_sig.inputs(),
391             &expected_arg_tys[..],
392             arg_exprs,
393             fn_sig.c_variadic,
394             TupleArgumentsFlag::DontTupleArguments,
395             def_span,
396         );
397
398         fn_sig.output()
399     }
400
401     fn confirm_deferred_closure_call(
402         &self,
403         call_expr: &'tcx hir::Expr<'tcx>,
404         arg_exprs: &'tcx [hir::Expr<'tcx>],
405         expected: Expectation<'tcx>,
406         fn_sig: ty::FnSig<'tcx>,
407     ) -> Ty<'tcx> {
408         // `fn_sig` is the *signature* of the cosure being called. We
409         // don't know the full details yet (`Fn` vs `FnMut` etc), but we
410         // do know the types expected for each argument and the return
411         // type.
412
413         let expected_arg_tys = self.expected_inputs_for_expected_output(
414             call_expr.span,
415             expected,
416             fn_sig.output().clone(),
417             fn_sig.inputs(),
418         );
419
420         self.check_argument_types(
421             call_expr.span,
422             call_expr,
423             fn_sig.inputs(),
424             &expected_arg_tys,
425             arg_exprs,
426             fn_sig.c_variadic,
427             TupleArgumentsFlag::TupleArguments,
428             None,
429         );
430
431         fn_sig.output()
432     }
433
434     fn confirm_overloaded_call(
435         &self,
436         call_expr: &'tcx hir::Expr<'tcx>,
437         arg_exprs: &'tcx [hir::Expr<'tcx>],
438         expected: Expectation<'tcx>,
439         method_callee: MethodCallee<'tcx>,
440     ) -> Ty<'tcx> {
441         let output_type = self.check_method_argument_types(
442             call_expr.span,
443             call_expr,
444             Ok(method_callee),
445             arg_exprs,
446             TupleArgumentsFlag::TupleArguments,
447             expected,
448         );
449
450         self.write_method_call(call_expr.hir_id, method_callee);
451         output_type
452     }
453 }
454
455 #[derive(Debug)]
456 pub struct DeferredCallResolution<'tcx> {
457     call_expr: &'tcx hir::Expr<'tcx>,
458     callee_expr: &'tcx hir::Expr<'tcx>,
459     adjusted_ty: Ty<'tcx>,
460     adjustments: Vec<Adjustment<'tcx>>,
461     fn_sig: ty::FnSig<'tcx>,
462     closure_def_id: DefId,
463     closure_substs: SubstsRef<'tcx>,
464 }
465
466 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
467     pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
468         debug!("DeferredCallResolution::resolve() {:?}", self);
469
470         // we should not be invoked until the closure kind has been
471         // determined by upvar inference
472         assert!(fcx.closure_kind(self.closure_def_id, self.closure_substs).is_some());
473
474         // We may now know enough to figure out fn vs fnmut etc.
475         match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
476             Some((autoref, method_callee)) => {
477                 // One problem is that when we get here, we are going
478                 // to have a newly instantiated function signature
479                 // from the call trait. This has to be reconciled with
480                 // the older function signature we had before. In
481                 // principle we *should* be able to fn_sigs(), but we
482                 // can't because of the annoying need for a TypeTrace.
483                 // (This always bites me, should find a way to
484                 // refactor it.)
485                 let method_sig = method_callee.sig;
486
487                 debug!("attempt_resolution: method_callee={:?}", method_callee);
488
489                 for (method_arg_ty, self_arg_ty) in
490                     method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
491                 {
492                     fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
493                 }
494
495                 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
496
497                 let mut adjustments = self.adjustments;
498                 adjustments.extend(autoref);
499                 fcx.apply_adjustments(self.callee_expr, adjustments);
500
501                 fcx.write_method_call(self.call_expr.hir_id, method_callee);
502             }
503             None => {
504                 span_bug!(
505                     self.call_expr.span,
506                     "failed to find an overloaded call trait for closure call"
507                 );
508             }
509         }
510     }
511 }