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