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