1 use super::method
::MethodCallee
;
2 use super::{Expectation, FnCtxt, TupleArgumentsFlag}
;
3 use crate::type_error_struct
;
5 use rustc_errors
::{struct_span_err, Applicability, DiagnosticBuilder}
;
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
,
14 use rustc_middle
::ty
::subst
::SubstsRef
;
15 use rustc_middle
::ty
::{self, Ty, TyCtxt, TypeFoldable}
;
16 use rustc_span
::symbol
::{sym, Ident}
;
18 use rustc_target
::spec
::abi
;
19 use rustc_trait_selection
::autoderef
::Autoderef
;
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(
27 receiver
: Option
<Span
>,
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");
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()));
43 "consider using `drop` function",
45 Applicability
::MaybeIncorrect
,
54 DeferredClosure(ty
::FnSig
<'tcx
>),
55 /// E.g., enum variant constructors.
56 Overloaded(MethodCallee
<'tcx
>),
59 impl<'a
, 'tcx
> FnCtxt
<'a
, 'tcx
> {
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
>,
67 let original_callee_ty
= self.check_expr(callee_expr
);
68 let expr_ty
= self.structurally_resolved_type(call_expr
.span
, original_callee_ty
);
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
);
75 self.register_predicates(autoderef
.into_obligations());
77 let output
= match result
{
79 // this will report an error since original_callee_ty is not a fn
80 self.confirm_builtin_call(
89 Some(CallStep
::Builtin(callee_ty
)) => {
90 self.confirm_builtin_call(call_expr
, callee_expr
, callee_ty
, arg_exprs
, expected
)
93 Some(CallStep
::DeferredClosure(fn_sig
)) => {
94 self.confirm_deferred_closure_call(call_expr
, arg_exprs
, expected
, fn_sig
)
97 Some(CallStep
::Overloaded(method_callee
)) => {
98 self.confirm_overloaded_call(call_expr
, arg_exprs
, expected
, method_callee
)
102 // we must check that return type of called functions is WF:
103 self.register_wf_obligation(output
.into(), call_expr
.span
, traits
::MiscObligation
);
108 fn try_overloaded_call_step(
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
>> {
116 self.structurally_resolved_type(autoderef
.span(), autoderef
.final_ty(false));
118 "try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?})",
119 call_expr
, adjusted_ty
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
));
130 ty
::Closure(def_id
, substs
) => {
131 assert_eq
!(def_id
.krate
, LOCAL_CRATE
);
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(
145 let adjustments
= self.adjust_steps(autoderef
);
146 self.record_deferred_call_resolution(
148 DeferredCallResolution
{
154 closure_substs
: substs
,
157 return Some(CallStep
::DeferredClosure(closure_sig
));
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 => {
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
)
193 fn try_overloaded_call_traits(
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),
205 let trait_def_id
= match opt_trait_def_id
{
206 Some(def_id
) => def_id
,
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
,
218 let opt_input_types
= opt_input_types
.as_ref().map(AsRef
::as_ref
);
220 if let Some(ok
) = self.lookup_method_in_trait(
227 let method
= self.register_infer_ok_obligations(ok
);
228 let mut autoref
= None
;
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() {
236 span_bug
!(call_expr
.span
, "input to call/call_mut is not a ref?");
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
,
248 autoref
= Some(Adjustment
{
249 kind
: Adjust
::Borrow(AutoBorrow
::Ref(region
, mutbl
)),
250 target
: method
.sig
.inputs()[0],
253 return Some((autoref
, method
));
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(
264 err
: &mut DiagnosticBuilder
<'a
>,
266 callee_node
: &hir
::ExprKind
<'_
>,
269 let hir_id
= self.tcx
.hir().get_parent_node(hir_id
);
270 let parent_node
= self.tcx
.hir().get(hir_id
);
272 hir
::Node
::Expr(hir
::Expr { kind: hir::ExprKind::Closure(_, _, _, sp, ..), .. }
),
273 hir
::ExprKind
::Block(..),
274 ) = (parent_node
, callee_node
)
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
,
287 fn confirm_builtin_call(
289 call_expr
: &'tcx hir
::Expr
<'tcx
>,
290 callee_expr
: &'tcx hir
::Expr
<'tcx
>,
292 arg_exprs
: &'tcx
[hir
::Expr
<'tcx
>],
293 expected
: Expectation
<'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
),
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
{
304 self.tcx
.sess
.source_map().span_to_snippet(expr
.span
).ok();
309 let mut err
= type_error_struct
!(
314 "expected function, found {}",
316 Some(ref path
) => format
!("enum variant `{}`", path
),
317 None
=> format
!("`{}`", callee_ty
),
321 self.identify_bad_closure_def_and_call(
328 if let Some(ref path
) = unit_variant
{
332 "`{}` is a unit variant, you need to write it \
333 without the parenthesis",
337 Applicability
::MachineApplicable
,
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
)
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
{
354 callee_expr
.span
.shrink_to_hi(),
355 "consider using a semicolon here",
357 Applicability
::MaybeIncorrect
,
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
)
370 err
.span_label(call_expr
.span
, "call expression requires function");
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
380 .span_to_snippet(path
.span
)
382 .map(|p
| format
!("`{}` defined here returns `{}`", p
, callee_ty
)),
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
),
392 Res
::Def(kind
, def_id
) if kind
.ns() == Some(Namespace
::ValueNS
) => {
395 self.tcx
.def_path_str(def_id
),
398 _
=> Some(format
!("`{}` defined here", callee_ty
)),
402 if let Some(label
) = label
{
403 err
.span_label(span
, label
);
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.
412 ty
::Binder
::dummy(self.tcx
.mk_fn_sig(
413 self.err_args(arg_exprs
.len()).into_iter(),
416 hir
::Unsafety
::Normal
,
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.
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
);
433 // Call the generic checker.
434 let expected_arg_tys
= self.expected_inputs_for_expected_output(
440 self.check_argument_types(
444 &expected_arg_tys
[..],
447 TupleArgumentsFlag
::DontTupleArguments
,
454 fn confirm_deferred_closure_call(
456 call_expr
: &'tcx hir
::Expr
<'tcx
>,
457 arg_exprs
: &'tcx
[hir
::Expr
<'tcx
>],
458 expected
: Expectation
<'tcx
>,
459 fn_sig
: ty
::FnSig
<'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
466 let expected_arg_tys
= self.expected_inputs_for_expected_output(
473 self.check_argument_types(
480 TupleArgumentsFlag
::TupleArguments
,
487 fn confirm_overloaded_call(
489 call_expr
: &'tcx hir
::Expr
<'tcx
>,
490 arg_exprs
: &'tcx
[hir
::Expr
<'tcx
>],
491 expected
: Expectation
<'tcx
>,
492 method_callee
: MethodCallee
<'tcx
>,
494 let output_type
= self.check_method_argument_types(
499 TupleArgumentsFlag
::TupleArguments
,
503 self.write_method_call(call_expr
.hir_id
, method_callee
);
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
>,
518 impl<'a
, 'tcx
> DeferredCallResolution
<'tcx
> {
519 pub fn resolve(self, fcx
: &FnCtxt
<'a
, 'tcx
>) {
520 debug
!("DeferredCallResolution::resolve() {:?}", self);
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());
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
537 let method_sig
= method_callee
.sig
;
539 debug
!("attempt_resolution: method_callee={:?}", method_callee
);
541 for (method_arg_ty
, self_arg_ty
) in
542 method_sig
.inputs().iter().skip(1).zip(self.fn_sig
.inputs())
544 fcx
.demand_eqtype(self.call_expr
.span
, &self_arg_ty
, &method_arg_ty
);
547 fcx
.demand_eqtype(self.call_expr
.span
, method_sig
.output(), self.fn_sig
.output());
549 let mut adjustments
= self.adjustments
;
550 adjustments
.extend(autoref
);
551 fcx
.apply_adjustments(self.callee_expr
, adjustments
);
553 fcx
.write_method_call(self.call_expr
.hir_id
, method_callee
);
558 "failed to find an overloaded call trait for closure call"