]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/callee.rs
866949220b5dfba64c3265a415b41018a523003e
[rust.git] / src / librustc_typeck / check / callee.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use super::{Expectation, FnCtxt, TupleArgumentsFlag};
12 use super::autoderef::Autoderef;
13 use super::method::MethodCallee;
14
15 use hir::def::Def;
16 use hir::def_id::{DefId, LOCAL_CRATE};
17 use rustc::{infer, traits};
18 use rustc::ty::{self, TyCtxt, TypeFoldable, LvaluePreference, Ty};
19 use rustc::ty::subst::Subst;
20 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow};
21 use syntax::abi;
22 use syntax::symbol::Symbol;
23 use syntax_pos::Span;
24
25 use rustc::hir;
26
27 /// Check that it is legal to call methods of the trait corresponding
28 /// to `trait_id` (this only cares about the trait, not the specific
29 /// method that is called)
30 pub fn check_legal_trait_for_method_call(tcx: TyCtxt, span: Span, trait_id: DefId) {
31     if tcx.lang_items().drop_trait() == Some(trait_id) {
32         struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method")
33             .span_label(span, "explicit destructor calls not allowed")
34             .emit();
35     }
36 }
37
38 enum CallStep<'tcx> {
39     Builtin(Ty<'tcx>),
40     DeferredClosure(ty::FnSig<'tcx>),
41     /// e.g. enum variant constructors
42     Overloaded(MethodCallee<'tcx>),
43 }
44
45 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
46     pub fn check_call(&self,
47                       call_expr: &'gcx hir::Expr,
48                       callee_expr: &'gcx hir::Expr,
49                       arg_exprs: &'gcx [hir::Expr],
50                       expected: Expectation<'tcx>)
51                       -> Ty<'tcx> {
52         let original_callee_ty = self.check_expr(callee_expr);
53         let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty);
54
55         let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
56         let mut result = None;
57         while result.is_none() && autoderef.next().is_some() {
58             result = self.try_overloaded_call_step(call_expr, callee_expr, &autoderef);
59         }
60         autoderef.finalize();
61
62         let output = match result {
63             None => {
64                 // this will report an error since original_callee_ty is not a fn
65                 self.confirm_builtin_call(call_expr, original_callee_ty, arg_exprs, expected)
66             }
67
68             Some(CallStep::Builtin(callee_ty)) => {
69                 self.confirm_builtin_call(call_expr, callee_ty, arg_exprs, expected)
70             }
71
72             Some(CallStep::DeferredClosure(fn_sig)) => {
73                 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, fn_sig)
74             }
75
76             Some(CallStep::Overloaded(method_callee)) => {
77                 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
78             }
79         };
80
81         // we must check that return type of called functions is WF:
82         self.register_wf_obligation(output, call_expr.span, traits::MiscObligation);
83
84         output
85     }
86
87     fn try_overloaded_call_step(&self,
88                                 call_expr: &'gcx hir::Expr,
89                                 callee_expr: &'gcx hir::Expr,
90                                 autoderef: &Autoderef<'a, 'gcx, 'tcx>)
91                                 -> Option<CallStep<'tcx>> {
92         let adjusted_ty = autoderef.unambiguous_final_ty();
93         debug!("try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
94                call_expr,
95                adjusted_ty);
96
97         // If the callee is a bare function or a closure, then we're all set.
98         match adjusted_ty.sty {
99             ty::TyFnDef(..) | ty::TyFnPtr(_) => {
100                 let adjustments = autoderef.adjust_steps(LvaluePreference::NoPreference);
101                 self.apply_adjustments(callee_expr, adjustments);
102                 return Some(CallStep::Builtin(adjusted_ty));
103             }
104
105             ty::TyClosure(def_id, substs) => {
106                 assert_eq!(def_id.krate, LOCAL_CRATE);
107
108                 // Check whether this is a call to a closure where we
109                 // haven't yet decided on whether the closure is fn vs
110                 // fnmut vs fnonce. If so, we have to defer further processing.
111                 if self.closure_kind(def_id).is_none() {
112                     let closure_ty = self.fn_sig(def_id).subst(self.tcx, substs.substs);
113                     let fn_sig = self.replace_late_bound_regions_with_fresh_var(call_expr.span,
114                                                                    infer::FnCall,
115                                                                    &closure_ty)
116                         .0;
117                     let adjustments = autoderef.adjust_steps(LvaluePreference::NoPreference);
118                     self.record_deferred_call_resolution(def_id, DeferredCallResolution {
119                         call_expr,
120                         callee_expr,
121                         adjusted_ty,
122                         adjustments,
123                         fn_sig,
124                         closure_def_id: def_id,
125                     });
126                     return Some(CallStep::DeferredClosure(fn_sig));
127                 }
128             }
129
130             // Hack: we know that there are traits implementing Fn for &F
131             // where F:Fn and so forth. In the particular case of types
132             // like `x: &mut FnMut()`, if there is a call `x()`, we would
133             // normally translate to `FnMut::call_mut(&mut x, ())`, but
134             // that winds up requiring `mut x: &mut FnMut()`. A little
135             // over the top. The simplest fix by far is to just ignore
136             // this case and deref again, so we wind up with
137             // `FnMut::call_mut(&mut *x, ())`.
138             ty::TyRef(..) if autoderef.step_count() == 0 => {
139                 return None;
140             }
141
142             _ => {}
143         }
144
145         self.try_overloaded_call_traits(call_expr, adjusted_ty).map(|(autoref, method)| {
146             let mut adjustments = autoderef.adjust_steps(LvaluePreference::NoPreference);
147             adjustments.extend(autoref);
148             self.apply_adjustments(callee_expr, adjustments);
149             CallStep::Overloaded(method)
150         })
151     }
152
153     fn try_overloaded_call_traits(&self,
154                                   call_expr: &hir::Expr,
155                                   adjusted_ty: Ty<'tcx>)
156                                   -> Option<(Option<Adjustment<'tcx>>,
157                                              MethodCallee<'tcx>)> {
158         // Try the options that are least restrictive on the caller first.
159         for &(opt_trait_def_id, method_name, borrow) in
160             &[(self.tcx.lang_items().fn_trait(), Symbol::intern("call"), true),
161               (self.tcx.lang_items().fn_mut_trait(), Symbol::intern("call_mut"), true),
162               (self.tcx.lang_items().fn_once_trait(), Symbol::intern("call_once"), false)] {
163             let trait_def_id = match opt_trait_def_id {
164                 Some(def_id) => def_id,
165                 None => continue,
166             };
167
168             match self.lookup_method_in_trait(call_expr.span,
169                                               method_name,
170                                               trait_def_id,
171                                               adjusted_ty,
172                                               None) {
173                 None => continue,
174                 Some(ok) => {
175                     let method = self.register_infer_ok_obligations(ok);
176                     let mut autoref = None;
177                     if borrow {
178                         if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
179                             autoref = Some(Adjustment {
180                                 kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
181                                 target: method.sig.inputs()[0]
182                             });
183                         }
184                     }
185                     return Some((autoref, method));
186                 }
187             }
188         }
189
190         None
191     }
192
193     fn confirm_builtin_call(&self,
194                             call_expr: &hir::Expr,
195                             callee_ty: Ty<'tcx>,
196                             arg_exprs: &'gcx [hir::Expr],
197                             expected: Expectation<'tcx>)
198                             -> Ty<'tcx> {
199         let (fn_sig, def_span) = match callee_ty.sty {
200             ty::TyFnDef(def_id, _) => {
201                 (callee_ty.fn_sig(self.tcx), self.tcx.hir.span_if_local(def_id))
202             }
203             ty::TyFnPtr(sig) => (sig, None),
204             ref t => {
205                 let mut unit_variant = None;
206                 if let &ty::TyAdt(adt_def, ..) = t {
207                     if adt_def.is_enum() {
208                         if let hir::ExprCall(ref expr, _) = call_expr.node {
209                             unit_variant = Some(self.tcx.hir.node_to_pretty_string(expr.id))
210                         }
211                     }
212                 }
213                 let mut err = type_error_struct!(self.tcx.sess, call_expr.span, callee_ty, E0618,
214                                                  "expected function, found `{}`",
215                                                  if let Some(ref path) = unit_variant {
216                                                      path.to_string()
217                                                  } else {
218                                                      callee_ty.to_string()
219                                                  });
220                 if let Some(path) = unit_variant {
221                     err.help(&format!("did you mean to write `{}`?", path));
222                 }
223
224                 if let hir::ExprCall(ref expr, _) = call_expr.node {
225                     let def = if let hir::ExprPath(ref qpath) = expr.node {
226                         self.tables.borrow().qpath_def(qpath, expr.hir_id)
227                     } else {
228                         Def::Err
229                     };
230                     if def != Def::Err {
231                         if let Some(span) = self.tcx.hir.span_if_local(def.def_id()) {
232                             err.span_note(span, "defined here");
233                         }
234                     }
235                 }
236
237                 err.emit();
238
239                 // This is the "default" function signature, used in case of error.
240                 // In that case, we check each argument against "error" in order to
241                 // set up all the node type bindings.
242                 (ty::Binder(self.tcx.mk_fn_sig(
243                     self.err_args(arg_exprs.len()).into_iter(),
244                     self.tcx.types.err,
245                     false,
246                     hir::Unsafety::Normal,
247                     abi::Abi::Rust
248                 )), None)
249             }
250         };
251
252         // Replace any late-bound regions that appear in the function
253         // signature with region variables. We also have to
254         // renormalize the associated types at this point, since they
255         // previously appeared within a `Binder<>` and hence would not
256         // have been normalized before.
257         let fn_sig =
258             self.replace_late_bound_regions_with_fresh_var(call_expr.span, infer::FnCall, &fn_sig)
259                 .0;
260         let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig);
261
262         // Call the generic checker.
263         let expected_arg_tys =
264             self.expected_inputs_for_expected_output(call_expr.span,
265                                             expected,
266                                             fn_sig.output(),
267                                             fn_sig.inputs());
268         self.check_argument_types(call_expr.span,
269                                   fn_sig.inputs(),
270                                   &expected_arg_tys[..],
271                                   arg_exprs,
272                                   fn_sig.variadic,
273                                   TupleArgumentsFlag::DontTupleArguments,
274                                   def_span);
275
276         fn_sig.output()
277     }
278
279     fn confirm_deferred_closure_call(&self,
280                                      call_expr: &hir::Expr,
281                                      arg_exprs: &'gcx [hir::Expr],
282                                      expected: Expectation<'tcx>,
283                                      fn_sig: ty::FnSig<'tcx>)
284                                      -> Ty<'tcx> {
285         // `fn_sig` is the *signature* of the cosure being called. We
286         // don't know the full details yet (`Fn` vs `FnMut` etc), but we
287         // do know the types expected for each argument and the return
288         // type.
289
290         let expected_arg_tys = self.expected_inputs_for_expected_output(call_expr.span,
291                                                                expected,
292                                                                fn_sig.output().clone(),
293                                                                fn_sig.inputs());
294
295         self.check_argument_types(call_expr.span,
296                                   fn_sig.inputs(),
297                                   &expected_arg_tys,
298                                   arg_exprs,
299                                   fn_sig.variadic,
300                                   TupleArgumentsFlag::TupleArguments,
301                                   None);
302
303         fn_sig.output()
304     }
305
306     fn confirm_overloaded_call(&self,
307                                call_expr: &hir::Expr,
308                                arg_exprs: &'gcx [hir::Expr],
309                                expected: Expectation<'tcx>,
310                                method_callee: MethodCallee<'tcx>)
311                                -> Ty<'tcx> {
312         let output_type = self.check_method_argument_types(call_expr.span,
313                                                            Ok(method_callee),
314                                                            arg_exprs,
315                                                            TupleArgumentsFlag::TupleArguments,
316                                                            expected);
317
318         self.write_method_call(call_expr.hir_id, method_callee);
319         output_type
320     }
321 }
322
323 #[derive(Debug)]
324 pub struct DeferredCallResolution<'gcx: 'tcx, 'tcx> {
325     call_expr: &'gcx hir::Expr,
326     callee_expr: &'gcx hir::Expr,
327     adjusted_ty: Ty<'tcx>,
328     adjustments: Vec<Adjustment<'tcx>>,
329     fn_sig: ty::FnSig<'tcx>,
330     closure_def_id: DefId,
331 }
332
333 impl<'a, 'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> {
334     pub fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
335         debug!("DeferredCallResolution::resolve() {:?}", self);
336
337         // we should not be invoked until the closure kind has been
338         // determined by upvar inference
339         assert!(fcx.closure_kind(self.closure_def_id).is_some());
340
341         // We may now know enough to figure out fn vs fnmut etc.
342         match fcx.try_overloaded_call_traits(self.call_expr,
343                                              self.adjusted_ty) {
344             Some((autoref, method_callee)) => {
345                 // One problem is that when we get here, we are going
346                 // to have a newly instantiated function signature
347                 // from the call trait. This has to be reconciled with
348                 // the older function signature we had before. In
349                 // principle we *should* be able to fn_sigs(), but we
350                 // can't because of the annoying need for a TypeTrace.
351                 // (This always bites me, should find a way to
352                 // refactor it.)
353                 let method_sig = method_callee.sig;
354
355                 debug!("attempt_resolution: method_callee={:?}", method_callee);
356
357                 for (method_arg_ty, self_arg_ty) in
358                     method_sig.inputs().iter().skip(1).zip(self.fn_sig.inputs()) {
359                     fcx.demand_eqtype(self.call_expr.span, &self_arg_ty, &method_arg_ty);
360                 }
361
362                 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
363
364                 let mut adjustments = self.adjustments;
365                 adjustments.extend(autoref);
366                 fcx.apply_adjustments(self.callee_expr, adjustments);
367
368                 fcx.write_method_call(self.call_expr.hir_id,
369                                       method_callee);
370             }
371             None => {
372                 span_bug!(self.call_expr.span,
373                           "failed to find an overloaded call trait for closure call");
374             }
375         }
376     }
377 }