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