]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/callee.rs
Rollup merge of #66081 - RalfJung:ptr-offset, r=zackmdavis
[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::ty::subst::SubstsRef;
11 use rustc::{infer, traits};
12 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
13 use rustc_target::spec::abi;
14 use syntax::ast::Ident;
15 use syntax_pos::Span;
16
17 use rustc::hir;
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,
41         callee_expr: &'tcx hir::Expr,
42         arg_exprs: &'tcx [hir::Expr],
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,
83         callee_expr: &'tcx hir::Expr,
84         arg_exprs: &'tcx [hir::Expr],
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]>,
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             (
174                 self.tcx.lang_items().fn_trait(),
175                 Ident::from_str("call"),
176                 true,
177             ),
178             (
179                 self.tcx.lang_items().fn_mut_trait(),
180                 Ident::from_str("call_mut"),
181                 true,
182             ),
183             (
184                 self.tcx.lang_items().fn_once_trait(),
185                 Ident::from_str("call_once"),
186                 false,
187             ),
188         ] {
189             let trait_def_id = match opt_trait_def_id {
190                 Some(def_id) => def_id,
191                 None => continue,
192             };
193
194             let opt_input_types = opt_arg_exprs.map(|arg_exprs| [self.tcx.mk_tup(
195                 arg_exprs
196                 .iter()
197                 .map(|e| {
198                     self.next_ty_var(TypeVariableOrigin {
199                         kind: TypeVariableOriginKind::TypeInference,
200                         span: e.span,
201                     })
202                 })
203             )]);
204             let opt_input_types = opt_input_types.as_ref().map(AsRef::as_ref);
205
206             if let Some(ok) = self.lookup_method_in_trait(
207                 call_expr.span,
208                 method_name,
209                 trait_def_id,
210                 adjusted_ty,
211                 opt_input_types,
212             ) {
213                 let method = self.register_infer_ok_obligations(ok);
214                 let mut autoref = None;
215                 if borrow {
216                     if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
217                         let mutbl = match mutbl {
218                             hir::MutImmutable => AutoBorrowMutability::Immutable,
219                             hir::MutMutable => AutoBorrowMutability::Mutable {
220                                 // For initial two-phase borrow
221                                 // deployment, conservatively omit
222                                 // overloaded function call ops.
223                                 allow_two_phase_borrow: AllowTwoPhase::No,
224                             },
225                         };
226                         autoref = Some(Adjustment {
227                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
228                             target: method.sig.inputs()[0],
229                         });
230                     }
231                 }
232                 return Some((autoref, method));
233             }
234         }
235
236         None
237     }
238
239     /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
240     /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
241     fn identify_bad_closure_def_and_call(
242         &self,
243         err: &mut DiagnosticBuilder<'a>,
244         hir_id: hir::HirId,
245         callee_node: &hir::ExprKind,
246         callee_span: Span,
247     ) {
248         let hir_id = self.tcx.hir().get_parent_node(hir_id);
249         let parent_node = self.tcx.hir().get(hir_id);
250         if let (
251             hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, _, _, sp, ..), .. }),
252             hir::ExprKind::Block(..),
253         ) = (parent_node, callee_node) {
254             let start = sp.shrink_to_lo();
255             let end = self.tcx.sess.source_map().next_point(callee_span);
256             err.multipart_suggestion(
257                 "if you meant to create this closure and immediately call it, surround the \
258                 closure with parenthesis",
259                 vec![(start, "(".to_string()), (end, ")".to_string())],
260                 Applicability::MaybeIncorrect,
261             );
262         }
263     }
264
265     fn confirm_builtin_call(
266         &self,
267         call_expr: &'tcx hir::Expr,
268         callee_ty: Ty<'tcx>,
269         arg_exprs: &'tcx [hir::Expr],
270         expected: Expectation<'tcx>,
271     ) -> Ty<'tcx> {
272         let (fn_sig, def_span) = match callee_ty.kind {
273             ty::FnDef(def_id, _) => (
274                 callee_ty.fn_sig(self.tcx),
275                 self.tcx.hir().span_if_local(def_id),
276             ),
277             ty::FnPtr(sig) => (sig, None),
278             ref t => {
279                 let mut unit_variant = None;
280                 if let &ty::Adt(adt_def, ..) = t {
281                     if adt_def.is_enum() {
282                         if let hir::ExprKind::Call(ref expr, _) = call_expr.kind {
283                             unit_variant = Some(self.tcx.hir().hir_to_pretty_string(expr.hir_id))
284                         }
285                     }
286                 }
287
288                 if let hir::ExprKind::Call(ref callee, _) = call_expr.kind {
289                     let mut err = type_error_struct!(
290                         self.tcx.sess,
291                         callee.span,
292                         callee_ty,
293                         E0618,
294                         "expected function, found {}",
295                         match unit_variant {
296                             Some(ref path) => format!("enum variant `{}`", path),
297                             None => format!("`{}`", callee_ty),
298                         }
299                     );
300
301                     self.identify_bad_closure_def_and_call(
302                         &mut err,
303                         call_expr.hir_id,
304                         &callee.kind,
305                         callee.span,
306                     );
307
308                     if let Some(ref path) = unit_variant {
309                         err.span_suggestion(
310                             call_expr.span,
311                             &format!(
312                                 "`{}` is a unit variant, you need to write it \
313                                  without the parenthesis",
314                                 path
315                             ),
316                             path.to_string(),
317                             Applicability::MachineApplicable,
318                         );
319                     }
320
321                     let mut inner_callee_path = None;
322                     let def = match callee.kind {
323                         hir::ExprKind::Path(ref qpath) => {
324                             self.tables.borrow().qpath_res(qpath, callee.hir_id)
325                         }
326                         hir::ExprKind::Call(ref inner_callee, _) => {
327                             // If the call spans more than one line and the callee kind is
328                             // itself another `ExprCall`, that's a clue that we might just be
329                             // missing a semicolon (Issue #51055)
330                             let call_is_multiline =
331                                 self.tcx.sess.source_map().is_multiline(call_expr.span);
332                             if call_is_multiline {
333                                 let span = self.tcx.sess.source_map().next_point(callee.span);
334                                 err.span_suggestion(
335                                     span,
336                                     "try adding a semicolon",
337                                     ";".to_owned(),
338                                     Applicability::MaybeIncorrect,
339                                 );
340                             }
341                             if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
342                                 inner_callee_path = Some(inner_qpath);
343                                 self.tables
344                                     .borrow()
345                                     .qpath_res(inner_qpath, inner_callee.hir_id)
346                             } else {
347                                 Res::Err
348                             }
349                         }
350                         _ => Res::Err,
351                     };
352
353                     err.span_label(call_expr.span, "call expression requires function");
354
355                     if let Some(span) = self.tcx.hir().res_span(def) {
356                         let label = match (unit_variant, inner_callee_path) {
357                             (Some(path), _) => format!("`{}` defined here", path),
358                             (_, Some(hir::QPath::Resolved(_, path))) => format!(
359                                 "`{}` defined here returns `{}`",
360                                 path,
361                                 callee_ty.to_string()
362                             ),
363                             _ => format!("`{}` defined here", callee_ty.to_string()),
364                         };
365                         err.span_label(span, label);
366                     }
367                     err.emit();
368                 } else {
369                     bug!(
370                         "call_expr.kind should be an ExprKind::Call, got {:?}",
371                         call_expr.kind
372                     );
373                 }
374
375                 // This is the "default" function signature, used in case of error.
376                 // In that case, we check each argument against "error" in order to
377                 // set up all the node type bindings.
378                 (
379                     ty::Binder::bind(self.tcx.mk_fn_sig(
380                         self.err_args(arg_exprs.len()).into_iter(),
381                         self.tcx.types.err,
382                         false,
383                         hir::Unsafety::Normal,
384                         abi::Abi::Rust,
385                     )),
386                     None,
387                 )
388             }
389         };
390
391         // Replace any late-bound regions that appear in the function
392         // signature with region variables. We also have to
393         // renormalize the associated types at this point, since they
394         // previously appeared within a `Binder<>` and hence would not
395         // have been normalized before.
396         let fn_sig = self
397             .replace_bound_vars_with_fresh_vars(call_expr.span, infer::FnCall, &fn_sig)
398             .0;
399         let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
400
401         // Call the generic checker.
402         let expected_arg_tys = self.expected_inputs_for_expected_output(
403             call_expr.span,
404             expected,
405             fn_sig.output(),
406             fn_sig.inputs(),
407         );
408         self.check_argument_types(
409             call_expr.span,
410             call_expr,
411             fn_sig.inputs(),
412             &expected_arg_tys[..],
413             arg_exprs,
414             fn_sig.c_variadic,
415             TupleArgumentsFlag::DontTupleArguments,
416             def_span,
417         );
418
419         fn_sig.output()
420     }
421
422     fn confirm_deferred_closure_call(
423         &self,
424         call_expr: &'tcx hir::Expr,
425         arg_exprs: &'tcx [hir::Expr],
426         expected: Expectation<'tcx>,
427         fn_sig: ty::FnSig<'tcx>,
428     ) -> Ty<'tcx> {
429         // `fn_sig` is the *signature* of the cosure being called. We
430         // don't know the full details yet (`Fn` vs `FnMut` etc), but we
431         // do know the types expected for each argument and the return
432         // type.
433
434         let expected_arg_tys = self.expected_inputs_for_expected_output(
435             call_expr.span,
436             expected,
437             fn_sig.output().clone(),
438             fn_sig.inputs(),
439         );
440
441         self.check_argument_types(
442             call_expr.span,
443             call_expr,
444             fn_sig.inputs(),
445             &expected_arg_tys,
446             arg_exprs,
447             fn_sig.c_variadic,
448             TupleArgumentsFlag::TupleArguments,
449             None,
450         );
451
452         fn_sig.output()
453     }
454
455     fn confirm_overloaded_call(
456         &self,
457         call_expr: &'tcx hir::Expr,
458         arg_exprs: &'tcx [hir::Expr],
459         expected: Expectation<'tcx>,
460         method_callee: MethodCallee<'tcx>,
461     ) -> Ty<'tcx> {
462         let output_type = self.check_method_argument_types(
463             call_expr.span,
464             call_expr,
465             Ok(method_callee),
466             arg_exprs,
467             TupleArgumentsFlag::TupleArguments,
468             expected,
469         );
470
471         self.write_method_call(call_expr.hir_id, method_callee);
472         output_type
473     }
474 }
475
476 #[derive(Debug)]
477 pub struct DeferredCallResolution<'tcx> {
478     call_expr: &'tcx hir::Expr,
479     callee_expr: &'tcx hir::Expr,
480     adjusted_ty: Ty<'tcx>,
481     adjustments: Vec<Adjustment<'tcx>>,
482     fn_sig: ty::FnSig<'tcx>,
483     closure_def_id: DefId,
484     closure_substs: SubstsRef<'tcx>,
485 }
486
487 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
488     pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
489         debug!("DeferredCallResolution::resolve() {:?}", self);
490
491         // we should not be invoked until the closure kind has been
492         // determined by upvar inference
493         assert!(fcx
494             .closure_kind(self.closure_def_id, self.closure_substs)
495             .is_some());
496
497         // We may now know enough to figure out fn vs fnmut etc.
498         match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
499             Some((autoref, method_callee)) => {
500                 // One problem is that when we get here, we are going
501                 // to have a newly instantiated function signature
502                 // from the call trait. This has to be reconciled with
503                 // the older function signature we had before. In
504                 // principle we *should* be able to fn_sigs(), but we
505                 // can't because of the annoying need for a TypeTrace.
506                 // (This always bites me, should find a way to
507                 // refactor it.)
508                 let method_sig = method_callee.sig;
509
510                 debug!("attempt_resolution: method_callee={:?}", method_callee);
511
512                 for (method_arg_ty, self_arg_ty) in
513                     method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs())
514                 {
515                     fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
516                 }
517
518                 fcx.demand_eqtype(
519                     self.call_expr.span,
520                     method_sig.output(),
521                     self.fn_sig.output(),
522                 );
523
524                 let mut adjustments = self.adjustments;
525                 adjustments.extend(autoref);
526                 fcx.apply_adjustments(self.callee_expr, adjustments);
527
528                 fcx.write_method_call(self.call_expr.hir_id, method_callee);
529             }
530             None => {
531                 span_bug!(
532                     self.call_expr.span,
533                     "failed to find an overloaded call trait for closure call"
534                 );
535             }
536         }
537     }
538 }