1 use super::method::probe::ProbeScope;
2 use super::method::MethodCallee;
3 use super::{Expectation, FnCtxt, TupleArgumentsFlag};
4
5 use crate::type_error_struct;
6 use rustc_ast::util::parser::PREC_POSTFIX;
7 use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed, StashKey};
8 use rustc_hir as hir;
9 use rustc_hir::def::{self, CtorKind, DefKind, Namespace, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::HirId;
12 use rustc_hir_analysis::autoderef::Autoderef;
13 use rustc_infer::{
14 infer,
15 traits::{self, Obligation},
16 };
17 use rustc_infer::{
18 infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
19 traits::ObligationCause,
20 };
21 use rustc_middle::ty::adjustment::{
22 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
23 };
24 use rustc_middle::ty::SubstsRef;
25 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
26 use rustc_span::def_id::LocalDefId;
27 use rustc_span::symbol::{sym, Ident};
28 use rustc_span::Span;
29 use rustc_target::spec::abi;
30 use rustc_trait_selection::infer::InferCtxtExt as _;
31 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
32 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
33
34 use std::{iter, slice};
35
36 /// Checks that it is legal to call methods of the trait corresponding
37 /// to `trait_id` (this only cares about the trait, not the specific
38 /// method that is called).
check_legal_trait_for_method_call( tcx: TyCtxt<'_>, span: Span, receiver: Option<Span>, expr_span: Span, trait_id: DefId, )39 pub fn check_legal_trait_for_method_call(
40 tcx: TyCtxt<'_>,
41 span: Span,
42 receiver: Option<Span>,
43 expr_span: Span,
44 trait_id: DefId,
45 ) {
46 if tcx.lang_items().drop_trait() == Some(trait_id) {
47 let mut err = struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
48 err.span_label(span, "explicit destructor calls not allowed");
49
50 let (sp, suggestion) = receiver
51 .and_then(|s| tcx.sess.source_map().span_to_snippet(s).ok())
52 .filter(|snippet| !snippet.is_empty())
53 .map(|snippet| (expr_span, format!("drop({snippet})")))
54 .unwrap_or_else(|| (span, "drop".to_string()));
55
56 err.span_suggestion(
57 sp,
58 "consider using `drop` function",
59 suggestion,
60 Applicability::MaybeIncorrect,
61 );
62
63 err.emit();
64 }
65 }
66
67 #[derive(Debug)]
68 enum CallStep<'tcx> {
69 Builtin(Ty<'tcx>),
70 DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
71 /// E.g., enum variant constructors.
72 Overloaded(MethodCallee<'tcx>),
73 }
74
75 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
check_call( &self, call_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>, arg_exprs: &'tcx [hir::Expr<'tcx>], expected: Expectation<'tcx>, ) -> Ty<'tcx>76 pub fn check_call(
77 &self,
78 call_expr: &'tcx hir::Expr<'tcx>,
79 callee_expr: &'tcx hir::Expr<'tcx>,
80 arg_exprs: &'tcx [hir::Expr<'tcx>],
81 expected: Expectation<'tcx>,
82 ) -> Ty<'tcx> {
83 let original_callee_ty = match &callee_expr.kind {
84 hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
85 .check_expr_with_expectation_and_args(
86 callee_expr,
87 Expectation::NoExpectation,
88 arg_exprs,
89 ),
90 _ => self.check_expr(callee_expr),
91 };
92
93 let expr_ty = self.structurally_resolve_type(call_expr.span, original_callee_ty);
94
95 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
96 let mut result = None;
97 while result.is_none() && autoderef.next().is_some() {
98 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
99 }
100 self.register_predicates(autoderef.into_obligations());
101
102 let output = match result {
103 None => {
104 // this will report an error since original_callee_ty is not a fn
105 self.confirm_builtin_call(
106 call_expr,
107 callee_expr,
108 original_callee_ty,
109 arg_exprs,
110 expected,
111 )
112 }
113
114 Some(CallStep::Builtin(callee_ty)) => {
115 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
116 }
117
118 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
119 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
120 }
121
122 Some(CallStep::Overloaded(method_callee)) => {
123 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
124 }
125 };
126
127 // we must check that return type of called functions is WF:
128 self.register_wf_obligation(output.into(), call_expr.span, traits::WellFormed(None));
129
130 output
131 }
132
133 #[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
try_overloaded_call_step( &self, call_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>, arg_exprs: &'tcx [hir::Expr<'tcx>], autoderef: &Autoderef<'a, 'tcx>, ) -> Option<CallStep<'tcx>>134 fn try_overloaded_call_step(
135 &self,
136 call_expr: &'tcx hir::Expr<'tcx>,
137 callee_expr: &'tcx hir::Expr<'tcx>,
138 arg_exprs: &'tcx [hir::Expr<'tcx>],
139 autoderef: &Autoderef<'a, 'tcx>,
140 ) -> Option<CallStep<'tcx>> {
141 let adjusted_ty =
142 self.structurally_resolve_type(autoderef.span(), autoderef.final_ty(false));
143
144 // If the callee is a bare function or a closure, then we're all set.
145 match *adjusted_ty.kind() {
146 ty::FnDef(..) | ty::FnPtr(_) => {
147 let adjustments = self.adjust_steps(autoderef);
148 self.apply_adjustments(callee_expr, adjustments);
149 return Some(CallStep::Builtin(adjusted_ty));
150 }
151
152 ty::Closure(def_id, substs) => {
153 let def_id = def_id.expect_local();
154
155 // Check whether this is a call to a closure where we
156 // haven't yet decided on whether the closure is fn vs
157 // fnmut vs fnonce. If so, we have to defer further processing.
158 if self.closure_kind(substs).is_none() {
159 let closure_sig = substs.as_closure().sig();
160 let closure_sig = self.instantiate_binder_with_fresh_vars(
161 call_expr.span,
162 infer::FnCall,
163 closure_sig,
164 );
165 let adjustments = self.adjust_steps(autoderef);
166 self.record_deferred_call_resolution(
167 def_id,
168 DeferredCallResolution {
169 call_expr,
170 callee_expr,
171 adjusted_ty,
172 adjustments,
173 fn_sig: closure_sig,
174 closure_substs: substs,
175 },
176 );
177 return Some(CallStep::DeferredClosure(def_id, closure_sig));
178 }
179 }
180
181 // Hack: we know that there are traits implementing Fn for &F
182 // where F:Fn and so forth. In the particular case of types
183 // like `f: &mut FnMut()`, if there is a call `f()`, we would
184 // normally translate to `FnMut::call_mut(&mut f, ())`, but
185 // that winds up potentially requiring the user to mark their
186 // variable as `mut` which feels unnecessary and unexpected.
187 //
188 // fn foo(f: &mut impl FnMut()) { f() }
189 // ^ without this hack `f` would have to be declared as mutable
190 //
191 // The simplest fix by far is to just ignore this case and deref again,
192 // so we wind up with `FnMut::call_mut(&mut *f, ())`.
193 ty::Ref(..) if autoderef.step_count() == 0 => {
194 return None;
195 }
196
197 ty::Error(_) => {
198 return None;
199 }
200
201 _ => {}
202 }
203
204 // Now, we look for the implementation of a Fn trait on the object's type.
205 // We first do it with the explicit instruction to look for an impl of
206 // `Fn<Tuple>`, with the tuple `Tuple` having an arity corresponding
207 // to the number of call parameters.
208 // If that fails (or_else branch), we try again without specifying the
209 // shape of the tuple (hence the None). This allows to detect an Fn trait
210 // is implemented, and use this information for diagnostic.
211 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
212 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
213 .map(|(autoref, method)| {
214 let mut adjustments = self.adjust_steps(autoderef);
215 adjustments.extend(autoref);
216 self.apply_adjustments(callee_expr, adjustments);
217 CallStep::Overloaded(method)
218 })
219 }
220
try_overloaded_call_traits( &self, call_expr: &hir::Expr<'_>, adjusted_ty: Ty<'tcx>, opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>, ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)>221 fn try_overloaded_call_traits(
222 &self,
223 call_expr: &hir::Expr<'_>,
224 adjusted_ty: Ty<'tcx>,
225 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
226 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
227 // Try the options that are least restrictive on the caller first.
228 for (opt_trait_def_id, method_name, borrow) in [
229 (self.tcx.lang_items().fn_trait(), Ident::with_dummy_span(sym::call), true),
230 (self.tcx.lang_items().fn_mut_trait(), Ident::with_dummy_span(sym::call_mut), true),
231 (self.tcx.lang_items().fn_once_trait(), Ident::with_dummy_span(sym::call_once), false),
232 ] {
233 let Some(trait_def_id) = opt_trait_def_id else { continue };
234
235 let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
236 Ty::new_tup_from_iter(
237 self.tcx,
238 arg_exprs.iter().map(|e| {
239 self.next_ty_var(TypeVariableOrigin {
240 kind: TypeVariableOriginKind::TypeInference,
241 span: e.span,
242 })
243 }),
244 )
245 });
246
247 if let Some(ok) = self.lookup_method_in_trait(
248 self.misc(call_expr.span),
249 method_name,
250 trait_def_id,
251 adjusted_ty,
252 opt_input_type.as_ref().map(slice::from_ref),
253 ) {
254 // Check for `self` receiver on the method, otherwise we can't use this as a `Fn*` trait.
255 if !self.tcx.associated_item(ok.value.def_id).fn_has_self_parameter {
256 self.tcx.sess.delay_span_bug(
257 call_expr.span,
258 "input to overloaded call fn is not a self receiver",
259 );
260 return None;
261 }
262
263 let method = self.register_infer_ok_obligations(ok);
264 let mut autoref = None;
265 if borrow {
266 // Check for &self vs &mut self in the method signature. Since this is either
267 // the Fn or FnMut trait, it should be one of those.
268 let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind() else {
269 // The `fn`/`fn_mut` lang item is ill-formed, which should have
270 // caused an error elsewhere.
271 self.tcx
272 .sess
273 .delay_span_bug(call_expr.span, "input to call/call_mut is not a ref");
274 return None;
275 };
276
277 // For initial two-phase borrow
278 // deployment, conservatively omit
279 // overloaded function call ops.
280 let mutbl = AutoBorrowMutability::new(*mutbl, AllowTwoPhase::No);
281
282 autoref = Some(Adjustment {
283 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
284 target: method.sig.inputs()[0],
285 });
286 }
287
288 return Some((autoref, method));
289 }
290 }
291
292 None
293 }
294
295 /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
296 /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
identify_bad_closure_def_and_call( &self, err: &mut Diagnostic, hir_id: hir::HirId, callee_node: &hir::ExprKind<'_>, callee_span: Span, )297 fn identify_bad_closure_def_and_call(
298 &self,
299 err: &mut Diagnostic,
300 hir_id: hir::HirId,
301 callee_node: &hir::ExprKind<'_>,
302 callee_span: Span,
303 ) {
304 let hir = self.tcx.hir();
305 let parent_hir_id = hir.parent_id(hir_id);
306 let parent_node = hir.get(parent_hir_id);
307 if let (
308 hir::Node::Expr(hir::Expr {
309 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, body, .. }),
310 ..
311 }),
312 hir::ExprKind::Block(..),
313 ) = (parent_node, callee_node)
314 {
315 let fn_decl_span = if hir.body(body).generator_kind
316 == Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure))
317 {
318 // Actually need to unwrap one more layer of HIR to get to
319 // the _real_ closure...
320 let async_closure = hir.parent_id(parent_hir_id);
321 if let hir::Node::Expr(hir::Expr {
322 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
323 ..
324 }) = hir.get(async_closure)
325 {
326 fn_decl_span
327 } else {
328 return;
329 }
330 } else {
331 fn_decl_span
332 };
333
334 let start = fn_decl_span.shrink_to_lo();
335 let end = callee_span.shrink_to_hi();
336 err.multipart_suggestion(
337 "if you meant to create this closure and immediately call it, surround the \
338 closure with parentheses",
339 vec![(start, "(".to_string()), (end, ")".to_string())],
340 Applicability::MaybeIncorrect,
341 );
342 }
343 }
344
345 /// Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the
346 /// likely intention is to create an array containing tuples.
maybe_suggest_bad_array_definition( &self, err: &mut Diagnostic, call_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>, ) -> bool347 fn maybe_suggest_bad_array_definition(
348 &self,
349 err: &mut Diagnostic,
350 call_expr: &'tcx hir::Expr<'tcx>,
351 callee_expr: &'tcx hir::Expr<'tcx>,
352 ) -> bool {
353 let hir_id = self.tcx.hir().parent_id(call_expr.hir_id);
354 let parent_node = self.tcx.hir().get(hir_id);
355 if let (
356 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
357 hir::ExprKind::Tup(exp),
358 hir::ExprKind::Call(_, args),
359 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
360 && args.len() == exp.len()
361 {
362 let start = callee_expr.span.shrink_to_hi();
363 err.span_suggestion(
364 start,
365 "consider separating array elements with a comma",
366 ",",
367 Applicability::MaybeIncorrect,
368 );
369 return true;
370 }
371 false
372 }
373
confirm_builtin_call( &self, call_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>, callee_ty: Ty<'tcx>, arg_exprs: &'tcx [hir::Expr<'tcx>], expected: Expectation<'tcx>, ) -> Ty<'tcx>374 fn confirm_builtin_call(
375 &self,
376 call_expr: &'tcx hir::Expr<'tcx>,
377 callee_expr: &'tcx hir::Expr<'tcx>,
378 callee_ty: Ty<'tcx>,
379 arg_exprs: &'tcx [hir::Expr<'tcx>],
380 expected: Expectation<'tcx>,
381 ) -> Ty<'tcx> {
382 let (fn_sig, def_id) = match *callee_ty.kind() {
383 ty::FnDef(def_id, substs) => {
384 self.enforce_context_effects(call_expr.hir_id, call_expr.span, def_id, substs);
385 let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs);
386
387 // Unit testing: function items annotated with
388 // `#[rustc_evaluate_where_clauses]` trigger special output
389 // to let us test the trait evaluation system.
390 if self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses) {
391 let predicates = self.tcx.predicates_of(def_id);
392 let predicates = predicates.instantiate(self.tcx, substs);
393 for (predicate, predicate_span) in predicates {
394 let obligation = Obligation::new(
395 self.tcx,
396 ObligationCause::dummy_with_span(callee_expr.span),
397 self.param_env,
398 predicate,
399 );
400 let result = self.evaluate_obligation(&obligation);
401 self.tcx
402 .sess
403 .struct_span_err(
404 callee_expr.span,
405 format!("evaluate({:?}) = {:?}", predicate, result),
406 )
407 .span_label(predicate_span, "predicate")
408 .emit();
409 }
410 }
411 (fn_sig, Some(def_id))
412 }
413 // FIXME(effects): these arms should error because we can't enforce them
414 ty::FnPtr(sig) => (sig, None),
415 _ => {
416 for arg in arg_exprs {
417 self.check_expr(arg);
418 }
419
420 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
421 && let [segment] = path.segments
422 && let Some(mut diag) = self
423 .tcx
424 .sess
425 .diagnostic()
426 .steal_diagnostic(segment.ident.span, StashKey::CallIntoMethod)
427 {
428 // Try suggesting `foo(a)` -> `a.foo()` if possible.
429 self.suggest_call_as_method(
430 &mut diag,
431 segment,
432 arg_exprs,
433 call_expr,
434 expected
435 );
436 diag.emit();
437 }
438
439 let err = self.report_invalid_callee(call_expr, callee_expr, callee_ty, arg_exprs);
440
441 return Ty::new_error(self.tcx, err);
442 }
443 };
444
445 // Replace any late-bound regions that appear in the function
446 // signature with region variables. We also have to
447 // renormalize the associated types at this point, since they
448 // previously appeared within a `Binder<>` and hence would not
449 // have been normalized before.
450 let fn_sig = self.instantiate_binder_with_fresh_vars(call_expr.span, infer::FnCall, fn_sig);
451 let fn_sig = self.normalize(call_expr.span, fn_sig);
452
453 // Call the generic checker.
454 let expected_arg_tys = self.expected_inputs_for_expected_output(
455 call_expr.span,
456 expected,
457 fn_sig.output(),
458 fn_sig.inputs(),
459 );
460 self.check_argument_types(
461 call_expr.span,
462 call_expr,
463 fn_sig.inputs(),
464 expected_arg_tys,
465 arg_exprs,
466 fn_sig.c_variadic,
467 TupleArgumentsFlag::DontTupleArguments,
468 def_id,
469 );
470
471 if fn_sig.abi == abi::Abi::RustCall {
472 let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
473 if let Some(ty) = fn_sig.inputs().last().copied() {
474 self.register_bound(
475 ty,
476 self.tcx.require_lang_item(hir::LangItem::Tuple, Some(sp)),
477 traits::ObligationCause::new(sp, self.body_id, traits::RustCall),
478 );
479 self.require_type_is_sized(ty, sp, traits::RustCall);
480 } else {
481 self.tcx.sess.span_err(
482 sp,
483 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
484 );
485 }
486 }
487
488 fn_sig.output()
489 }
490
491 /// Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)`
492 /// and suggesting the fix if the method probe is successful.
suggest_call_as_method( &self, diag: &mut Diagnostic, segment: &'tcx hir::PathSegment<'tcx>, arg_exprs: &'tcx [hir::Expr<'tcx>], call_expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>, )493 fn suggest_call_as_method(
494 &self,
495 diag: &mut Diagnostic,
496 segment: &'tcx hir::PathSegment<'tcx>,
497 arg_exprs: &'tcx [hir::Expr<'tcx>],
498 call_expr: &'tcx hir::Expr<'tcx>,
499 expected: Expectation<'tcx>,
500 ) {
501 if let [callee_expr, rest @ ..] = arg_exprs {
502 let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr) else {
503 return;
504 };
505
506 // First, do a probe with `IsSuggestion(true)` to avoid emitting
507 // any strange errors. If it's successful, then we'll do a true
508 // method lookup.
509 let Ok(pick) = self
510 .lookup_probe_for_diagnostic(
511 segment.ident,
512 callee_ty,
513 call_expr,
514 // We didn't record the in scope traits during late resolution
515 // so we need to probe AllTraits unfortunately
516 ProbeScope::AllTraits,
517 expected.only_has_type(self),
518 ) else {
519 return;
520 };
521
522 let pick = self.confirm_method(
523 call_expr.span,
524 callee_expr,
525 call_expr,
526 callee_ty,
527 &pick,
528 segment,
529 );
530 if pick.illegal_sized_bound.is_some() {
531 return;
532 }
533
534 let up_to_rcvr_span = segment.ident.span.until(callee_expr.span);
535 let rest_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
536 let rest_snippet = if let Some(first) = rest.first() {
537 self.tcx
538 .sess
539 .source_map()
540 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
541 } else {
542 Ok(")".to_string())
543 };
544
545 if let Ok(rest_snippet) = rest_snippet {
546 let sugg = if callee_expr.precedence().order() >= PREC_POSTFIX {
547 vec![
548 (up_to_rcvr_span, "".to_string()),
549 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
550 ]
551 } else {
552 vec![
553 (up_to_rcvr_span, "(".to_string()),
554 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
555 ]
556 };
557 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
558 diag.multipart_suggestion(
559 format!(
560 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
561 self.tcx
562 .associated_item(pick.callee.def_id)
563 .trait_container(self.tcx)
564 .map_or_else(
565 || String::new(),
566 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
567 ),
568 segment.ident
569 ),
570 sugg,
571 Applicability::MaybeIncorrect,
572 );
573 }
574 }
575 }
576
report_invalid_callee( &self, call_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>, callee_ty: Ty<'tcx>, arg_exprs: &'tcx [hir::Expr<'tcx>], ) -> ErrorGuaranteed577 fn report_invalid_callee(
578 &self,
579 call_expr: &'tcx hir::Expr<'tcx>,
580 callee_expr: &'tcx hir::Expr<'tcx>,
581 callee_ty: Ty<'tcx>,
582 arg_exprs: &'tcx [hir::Expr<'tcx>],
583 ) -> ErrorGuaranteed {
584 let mut unit_variant = None;
585 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
586 && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
587 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
588 // Only suggest removing parens if there are no arguments
589 && arg_exprs.is_empty()
590 {
591 let descr = match kind {
592 def::CtorOf::Struct => "struct",
593 def::CtorOf::Variant => "enum variant",
594 };
595 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
596 unit_variant = Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(qpath)));
597 }
598
599 let callee_ty = self.resolve_vars_if_possible(callee_ty);
600 let mut err = type_error_struct!(
601 self.tcx.sess,
602 callee_expr.span,
603 callee_ty,
604 E0618,
605 "expected function, found {}",
606 match &unit_variant {
607 Some((_, kind, path)) => format!("{kind} `{path}`"),
608 None => format!("`{callee_ty}`"),
609 }
610 );
611
612 self.identify_bad_closure_def_and_call(
613 &mut err,
614 call_expr.hir_id,
615 &callee_expr.kind,
616 callee_expr.span,
617 );
618
619 if let Some((removal_span, kind, path)) = &unit_variant {
620 err.span_suggestion_verbose(
621 *removal_span,
622 format!(
623 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
624 ),
625 "",
626 Applicability::MachineApplicable,
627 );
628 }
629
630 let mut inner_callee_path = None;
631 let def = match callee_expr.kind {
632 hir::ExprKind::Path(ref qpath) => {
633 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
634 }
635 hir::ExprKind::Call(ref inner_callee, _) => {
636 // If the call spans more than one line and the callee kind is
637 // itself another `ExprCall`, that's a clue that we might just be
638 // missing a semicolon (Issue #51055)
639 let call_is_multiline = self.tcx.sess.source_map().is_multiline(call_expr.span);
640 if call_is_multiline {
641 err.span_suggestion(
642 callee_expr.span.shrink_to_hi(),
643 "consider using a semicolon here",
644 ";",
645 Applicability::MaybeIncorrect,
646 );
647 }
648 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
649 inner_callee_path = Some(inner_qpath);
650 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
651 } else {
652 Res::Err
653 }
654 }
655 _ => Res::Err,
656 };
657
658 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
659 if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
660 && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
661 {
662 let descr = match maybe_def {
663 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
664 DefIdOrName::Name(name) => name,
665 };
666 err.span_label(
667 callee_expr.span,
668 format!("this {descr} returns an unsized value `{output_ty}`, so it cannot be called")
669 );
670 if let DefIdOrName::DefId(def_id) = maybe_def
671 && let Some(def_span) = self.tcx.hir().span_if_local(def_id)
672 {
673 err.span_label(def_span, "the callable type is defined here");
674 }
675 } else {
676 err.span_label(call_expr.span, "call expression requires function");
677 }
678 }
679
680 if let Some(span) = self.tcx.hir().res_span(def) {
681 let callee_ty = callee_ty.to_string();
682 let label = match (unit_variant, inner_callee_path) {
683 (Some((_, kind, path)), _) => Some(format!("{kind} `{path}` defined here")),
684 (_, Some(hir::QPath::Resolved(_, path))) => self
685 .tcx
686 .sess
687 .source_map()
688 .span_to_snippet(path.span)
689 .ok()
690 .map(|p| format!("`{p}` defined here returns `{callee_ty}`")),
691 _ => {
692 match def {
693 // Emit a different diagnostic for local variables, as they are not
694 // type definitions themselves, but rather variables *of* that type.
695 Res::Local(hir_id) => Some(format!(
696 "`{}` has type `{}`",
697 self.tcx.hir().name(hir_id),
698 callee_ty
699 )),
700 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
701 Some(format!("`{}` defined here", self.tcx.def_path_str(def_id),))
702 }
703 _ => Some(format!("`{callee_ty}` defined here")),
704 }
705 }
706 };
707 if let Some(label) = label {
708 err.span_label(span, label);
709 }
710 }
711 err.emit()
712 }
713
confirm_deferred_closure_call( &self, call_expr: &'tcx hir::Expr<'tcx>, arg_exprs: &'tcx [hir::Expr<'tcx>], expected: Expectation<'tcx>, closure_def_id: LocalDefId, fn_sig: ty::FnSig<'tcx>, ) -> Ty<'tcx>714 fn confirm_deferred_closure_call(
715 &self,
716 call_expr: &'tcx hir::Expr<'tcx>,
717 arg_exprs: &'tcx [hir::Expr<'tcx>],
718 expected: Expectation<'tcx>,
719 closure_def_id: LocalDefId,
720 fn_sig: ty::FnSig<'tcx>,
721 ) -> Ty<'tcx> {
722 // `fn_sig` is the *signature* of the closure being called. We
723 // don't know the full details yet (`Fn` vs `FnMut` etc), but we
724 // do know the types expected for each argument and the return
725 // type.
726
727 let expected_arg_tys = self.expected_inputs_for_expected_output(
728 call_expr.span,
729 expected,
730 fn_sig.output(),
731 fn_sig.inputs(),
732 );
733
734 self.check_argument_types(
735 call_expr.span,
736 call_expr,
737 fn_sig.inputs(),
738 expected_arg_tys,
739 arg_exprs,
740 fn_sig.c_variadic,
741 TupleArgumentsFlag::TupleArguments,
742 Some(closure_def_id.to_def_id()),
743 );
744
745 fn_sig.output()
746 }
747
748 #[tracing::instrument(level = "debug", skip(self, span))]
enforce_context_effects( &self, call_expr_hir: HirId, span: Span, callee_did: DefId, callee_substs: SubstsRef<'tcx>, )749 pub(super) fn enforce_context_effects(
750 &self,
751 call_expr_hir: HirId,
752 span: Span,
753 callee_did: DefId,
754 callee_substs: SubstsRef<'tcx>,
755 ) {
756 let tcx = self.tcx;
757
758 if !tcx.features().effects || tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you {
759 return;
760 }
761
762 // Compute the constness required by the context.
763 let context = tcx.hir().enclosing_body_owner(call_expr_hir);
764 let const_context = tcx.hir().body_const_context(context);
765
766 let kind = tcx.def_kind(context.to_def_id());
767 debug_assert_ne!(kind, DefKind::ConstParam);
768
769 if tcx.has_attr(context.to_def_id(), sym::rustc_do_not_const_check) {
770 trace!("do not const check this context");
771 return;
772 }
773
774 let effect = match const_context {
775 Some(hir::ConstContext::Static(_) | hir::ConstContext::Const) => tcx.consts.false_,
776 Some(hir::ConstContext::ConstFn) => {
777 let substs = ty::InternalSubsts::identity_for_item(tcx, context);
778 substs.host_effect_param().expect("ConstContext::Maybe must have host effect param")
779 }
780 None => tcx.consts.true_,
781 };
782
783 let generics = tcx.generics_of(callee_did);
784
785 trace!(?effect, ?generics, ?callee_substs);
786
787 if let Some(idx) = generics.host_effect_index {
788 let param = callee_substs.const_at(idx);
789 let cause = self.misc(span);
790 match self.at(&cause, self.param_env).eq(infer::DefineOpaqueTypes::No, effect, param) {
791 Ok(infer::InferOk { obligations, value: () }) => {
792 self.register_predicates(obligations);
793 }
794 Err(e) => {
795 // FIXME(effects): better diagnostic
796 self.err_ctxt().report_mismatched_consts(&cause, effect, param, e).emit();
797 }
798 }
799 }
800 }
801
confirm_overloaded_call( &self, call_expr: &'tcx hir::Expr<'tcx>, arg_exprs: &'tcx [hir::Expr<'tcx>], expected: Expectation<'tcx>, method_callee: MethodCallee<'tcx>, ) -> Ty<'tcx>802 fn confirm_overloaded_call(
803 &self,
804 call_expr: &'tcx hir::Expr<'tcx>,
805 arg_exprs: &'tcx [hir::Expr<'tcx>],
806 expected: Expectation<'tcx>,
807 method_callee: MethodCallee<'tcx>,
808 ) -> Ty<'tcx> {
809 let output_type = self.check_method_argument_types(
810 call_expr.span,
811 call_expr,
812 Ok(method_callee),
813 arg_exprs,
814 TupleArgumentsFlag::TupleArguments,
815 expected,
816 );
817
818 self.write_method_call(call_expr.hir_id, method_callee);
819 output_type
820 }
821 }
822
823 #[derive(Debug)]
824 pub struct DeferredCallResolution<'tcx> {
825 call_expr: &'tcx hir::Expr<'tcx>,
826 callee_expr: &'tcx hir::Expr<'tcx>,
827 adjusted_ty: Ty<'tcx>,
828 adjustments: Vec<Adjustment<'tcx>>,
829 fn_sig: ty::FnSig<'tcx>,
830 closure_substs: SubstsRef<'tcx>,
831 }
832
833 impl<'a, 'tcx> DeferredCallResolution<'tcx> {
resolve(self, fcx: &FnCtxt<'a, 'tcx>)834 pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
835 debug!("DeferredCallResolution::resolve() {:?}", self);
836
837 // we should not be invoked until the closure kind has been
838 // determined by upvar inference
839 assert!(fcx.closure_kind(self.closure_substs).is_some());
840
841 // We may now know enough to figure out fn vs fnmut etc.
842 match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) {
843 Some((autoref, method_callee)) => {
844 // One problem is that when we get here, we are going
845 // to have a newly instantiated function signature
846 // from the call trait. This has to be reconciled with
847 // the older function signature we had before. In
848 // principle we *should* be able to fn_sigs(), but we
849 // can't because of the annoying need for a TypeTrace.
850 // (This always bites me, should find a way to
851 // refactor it.)
852 let method_sig = method_callee.sig;
853
854 debug!("attempt_resolution: method_callee={:?}", method_callee);
855
856 for (method_arg_ty, self_arg_ty) in
857 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
858 {
859 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
860 }
861
862 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
863
864 let mut adjustments = self.adjustments;
865 adjustments.extend(autoref);
866 fcx.apply_adjustments(self.callee_expr, adjustments);
867
868 fcx.write_method_call(self.call_expr.hir_id, method_callee);
869 }
870 None => {
871 // This can happen if `#![no_core]` is used and the `fn/fn_mut/fn_once`
872 // lang items are not defined (issue #86238).
873 let mut err = fcx.inh.tcx.sess.struct_span_err(
874 self.call_expr.span,
875 "failed to find an overloaded call trait for closure call",
876 );
877 err.help(
878 "make sure the `fn`/`fn_mut`/`fn_once` lang items are defined \
879 and have correctly defined `call`/`call_mut`/`call_once` methods",
880 );
881 err.emit();
882 }
883 }
884 }
885 }
886