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