1use std::iter;
2
3use rustc_abi::{CanonAbi, ExternAbi};
4use rustc_ast::util::parser::ExprPrecedence;
5use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey};
6use rustc_hir::def::{self, CtorKind, Namespace, Res};
7use rustc_hir::def_id::DefId;
8use rustc_hir::{self as hir, HirId, LangItem};
9use rustc_hir_analysis::autoderef::Autoderef;
10use rustc_infer::infer::BoundRegionConversionTime;
11use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode};
12use rustc_middle::ty::adjustment::{
13 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
14};
15use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt};
16use rustc_middle::{bug, span_bug};
17use rustc_span::def_id::LocalDefId;
18use rustc_span::{Span, sym};
19use rustc_target::spec::{AbiMap, AbiMapping};
20use rustc_trait_selection::error_reporting::traits::DefIdOrName;
21use rustc_trait_selection::infer::InferCtxtExt as _;
22use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
23use tracing::{debug, instrument};
24
25use super::method::MethodCallee;
26use super::method::probe::ProbeScope;
27use super::{Expectation, FnCtxt, TupleArgumentsFlag};
28use crate::{errors, fluent_generated};
29
30pub(crate) fn check_legal_trait_for_method_call(
34 tcx: TyCtxt<'_>,
35 span: Span,
36 receiver: Option<Span>,
37 expr_span: Span,
38 trait_id: DefId,
39 _body_id: DefId,
40) -> Result<(), ErrorGuaranteed> {
41 if tcx.is_lang_item(trait_id, LangItem::Drop) {
42 let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
43 errors::ExplicitDestructorCallSugg::Snippet {
44 lo: expr_span.shrink_to_lo(),
45 hi: receiver.shrink_to_hi().to(expr_span.shrink_to_hi()),
46 }
47 } else {
48 errors::ExplicitDestructorCallSugg::Empty(span)
49 };
50 return Err(tcx.dcx().emit_err(errors::ExplicitDestructorCall { span, sugg }));
51 }
52 tcx.ensure_ok().coherent_trait(trait_id)
53}
54
55#[derive(Debug)]
56enum CallStep<'tcx> {
57 Builtin(Ty<'tcx>),
58 DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
59 Overloaded(MethodCallee<'tcx>),
61}
62
63impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
64 pub(crate) fn check_expr_call(
65 &self,
66 call_expr: &'tcx hir::Expr<'tcx>,
67 callee_expr: &'tcx hir::Expr<'tcx>,
68 arg_exprs: &'tcx [hir::Expr<'tcx>],
69 expected: Expectation<'tcx>,
70 ) -> Ty<'tcx> {
71 let original_callee_ty = match &callee_expr.kind {
72 hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
73 .check_expr_with_expectation_and_args(
74 callee_expr,
75 Expectation::NoExpectation,
76 Some((call_expr, arg_exprs)),
77 ),
78 _ => self.check_expr(callee_expr),
79 };
80
81 let expr_ty = self.structurally_resolve_type(call_expr.span, original_callee_ty);
82
83 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
84 let mut result = None;
85 while result.is_none() && autoderef.next().is_some() {
86 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
87 }
88
89 match autoderef.final_ty(false).kind() {
90 ty::FnDef(def_id, _) => {
91 let abi = self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi;
92 self.check_call_abi(abi, call_expr.span);
93 }
94 ty::FnPtr(_, header) => {
95 self.check_call_abi(header.abi, call_expr.span);
96 }
97 _ => { }
98 }
99
100 self.register_predicates(autoderef.into_obligations());
101
102 let output = match result {
103 None => {
104 for arg in arg_exprs {
107 self.check_expr(arg);
108 }
109
110 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
111 && let [segment] = path.segments
112 {
113 self.dcx().try_steal_modify_and_emit_err(
114 segment.ident.span,
115 StashKey::CallIntoMethod,
116 |err| {
117 self.suggest_call_as_method(
119 err, segment, arg_exprs, call_expr, expected,
120 );
121 },
122 );
123 }
124
125 let guar = self.report_invalid_callee(call_expr, callee_expr, expr_ty, arg_exprs);
126 Ty::new_error(self.tcx, guar)
127 }
128
129 Some(CallStep::Builtin(callee_ty)) => {
130 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
131 }
132
133 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
134 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
135 }
136
137 Some(CallStep::Overloaded(method_callee)) => {
138 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
139 }
140 };
141
142 self.register_wf_obligation(
144 output.into(),
145 call_expr.span,
146 ObligationCauseCode::WellFormed(None),
147 );
148
149 output
150 }
151
152 pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span) {
157 let canon_abi = match AbiMap::from_target(&self.sess().target).canonize_abi(abi, false) {
158 AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => canon_abi,
159 AbiMapping::Invalid => {
160 let guar = self.dcx().span_delayed_bug(
163 span,
164 format!("invalid abi for platform should have reported an error: {abi}"),
165 );
166 self.set_tainted_by_errors(guar);
167 return;
168 }
169 };
170
171 let valid = match canon_abi {
172 CanonAbi::Custom => false,
174
175 CanonAbi::GpuKernel => false,
177
178 CanonAbi::Interrupt(_) => false,
181
182 CanonAbi::C
183 | CanonAbi::Rust
184 | CanonAbi::RustCold
185 | CanonAbi::Arm(_)
186 | CanonAbi::X86(_) => true,
187 };
188
189 if !valid {
190 let err = crate::errors::AbiCannotBeCalled { span, abi };
191 self.tcx.dcx().emit_err(err);
192 }
193 }
194
195 #[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
196 fn try_overloaded_call_step(
197 &self,
198 call_expr: &'tcx hir::Expr<'tcx>,
199 callee_expr: &'tcx hir::Expr<'tcx>,
200 arg_exprs: &'tcx [hir::Expr<'tcx>],
201 autoderef: &Autoderef<'a, 'tcx>,
202 ) -> Option<CallStep<'tcx>> {
203 let adjusted_ty =
204 self.structurally_resolve_type(autoderef.span(), autoderef.final_ty(false));
205
206 match *adjusted_ty.kind() {
208 ty::FnDef(..) | ty::FnPtr(..) => {
209 let adjustments = self.adjust_steps(autoderef);
210 self.apply_adjustments(callee_expr, adjustments);
211 return Some(CallStep::Builtin(adjusted_ty));
212 }
213
214 ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
218 let def_id = def_id.expect_local();
219 let closure_sig = args.as_closure().sig();
220 let closure_sig = self.instantiate_binder_with_fresh_vars(
221 call_expr.span,
222 BoundRegionConversionTime::FnCall,
223 closure_sig,
224 );
225 let adjustments = self.adjust_steps(autoderef);
226 self.record_deferred_call_resolution(
227 def_id,
228 DeferredCallResolution {
229 call_expr,
230 callee_expr,
231 closure_ty: adjusted_ty,
232 adjustments,
233 fn_sig: closure_sig,
234 },
235 );
236 return Some(CallStep::DeferredClosure(def_id, closure_sig));
237 }
238
239 ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
245 let def_id = def_id.expect_local();
246 let closure_args = args.as_coroutine_closure();
247 let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
248 call_expr.span,
249 BoundRegionConversionTime::FnCall,
250 closure_args.coroutine_closure_sig(),
251 );
252 let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
253 let kind_ty = self.next_ty_var(callee_expr.span);
258 let call_sig = self.tcx.mk_fn_sig(
259 [coroutine_closure_sig.tupled_inputs_ty],
260 coroutine_closure_sig.to_coroutine(
261 self.tcx,
262 closure_args.parent_args(),
263 kind_ty,
264 self.tcx.coroutine_for_closure(def_id),
265 tupled_upvars_ty,
266 ),
267 coroutine_closure_sig.c_variadic,
268 coroutine_closure_sig.safety,
269 coroutine_closure_sig.abi,
270 );
271 let adjustments = self.adjust_steps(autoderef);
272 self.record_deferred_call_resolution(
273 def_id,
274 DeferredCallResolution {
275 call_expr,
276 callee_expr,
277 closure_ty: adjusted_ty,
278 adjustments,
279 fn_sig: call_sig,
280 },
281 );
282 return Some(CallStep::DeferredClosure(def_id, call_sig));
283 }
284
285 ty::Ref(..) if autoderef.step_count() == 0 => {
298 return None;
299 }
300
301 ty::Error(_) => {
302 return None;
303 }
304
305 _ => {}
306 }
307
308 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
316 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
317 .map(|(autoref, method)| {
318 let mut adjustments = self.adjust_steps(autoderef);
319 adjustments.extend(autoref);
320 self.apply_adjustments(callee_expr, adjustments);
321 CallStep::Overloaded(method)
322 })
323 }
324
325 fn try_overloaded_call_traits(
326 &self,
327 call_expr: &hir::Expr<'_>,
328 adjusted_ty: Ty<'tcx>,
329 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
330 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
331 let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
344 [
345 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
346 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
347 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
348 (self.tcx.lang_items().fn_trait(), sym::call, true),
349 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
350 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
351 ]
352 } else {
353 [
354 (self.tcx.lang_items().fn_trait(), sym::call, true),
355 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
356 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
357 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
358 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
359 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
360 ]
361 };
362
363 for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
365 let Some(trait_def_id) = opt_trait_def_id else { continue };
366
367 let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
368 Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
369 });
370
371 if let Some(ok) = self.lookup_method_for_operator(
372 self.misc(call_expr.span),
373 method_name,
374 trait_def_id,
375 adjusted_ty,
376 opt_input_type,
377 ) {
378 let method = self.register_infer_ok_obligations(ok);
379 let mut autoref = None;
380 if borrow {
381 let ty::Ref(_, _, mutbl) = method.sig.inputs()[0].kind() else {
384 bug!("Expected `FnMut`/`Fn` to take receiver by-ref/by-mut")
385 };
386
387 let mutbl = AutoBorrowMutability::new(*mutbl, AllowTwoPhase::No);
391
392 autoref = Some(Adjustment {
393 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
394 target: method.sig.inputs()[0],
395 });
396 }
397
398 return Some((autoref, method));
399 }
400 }
401
402 None
403 }
404
405 fn identify_bad_closure_def_and_call(
408 &self,
409 err: &mut Diag<'_>,
410 hir_id: hir::HirId,
411 callee_node: &hir::ExprKind<'_>,
412 callee_span: Span,
413 ) {
414 let hir::ExprKind::Block(..) = callee_node else {
415 return;
417 };
418
419 let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
420 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
421 ..
422 }) = self.tcx.parent_hir_node(hir_id)
423 {
424 fn_decl_span
425 } else if let Some((
426 _,
427 hir::Node::Expr(&hir::Expr {
428 hir_id: parent_hir_id,
429 kind:
430 hir::ExprKind::Closure(&hir::Closure {
431 kind:
432 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
433 hir::CoroutineDesugaring::Async,
434 hir::CoroutineSource::Closure,
435 )),
436 ..
437 }),
438 ..
439 }),
440 )) = self.tcx.hir_parent_iter(hir_id).nth(3)
441 {
442 if let hir::Node::Expr(&hir::Expr {
445 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
446 ..
447 }) = self.tcx.parent_hir_node(parent_hir_id)
448 {
449 fn_decl_span
450 } else {
451 return;
452 }
453 } else {
454 return;
455 };
456
457 let start = fn_decl_span.shrink_to_lo();
458 let end = callee_span.shrink_to_hi();
459 err.multipart_suggestion(
460 "if you meant to create this closure and immediately call it, surround the \
461 closure with parentheses",
462 vec![(start, "(".to_string()), (end, ")".to_string())],
463 Applicability::MaybeIncorrect,
464 );
465 }
466
467 fn maybe_suggest_bad_array_definition(
470 &self,
471 err: &mut Diag<'_>,
472 call_expr: &'tcx hir::Expr<'tcx>,
473 callee_expr: &'tcx hir::Expr<'tcx>,
474 ) -> bool {
475 let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
476 if let (
477 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
478 hir::ExprKind::Tup(exp),
479 hir::ExprKind::Call(_, args),
480 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
481 && args.len() == exp.len()
482 {
483 let start = callee_expr.span.shrink_to_hi();
484 err.span_suggestion(
485 start,
486 "consider separating array elements with a comma",
487 ",",
488 Applicability::MaybeIncorrect,
489 );
490 return true;
491 }
492 false
493 }
494
495 fn confirm_builtin_call(
496 &self,
497 call_expr: &'tcx hir::Expr<'tcx>,
498 callee_expr: &'tcx hir::Expr<'tcx>,
499 callee_ty: Ty<'tcx>,
500 arg_exprs: &'tcx [hir::Expr<'tcx>],
501 expected: Expectation<'tcx>,
502 ) -> Ty<'tcx> {
503 let (fn_sig, def_id) = match *callee_ty.kind() {
504 ty::FnDef(def_id, args) => {
505 self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
506 let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args);
507
508 #[allow(rustc::untranslatable_diagnostic)]
513 #[allow(rustc::diagnostic_outside_of_impl)]
514 if self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses) {
515 let predicates = self.tcx.predicates_of(def_id);
516 let predicates = predicates.instantiate(self.tcx, args);
517 for (predicate, predicate_span) in predicates {
518 let obligation = Obligation::new(
519 self.tcx,
520 ObligationCause::dummy_with_span(callee_expr.span),
521 self.param_env,
522 predicate,
523 );
524 let result = self.evaluate_obligation(&obligation);
525 self.dcx()
526 .struct_span_err(
527 callee_expr.span,
528 format!("evaluate({predicate:?}) = {result:?}"),
529 )
530 .with_span_label(predicate_span, "predicate")
531 .emit();
532 }
533 }
534 (fn_sig, Some(def_id))
535 }
536
537 ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None),
539
540 _ => unreachable!(),
541 };
542
543 let fn_sig = self.instantiate_binder_with_fresh_vars(
549 call_expr.span,
550 BoundRegionConversionTime::FnCall,
551 fn_sig,
552 );
553 let fn_sig = self.normalize(call_expr.span, fn_sig);
554
555 self.check_argument_types(
556 call_expr.span,
557 call_expr,
558 fn_sig.inputs(),
559 fn_sig.output(),
560 expected,
561 arg_exprs,
562 fn_sig.c_variadic,
563 TupleArgumentsFlag::DontTupleArguments,
564 def_id,
565 );
566
567 if fn_sig.abi == rustc_abi::ExternAbi::RustCall {
568 let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
569 if let Some(ty) = fn_sig.inputs().last().copied() {
570 self.register_bound(
571 ty,
572 self.tcx.require_lang_item(hir::LangItem::Tuple, sp),
573 self.cause(sp, ObligationCauseCode::RustCall),
574 );
575 self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
576 } else {
577 self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
578 }
579 }
580
581 if let Some(def_id) = def_id
582 && self.tcx.def_kind(def_id) == hir::def::DefKind::Fn
583 && self.tcx.is_intrinsic(def_id, sym::const_eval_select)
584 {
585 let fn_sig = self.resolve_vars_if_possible(fn_sig);
586 for idx in 0..=1 {
587 let arg_ty = fn_sig.inputs()[idx + 1];
588 let span = arg_exprs.get(idx + 1).map_or(call_expr.span, |arg| arg.span);
589 if let ty::FnDef(def_id, _args) = *arg_ty.kind() {
595 if idx == 0 && !self.tcx.is_const_fn(def_id) {
596 self.dcx().emit_err(errors::ConstSelectMustBeConst { span });
597 }
598 } else {
599 self.dcx().emit_err(errors::ConstSelectMustBeFn { span, ty: arg_ty });
600 }
601 }
602 }
603
604 fn_sig.output()
605 }
606
607 fn suggest_call_as_method(
610 &self,
611 diag: &mut Diag<'_>,
612 segment: &'tcx hir::PathSegment<'tcx>,
613 arg_exprs: &'tcx [hir::Expr<'tcx>],
614 call_expr: &'tcx hir::Expr<'tcx>,
615 expected: Expectation<'tcx>,
616 ) {
617 if let [callee_expr, rest @ ..] = arg_exprs {
618 let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
619 else {
620 return;
621 };
622
623 let Ok(pick) = self.lookup_probe_for_diagnostic(
627 segment.ident,
628 callee_ty,
629 call_expr,
630 ProbeScope::AllTraits,
633 expected.only_has_type(self),
634 ) else {
635 return;
636 };
637
638 let pick = self.confirm_method_for_diagnostic(
639 call_expr.span,
640 callee_expr,
641 call_expr,
642 callee_ty,
643 &pick,
644 segment,
645 );
646 if pick.illegal_sized_bound.is_some() {
647 return;
648 }
649
650 let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
651 else {
652 return;
653 };
654 let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
655 let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
656 let rest_snippet = if let Some(first) = rest.first() {
657 self.tcx
658 .sess
659 .source_map()
660 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
661 } else {
662 Ok(")".to_string())
663 };
664
665 if let Ok(rest_snippet) = rest_snippet {
666 let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
667 vec![
668 (up_to_rcvr_span, "".to_string()),
669 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
670 ]
671 } else {
672 vec![
673 (up_to_rcvr_span, "(".to_string()),
674 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
675 ]
676 };
677 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
678 diag.multipart_suggestion(
679 format!(
680 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
681 self.tcx
682 .associated_item(pick.callee.def_id)
683 .trait_container(self.tcx)
684 .map_or_else(
685 || String::new(),
686 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
687 ),
688 segment.ident
689 ),
690 sugg,
691 Applicability::MaybeIncorrect,
692 );
693 }
694 }
695 }
696
697 fn report_invalid_callee(
698 &self,
699 call_expr: &'tcx hir::Expr<'tcx>,
700 callee_expr: &'tcx hir::Expr<'tcx>,
701 callee_ty: Ty<'tcx>,
702 arg_exprs: &'tcx [hir::Expr<'tcx>],
703 ) -> ErrorGuaranteed {
704 if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
707 && let Err(err) = args.error_reported()
708 {
709 return err;
710 }
711
712 let mut unit_variant = None;
713 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
714 && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
715 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
716 && arg_exprs.is_empty()
718 && call_expr.span.contains(callee_expr.span)
719 {
720 let descr = match kind {
721 def::CtorOf::Struct => "struct",
722 def::CtorOf::Variant => "enum variant",
723 };
724 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
725 unit_variant =
726 Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
727 }
728
729 let callee_ty = self.resolve_vars_if_possible(callee_ty);
730 let mut path = None;
731 let mut err = self.dcx().create_err(errors::InvalidCallee {
732 span: callee_expr.span,
733 ty: callee_ty,
734 found: match &unit_variant {
735 Some((_, kind, path)) => format!("{kind} `{path}`"),
736 None => format!("`{}`", self.tcx.short_string(callee_ty, &mut path)),
737 },
738 });
739 *err.long_ty_path() = path;
740 if callee_ty.references_error() {
741 err.downgrade_to_delayed_bug();
742 }
743
744 self.identify_bad_closure_def_and_call(
745 &mut err,
746 call_expr.hir_id,
747 &callee_expr.kind,
748 callee_expr.span,
749 );
750
751 if let Some((removal_span, kind, path)) = &unit_variant {
752 err.span_suggestion_verbose(
753 *removal_span,
754 format!(
755 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
756 ),
757 "",
758 Applicability::MachineApplicable,
759 );
760 }
761
762 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
763 && let Res::Local(_) = path.res
764 && let [segment] = &path.segments
765 {
766 for id in self.tcx.hir_free_items() {
767 if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
768 && let hir::Node::Item(item) = node
769 && let hir::ItemKind::Fn { ident, .. } = item.kind
770 && ident.name == segment.ident.name
771 {
772 err.span_label(
773 self.tcx.def_span(id.owner_id),
774 "this function of the same name is available here, but it's shadowed by \
775 the local binding",
776 );
777 }
778 }
779 }
780
781 let mut inner_callee_path = None;
782 let def = match callee_expr.kind {
783 hir::ExprKind::Path(ref qpath) => {
784 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
785 }
786 hir::ExprKind::Call(inner_callee, _) => {
787 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
788 inner_callee_path = Some(inner_qpath);
789 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
790 } else {
791 Res::Err
792 }
793 }
794 _ => Res::Err,
795 };
796
797 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
798 let call_is_multiline = self
802 .tcx
803 .sess
804 .source_map()
805 .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
806 && call_expr.span.eq_ctxt(callee_expr.span);
807 if call_is_multiline {
808 err.span_suggestion(
809 callee_expr.span.shrink_to_hi(),
810 "consider using a semicolon here to finish the statement",
811 ";",
812 Applicability::MaybeIncorrect,
813 );
814 }
815 if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
816 && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
817 {
818 let descr = match maybe_def {
819 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
820 DefIdOrName::Name(name) => name,
821 };
822 err.span_label(
823 callee_expr.span,
824 format!("this {descr} returns an unsized value `{output_ty}`, so it cannot be called")
825 );
826 if let DefIdOrName::DefId(def_id) = maybe_def
827 && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
828 {
829 err.span_label(def_span, "the callable type is defined here");
830 }
831 } else {
832 err.span_label(call_expr.span, "call expression requires function");
833 }
834 }
835
836 if let Some(span) = self.tcx.hir_res_span(def) {
837 let callee_ty = callee_ty.to_string();
838 let label = match (unit_variant, inner_callee_path) {
839 (Some((_, kind, path)), _) => {
840 err.arg("kind", kind);
841 err.arg("path", path);
842 Some(fluent_generated::hir_typeck_invalid_defined_kind)
843 }
844 (_, Some(hir::QPath::Resolved(_, path))) => {
845 self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
846 err.arg("func", p);
847 fluent_generated::hir_typeck_invalid_fn_defined
848 })
849 }
850 _ => {
851 match def {
852 Res::Local(hir_id) => {
855 err.arg("local_name", self.tcx.hir_name(hir_id));
856 Some(fluent_generated::hir_typeck_invalid_local)
857 }
858 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
859 err.arg("path", self.tcx.def_path_str(def_id));
860 Some(fluent_generated::hir_typeck_invalid_defined)
861 }
862 _ => {
863 err.arg("path", callee_ty);
864 Some(fluent_generated::hir_typeck_invalid_defined)
865 }
866 }
867 }
868 };
869 if let Some(label) = label {
870 err.span_label(span, label);
871 }
872 }
873 err.emit()
874 }
875
876 fn confirm_deferred_closure_call(
877 &self,
878 call_expr: &'tcx hir::Expr<'tcx>,
879 arg_exprs: &'tcx [hir::Expr<'tcx>],
880 expected: Expectation<'tcx>,
881 closure_def_id: LocalDefId,
882 fn_sig: ty::FnSig<'tcx>,
883 ) -> Ty<'tcx> {
884 self.check_argument_types(
889 call_expr.span,
890 call_expr,
891 fn_sig.inputs(),
892 fn_sig.output(),
893 expected,
894 arg_exprs,
895 fn_sig.c_variadic,
896 TupleArgumentsFlag::TupleArguments,
897 Some(closure_def_id.to_def_id()),
898 );
899
900 fn_sig.output()
901 }
902
903 #[tracing::instrument(level = "debug", skip(self, span))]
904 pub(super) fn enforce_context_effects(
905 &self,
906 call_hir_id: Option<HirId>,
907 span: Span,
908 callee_did: DefId,
909 callee_args: GenericArgsRef<'tcx>,
910 ) {
911 if !self.tcx.features().const_trait_impl() {
916 return;
917 }
918
919 if self.tcx.has_attr(self.body_id, sym::rustc_do_not_const_check) {
921 return;
922 }
923
924 let host = match self.tcx.hir_body_const_context(self.body_id) {
925 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
926 ty::BoundConstness::Const
927 }
928 Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
929 None => return,
930 };
931
932 if self.tcx.is_conditionally_const(callee_did) {
935 let q = self.tcx.const_conditions(callee_did);
936 for (idx, (cond, pred_span)) in
938 q.instantiate(self.tcx, callee_args).into_iter().enumerate()
939 {
940 let cause = self.cause(
941 span,
942 if let Some(hir_id) = call_hir_id {
943 ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
944 } else {
945 ObligationCauseCode::WhereClause(callee_did, pred_span)
946 },
947 );
948 self.register_predicate(Obligation::new(
949 self.tcx,
950 cause,
951 self.param_env,
952 cond.to_host_effect_clause(self.tcx, host),
953 ));
954 }
955 } else {
956 }
959 }
960
961 fn confirm_overloaded_call(
962 &self,
963 call_expr: &'tcx hir::Expr<'tcx>,
964 arg_exprs: &'tcx [hir::Expr<'tcx>],
965 expected: Expectation<'tcx>,
966 method: MethodCallee<'tcx>,
967 ) -> Ty<'tcx> {
968 self.check_argument_types(
969 call_expr.span,
970 call_expr,
971 &method.sig.inputs()[1..],
972 method.sig.output(),
973 expected,
974 arg_exprs,
975 method.sig.c_variadic,
976 TupleArgumentsFlag::TupleArguments,
977 Some(method.def_id),
978 );
979
980 self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
981
982 method.sig.output()
983 }
984}
985
986#[derive(Debug)]
987pub(crate) struct DeferredCallResolution<'tcx> {
988 call_expr: &'tcx hir::Expr<'tcx>,
989 callee_expr: &'tcx hir::Expr<'tcx>,
990 closure_ty: Ty<'tcx>,
991 adjustments: Vec<Adjustment<'tcx>>,
992 fn_sig: ty::FnSig<'tcx>,
993}
994
995impl<'a, 'tcx> DeferredCallResolution<'tcx> {
996 pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
997 debug!("DeferredCallResolution::resolve() {:?}", self);
998
999 assert!(fcx.closure_kind(self.closure_ty).is_some());
1002
1003 match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1005 Some((autoref, method_callee)) => {
1006 let method_sig = method_callee.sig;
1015
1016 debug!("attempt_resolution: method_callee={:?}", method_callee);
1017
1018 for (method_arg_ty, self_arg_ty) in
1019 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1020 {
1021 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1022 }
1023
1024 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1025
1026 let mut adjustments = self.adjustments;
1027 adjustments.extend(autoref);
1028 fcx.apply_adjustments(self.callee_expr, adjustments);
1029
1030 fcx.write_method_call_and_enforce_effects(
1031 self.call_expr.hir_id,
1032 self.call_expr.span,
1033 method_callee,
1034 );
1035 }
1036 None => {
1037 span_bug!(
1038 self.call_expr.span,
1039 "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1040 self.closure_ty
1041 )
1042 }
1043 }
1044 }
1045}