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::method::TreatNotYetDefinedOpaques;
29use crate::{errors, fluent_generated};
30
31pub(crate) fn check_legal_trait_for_method_call(
35 tcx: TyCtxt<'_>,
36 span: Span,
37 receiver: Option<Span>,
38 expr_span: Span,
39 trait_id: DefId,
40 _body_id: DefId,
41) -> Result<(), ErrorGuaranteed> {
42 if tcx.is_lang_item(trait_id, LangItem::Drop) {
43 let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
44 errors::ExplicitDestructorCallSugg::Snippet {
45 lo: expr_span.shrink_to_lo(),
46 hi: receiver.shrink_to_hi().to(expr_span.shrink_to_hi()),
47 }
48 } else {
49 errors::ExplicitDestructorCallSugg::Empty(span)
50 };
51 return Err(tcx.dcx().emit_err(errors::ExplicitDestructorCall { span, sugg }));
52 }
53 tcx.ensure_ok().coherent_trait(trait_id)
54}
55
56#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CallStep<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CallStep::Builtin(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Builtin", &__self_0),
CallStep::DeferredClosure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"DeferredClosure", __self_0, &__self_1),
CallStep::Overloaded(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Overloaded", &__self_0),
}
}
}Debug)]
57enum CallStep<'tcx> {
58 Builtin(Ty<'tcx>),
59 DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
60 Overloaded(MethodCallee<'tcx>),
62}
63
64impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
65 pub(crate) fn check_expr_call(
66 &self,
67 call_expr: &'tcx hir::Expr<'tcx>,
68 callee_expr: &'tcx hir::Expr<'tcx>,
69 arg_exprs: &'tcx [hir::Expr<'tcx>],
70 expected: Expectation<'tcx>,
71 ) -> Ty<'tcx> {
72 let original_callee_ty = match &callee_expr.kind {
73 hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
74 .check_expr_with_expectation_and_args(
75 callee_expr,
76 Expectation::NoExpectation,
77 Some((call_expr, arg_exprs)),
78 ),
79 _ => self.check_expr(callee_expr),
80 };
81
82 let expr_ty = self.try_structurally_resolve_type(call_expr.span, original_callee_ty);
83
84 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
85 let mut result = None;
86 while result.is_none() && autoderef.next().is_some() {
87 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
88 }
89
90 match autoderef.final_ty().kind() {
91 ty::FnDef(def_id, _) => {
92 let abi = self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi;
93 self.check_call_abi(abi, call_expr.span);
94 }
95 ty::FnPtr(_, header) => {
96 self.check_call_abi(header.abi, call_expr.span);
97 }
98 _ => { }
99 }
100
101 self.register_predicates(autoderef.into_obligations());
102
103 let output = match result {
104 None => {
105 for arg in arg_exprs {
108 self.check_expr(arg);
109 }
110
111 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
112 && let [segment] = path.segments
113 {
114 self.dcx().try_steal_modify_and_emit_err(
115 segment.ident.span,
116 StashKey::CallIntoMethod,
117 |err| {
118 self.suggest_call_as_method(
120 err, segment, arg_exprs, call_expr, expected,
121 );
122 },
123 );
124 }
125
126 let guar = self.report_invalid_callee(call_expr, callee_expr, expr_ty, arg_exprs);
127 Ty::new_error(self.tcx, guar)
128 }
129
130 Some(CallStep::Builtin(callee_ty)) => {
131 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
132 }
133
134 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
135 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
136 }
137
138 Some(CallStep::Overloaded(method_callee)) => {
139 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
140 }
141 };
142
143 self.register_wf_obligation(
145 output.into(),
146 call_expr.span,
147 ObligationCauseCode::WellFormed(None),
148 );
149
150 output
151 }
152
153 pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span) {
158 let canon_abi = match AbiMap::from_target(&self.sess().target).canonize_abi(abi, false) {
159 AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => canon_abi,
160 AbiMapping::Invalid => {
161 let guar = self.dcx().span_delayed_bug(
164 span,
165 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid abi for platform should have reported an error: {0}",
abi))
})format!("invalid abi for platform should have reported an error: {abi}"),
166 );
167 self.set_tainted_by_errors(guar);
168 return;
169 }
170 };
171
172 match canon_abi {
173 CanonAbi::Custom
175 | CanonAbi::Interrupt(_) => {
178 let err = crate::errors::AbiCannotBeCalled { span, abi };
179 self.tcx.dcx().emit_err(err);
180 }
181
182 CanonAbi::GpuKernel => {
184 let err = crate::errors::GpuKernelAbiCannotBeCalled { span };
185 self.tcx.dcx().emit_err(err);
186 }
187
188 CanonAbi::C
189 | CanonAbi::Rust
190 | CanonAbi::RustCold
191 | CanonAbi::RustPreserveNone
192 | CanonAbi::Arm(_)
193 | CanonAbi::X86(_) => {}
194 }
195 }
196
197 x;#[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
198 fn try_overloaded_call_step(
199 &self,
200 call_expr: &'tcx hir::Expr<'tcx>,
201 callee_expr: &'tcx hir::Expr<'tcx>,
202 arg_exprs: &'tcx [hir::Expr<'tcx>],
203 autoderef: &Autoderef<'a, 'tcx>,
204 ) -> Option<CallStep<'tcx>> {
205 let adjusted_ty =
206 self.try_structurally_resolve_type(autoderef.span(), autoderef.final_ty());
207
208 match *adjusted_ty.kind() {
210 ty::FnDef(..) | ty::FnPtr(..) => {
211 let adjustments = self.adjust_steps(autoderef);
212 self.apply_adjustments(callee_expr, adjustments);
213 return Some(CallStep::Builtin(adjusted_ty));
214 }
215
216 ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
220 let def_id = def_id.expect_local();
221 let closure_sig = args.as_closure().sig();
222 let closure_sig = self.instantiate_binder_with_fresh_vars(
223 call_expr.span,
224 BoundRegionConversionTime::FnCall,
225 closure_sig,
226 );
227 let adjustments = self.adjust_steps(autoderef);
228 self.record_deferred_call_resolution(
229 def_id,
230 DeferredCallResolution {
231 call_expr,
232 callee_expr,
233 closure_ty: adjusted_ty,
234 adjustments,
235 fn_sig: closure_sig,
236 },
237 );
238 return Some(CallStep::DeferredClosure(def_id, closure_sig));
239 }
240
241 ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
247 let def_id = def_id.expect_local();
248 let closure_args = args.as_coroutine_closure();
249 let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
250 call_expr.span,
251 BoundRegionConversionTime::FnCall,
252 closure_args.coroutine_closure_sig(),
253 );
254 let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
255 let kind_ty = self.next_ty_var(callee_expr.span);
260 let call_sig = self.tcx.mk_fn_sig(
261 [coroutine_closure_sig.tupled_inputs_ty],
262 coroutine_closure_sig.to_coroutine(
263 self.tcx,
264 closure_args.parent_args(),
265 kind_ty,
266 self.tcx.coroutine_for_closure(def_id),
267 tupled_upvars_ty,
268 ),
269 coroutine_closure_sig.c_variadic,
270 coroutine_closure_sig.safety,
271 coroutine_closure_sig.abi,
272 );
273 let adjustments = self.adjust_steps(autoderef);
274 self.record_deferred_call_resolution(
275 def_id,
276 DeferredCallResolution {
277 call_expr,
278 callee_expr,
279 closure_ty: adjusted_ty,
280 adjustments,
281 fn_sig: call_sig,
282 },
283 );
284 return Some(CallStep::DeferredClosure(def_id, call_sig));
285 }
286
287 ty::Ref(..) if autoderef.step_count() == 0 => {
300 return None;
301 }
302
303 ty::Infer(ty::TyVar(vid)) => {
304 if !self.has_opaques_with_sub_unified_hidden_type(vid) {
307 self.type_must_be_known_at_this_point(autoderef.span(), adjusted_ty);
308 return None;
309 }
310 }
311
312 ty::Error(_) => {
313 return None;
314 }
315
316 _ => {}
317 }
318
319 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
327 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
328 .map(|(autoref, method)| {
329 let mut adjustments = self.adjust_steps(autoderef);
330 adjustments.extend(autoref);
331 self.apply_adjustments(callee_expr, adjustments);
332 CallStep::Overloaded(method)
333 })
334 }
335
336 fn try_overloaded_call_traits(
337 &self,
338 call_expr: &hir::Expr<'_>,
339 adjusted_ty: Ty<'tcx>,
340 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
341 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
342 let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
355 [
356 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
357 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
358 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
359 (self.tcx.lang_items().fn_trait(), sym::call, true),
360 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
361 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
362 ]
363 } else {
364 [
365 (self.tcx.lang_items().fn_trait(), sym::call, true),
366 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
367 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
368 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
369 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
370 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
371 ]
372 };
373
374 for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
376 let Some(trait_def_id) = opt_trait_def_id else { continue };
377
378 let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
379 Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
380 });
381
382 if let Some(ok) = self.lookup_method_for_operator(
389 self.misc(call_expr.span),
390 method_name,
391 trait_def_id,
392 adjusted_ty,
393 opt_input_type,
394 TreatNotYetDefinedOpaques::AsRigid,
395 ) {
396 let method = self.register_infer_ok_obligations(ok);
397 let mut autoref = None;
398 if borrow {
399 let ty::Ref(_, _, mutbl) = *method.sig.inputs()[0].kind() else {
402 ::rustc_middle::util::bug::bug_fmt(format_args!("Expected `FnMut`/`Fn` to take receiver by-ref/by-mut"))bug!("Expected `FnMut`/`Fn` to take receiver by-ref/by-mut")
403 };
404
405 let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::No);
409
410 autoref = Some(Adjustment {
411 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
412 target: method.sig.inputs()[0],
413 });
414 }
415
416 return Some((autoref, method));
417 }
418 }
419
420 None
421 }
422
423 fn identify_bad_closure_def_and_call(
426 &self,
427 err: &mut Diag<'_>,
428 hir_id: hir::HirId,
429 callee_node: &hir::ExprKind<'_>,
430 callee_span: Span,
431 ) {
432 let hir::ExprKind::Block(..) = callee_node else {
433 return;
435 };
436
437 let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
438 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
439 ..
440 }) = self.tcx.parent_hir_node(hir_id)
441 {
442 fn_decl_span
443 } else if let Some((
444 _,
445 hir::Node::Expr(&hir::Expr {
446 hir_id: parent_hir_id,
447 kind:
448 hir::ExprKind::Closure(&hir::Closure {
449 kind:
450 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
451 hir::CoroutineDesugaring::Async,
452 hir::CoroutineSource::Closure,
453 )),
454 ..
455 }),
456 ..
457 }),
458 )) = self.tcx.hir_parent_iter(hir_id).nth(3)
459 {
460 let hir::Node::Expr(&hir::Expr {
463 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
464 ..
465 }) = self.tcx.parent_hir_node(parent_hir_id)
466 else {
467 return;
468 };
469 fn_decl_span
470 } else {
471 return;
472 };
473
474 let start = fn_decl_span.shrink_to_lo();
475 let end = callee_span.shrink_to_hi();
476 err.multipart_suggestion(
477 "if you meant to create this closure and immediately call it, surround the \
478 closure with parentheses",
479 <[_]>::into_vec(::alloc::boxed::box_new([(start, "(".to_string()),
(end, ")".to_string())]))vec![(start, "(".to_string()), (end, ")".to_string())],
480 Applicability::MaybeIncorrect,
481 );
482 }
483
484 fn maybe_suggest_bad_array_definition(
487 &self,
488 err: &mut Diag<'_>,
489 call_expr: &'tcx hir::Expr<'tcx>,
490 callee_expr: &'tcx hir::Expr<'tcx>,
491 ) -> bool {
492 let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
493 if let (
494 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
495 hir::ExprKind::Tup(exp),
496 hir::ExprKind::Call(_, args),
497 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
498 && args.len() == exp.len()
499 {
500 let start = callee_expr.span.shrink_to_hi();
501 err.span_suggestion(
502 start,
503 "consider separating array elements with a comma",
504 ",",
505 Applicability::MaybeIncorrect,
506 );
507 return true;
508 }
509 false
510 }
511
512 fn confirm_builtin_call(
513 &self,
514 call_expr: &'tcx hir::Expr<'tcx>,
515 callee_expr: &'tcx hir::Expr<'tcx>,
516 callee_ty: Ty<'tcx>,
517 arg_exprs: &'tcx [hir::Expr<'tcx>],
518 expected: Expectation<'tcx>,
519 ) -> Ty<'tcx> {
520 let (fn_sig, def_id) = match *callee_ty.kind() {
521 ty::FnDef(def_id, args) => {
522 self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
523 let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args);
524
525 if self.has_rustc_attrs
529 && self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses)
530 {
531 let predicates = self.tcx.predicates_of(def_id);
532 let predicates = predicates.instantiate(self.tcx, args);
533 for (predicate, predicate_span) in predicates {
534 let obligation = Obligation::new(
535 self.tcx,
536 ObligationCause::dummy_with_span(callee_expr.span),
537 self.param_env,
538 predicate,
539 );
540 let result = self.evaluate_obligation(&obligation);
541 self.dcx()
542 .struct_span_err(
543 callee_expr.span,
544 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("evaluate({0:?}) = {1:?}",
predicate, result))
})format!("evaluate({predicate:?}) = {result:?}"),
545 )
546 .with_span_label(predicate_span, "predicate")
547 .emit();
548 }
549 }
550 (fn_sig, Some(def_id))
551 }
552
553 ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None),
555
556 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
557 };
558
559 let fn_sig = self.instantiate_binder_with_fresh_vars(
565 call_expr.span,
566 BoundRegionConversionTime::FnCall,
567 fn_sig,
568 );
569 let fn_sig = self.normalize(call_expr.span, fn_sig);
570
571 self.check_argument_types(
572 call_expr.span,
573 call_expr,
574 fn_sig.inputs(),
575 fn_sig.output(),
576 expected,
577 arg_exprs,
578 fn_sig.c_variadic,
579 TupleArgumentsFlag::DontTupleArguments,
580 def_id,
581 );
582
583 if fn_sig.abi == rustc_abi::ExternAbi::RustCall {
584 let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
585 if let Some(ty) = fn_sig.inputs().last().copied() {
586 self.register_bound(
587 ty,
588 self.tcx.require_lang_item(hir::LangItem::Tuple, sp),
589 self.cause(sp, ObligationCauseCode::RustCall),
590 );
591 self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
592 } else {
593 self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
594 }
595 }
596
597 fn_sig.output()
598 }
599
600 fn suggest_call_as_method(
603 &self,
604 diag: &mut Diag<'_>,
605 segment: &'tcx hir::PathSegment<'tcx>,
606 arg_exprs: &'tcx [hir::Expr<'tcx>],
607 call_expr: &'tcx hir::Expr<'tcx>,
608 expected: Expectation<'tcx>,
609 ) {
610 if let [callee_expr, rest @ ..] = arg_exprs {
611 let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
612 else {
613 return;
614 };
615
616 let Ok(pick) = self.lookup_probe_for_diagnostic(
620 segment.ident,
621 callee_ty,
622 call_expr,
623 ProbeScope::AllTraits,
626 expected.only_has_type(self),
627 ) else {
628 return;
629 };
630
631 let pick = self.confirm_method_for_diagnostic(
632 call_expr.span,
633 callee_expr,
634 call_expr,
635 callee_ty,
636 &pick,
637 segment,
638 );
639 if pick.illegal_sized_bound.is_some() {
640 return;
641 }
642
643 let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
644 else {
645 return;
646 };
647 let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
648 let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
649 let rest_snippet = if let Some(first) = rest.first() {
650 self.tcx
651 .sess
652 .source_map()
653 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
654 } else {
655 Ok(")".to_string())
656 };
657
658 if let Ok(rest_snippet) = rest_snippet {
659 let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
660 <[_]>::into_vec(::alloc::boxed::box_new([(up_to_rcvr_span, "".to_string()),
(rest_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(".{0}({1}", segment.ident,
rest_snippet))
}))]))vec![
661 (up_to_rcvr_span, "".to_string()),
662 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
663 ]
664 } else {
665 <[_]>::into_vec(::alloc::boxed::box_new([(up_to_rcvr_span, "(".to_string()),
(rest_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(").{0}({1}",
segment.ident, rest_snippet))
}))]))vec![
666 (up_to_rcvr_span, "(".to_string()),
667 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
668 ]
669 };
670 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
671 diag.multipart_suggestion(
672 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use the `.` operator to call the method `{0}{1}` on `{2}`",
self.tcx.associated_item(pick.callee.def_id).trait_container(self.tcx).map_or_else(||
String::new(),
|trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"),
segment.ident, self_ty))
})format!(
673 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
674 self.tcx
675 .associated_item(pick.callee.def_id)
676 .trait_container(self.tcx)
677 .map_or_else(
678 || String::new(),
679 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
680 ),
681 segment.ident
682 ),
683 sugg,
684 Applicability::MaybeIncorrect,
685 );
686 }
687 }
688 }
689
690 fn report_invalid_callee(
691 &self,
692 call_expr: &'tcx hir::Expr<'tcx>,
693 callee_expr: &'tcx hir::Expr<'tcx>,
694 callee_ty: Ty<'tcx>,
695 arg_exprs: &'tcx [hir::Expr<'tcx>],
696 ) -> ErrorGuaranteed {
697 if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
700 && let Err(err) = args.error_reported()
701 {
702 return err;
703 }
704
705 let mut unit_variant = None;
706 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
707 && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
708 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
709 && arg_exprs.is_empty()
711 && call_expr.span.contains(callee_expr.span)
712 {
713 let descr = match kind {
714 def::CtorOf::Struct => "struct",
715 def::CtorOf::Variant => "enum variant",
716 };
717 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
718 unit_variant =
719 Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
720 }
721
722 let callee_ty = self.resolve_vars_if_possible(callee_ty);
723 let mut path = None;
724 let mut err = self.dcx().create_err(errors::InvalidCallee {
725 span: callee_expr.span,
726 ty: callee_ty,
727 found: match &unit_variant {
728 Some((_, kind, path)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind, path))
})format!("{kind} `{path}`"),
729 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(callee_ty, &mut path)))
})format!("`{}`", self.tcx.short_string(callee_ty, &mut path)),
730 },
731 });
732 *err.long_ty_path() = path;
733 if callee_ty.references_error() {
734 err.downgrade_to_delayed_bug();
735 }
736
737 self.identify_bad_closure_def_and_call(
738 &mut err,
739 call_expr.hir_id,
740 &callee_expr.kind,
741 callee_expr.span,
742 );
743
744 if let Some((removal_span, kind, path)) = &unit_variant {
745 err.span_suggestion_verbose(
746 *removal_span,
747 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a unit {1}, and does not take parentheses to be constructed",
path, kind))
})format!(
748 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
749 ),
750 "",
751 Applicability::MachineApplicable,
752 );
753 }
754
755 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
756 && let Res::Local(_) = path.res
757 && let [segment] = &path.segments
758 {
759 for id in self.tcx.hir_free_items() {
760 if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
761 && let hir::Node::Item(item) = node
762 && let hir::ItemKind::Fn { ident, .. } = item.kind
763 && ident.name == segment.ident.name
764 {
765 err.span_label(
766 self.tcx.def_span(id.owner_id),
767 "this function of the same name is available here, but it's shadowed by \
768 the local binding",
769 );
770 }
771 }
772 }
773
774 let mut inner_callee_path = None;
775 let def = match callee_expr.kind {
776 hir::ExprKind::Path(ref qpath) => {
777 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
778 }
779 hir::ExprKind::Call(inner_callee, _) => {
780 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
781 inner_callee_path = Some(inner_qpath);
782 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
783 } else {
784 Res::Err
785 }
786 }
787 _ => Res::Err,
788 };
789
790 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
791 let call_is_multiline = self
795 .tcx
796 .sess
797 .source_map()
798 .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
799 && call_expr.span.eq_ctxt(callee_expr.span);
800 if call_is_multiline {
801 err.span_suggestion(
802 callee_expr.span.shrink_to_hi(),
803 "consider using a semicolon here to finish the statement",
804 ";",
805 Applicability::MaybeIncorrect,
806 );
807 }
808 if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
809 && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
810 {
811 let descr = match maybe_def {
812 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
813 DefIdOrName::Name(name) => name,
814 };
815 err.span_label(
816 callee_expr.span,
817 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this {0} returns an unsized value `{1}`, so it cannot be called",
descr, output_ty))
})format!("this {descr} returns an unsized value `{output_ty}`, so it cannot be called")
818 );
819 if let DefIdOrName::DefId(def_id) = maybe_def
820 && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
821 {
822 err.span_label(def_span, "the callable type is defined here");
823 }
824 } else {
825 err.span_label(call_expr.span, "call expression requires function");
826 }
827 }
828
829 if let Some(span) = self.tcx.hir_res_span(def) {
830 let callee_ty = callee_ty.to_string();
831 let label = match (unit_variant, inner_callee_path) {
832 (Some((_, kind, path)), _) => {
833 err.arg("kind", kind);
834 err.arg("path", path);
835 Some(fluent_generated::hir_typeck_invalid_defined_kind)
836 }
837 (_, Some(hir::QPath::Resolved(_, path))) => {
838 self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
839 err.arg("func", p);
840 fluent_generated::hir_typeck_invalid_fn_defined
841 })
842 }
843 _ => {
844 match def {
845 Res::Local(hir_id) => {
848 err.arg("local_name", self.tcx.hir_name(hir_id));
849 Some(fluent_generated::hir_typeck_invalid_local)
850 }
851 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
852 err.arg("path", self.tcx.def_path_str(def_id));
853 Some(fluent_generated::hir_typeck_invalid_defined)
854 }
855 _ => {
856 err.arg("path", callee_ty);
857 Some(fluent_generated::hir_typeck_invalid_defined)
858 }
859 }
860 }
861 };
862 if let Some(label) = label {
863 err.span_label(span, label);
864 }
865 }
866 err.emit()
867 }
868
869 fn confirm_deferred_closure_call(
870 &self,
871 call_expr: &'tcx hir::Expr<'tcx>,
872 arg_exprs: &'tcx [hir::Expr<'tcx>],
873 expected: Expectation<'tcx>,
874 closure_def_id: LocalDefId,
875 fn_sig: ty::FnSig<'tcx>,
876 ) -> Ty<'tcx> {
877 self.check_argument_types(
882 call_expr.span,
883 call_expr,
884 fn_sig.inputs(),
885 fn_sig.output(),
886 expected,
887 arg_exprs,
888 fn_sig.c_variadic,
889 TupleArgumentsFlag::TupleArguments,
890 Some(closure_def_id.to_def_id()),
891 );
892
893 fn_sig.output()
894 }
895
896 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("enforce_context_effects",
"rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(896u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&["call_hir_id",
"callee_did", "callee_args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_did)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if !self.tcx.features().const_trait_impl() { return; }
if self.has_rustc_attrs &&
self.tcx.has_attr(self.body_id,
sym::rustc_do_not_const_check) {
return;
}
let host =
match self.tcx.hir_body_const_context(self.body_id) {
Some(hir::ConstContext::Const { .. } |
hir::ConstContext::Static(_)) => {
ty::BoundConstness::Const
}
Some(hir::ConstContext::ConstFn) =>
ty::BoundConstness::Maybe,
None => return,
};
if self.tcx.is_conditionally_const(callee_did) {
let q = self.tcx.const_conditions(callee_did);
for (idx, (cond, pred_span)) in
q.instantiate(self.tcx, callee_args).into_iter().enumerate()
{
let cause =
self.cause(span,
if let Some(hir_id) = call_hir_id {
ObligationCauseCode::HostEffectInExpr(callee_did, pred_span,
hir_id, idx)
} else {
ObligationCauseCode::WhereClause(callee_did, pred_span)
});
self.register_predicate(Obligation::new(self.tcx, cause,
self.param_env,
cond.to_host_effect_clause(self.tcx, host)));
}
} else {}
}
}
}#[tracing::instrument(level = "debug", skip(self, span))]
897 pub(super) fn enforce_context_effects(
898 &self,
899 call_hir_id: Option<HirId>,
900 span: Span,
901 callee_did: DefId,
902 callee_args: GenericArgsRef<'tcx>,
903 ) {
904 if !self.tcx.features().const_trait_impl() {
909 return;
910 }
911
912 if self.has_rustc_attrs && self.tcx.has_attr(self.body_id, sym::rustc_do_not_const_check) {
914 return;
915 }
916
917 let host = match self.tcx.hir_body_const_context(self.body_id) {
918 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
919 ty::BoundConstness::Const
920 }
921 Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
922 None => return,
923 };
924
925 if self.tcx.is_conditionally_const(callee_did) {
928 let q = self.tcx.const_conditions(callee_did);
929 for (idx, (cond, pred_span)) in
930 q.instantiate(self.tcx, callee_args).into_iter().enumerate()
931 {
932 let cause = self.cause(
933 span,
934 if let Some(hir_id) = call_hir_id {
935 ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
936 } else {
937 ObligationCauseCode::WhereClause(callee_did, pred_span)
938 },
939 );
940 self.register_predicate(Obligation::new(
941 self.tcx,
942 cause,
943 self.param_env,
944 cond.to_host_effect_clause(self.tcx, host),
945 ));
946 }
947 } else {
948 }
951 }
952
953 fn confirm_overloaded_call(
954 &self,
955 call_expr: &'tcx hir::Expr<'tcx>,
956 arg_exprs: &'tcx [hir::Expr<'tcx>],
957 expected: Expectation<'tcx>,
958 method: MethodCallee<'tcx>,
959 ) -> Ty<'tcx> {
960 self.check_argument_types(
961 call_expr.span,
962 call_expr,
963 &method.sig.inputs()[1..],
964 method.sig.output(),
965 expected,
966 arg_exprs,
967 method.sig.c_variadic,
968 TupleArgumentsFlag::TupleArguments,
969 Some(method.def_id),
970 );
971
972 self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
973
974 method.sig.output()
975 }
976}
977
978#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for DeferredCallResolution<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"DeferredCallResolution", "call_expr", &self.call_expr,
"callee_expr", &self.callee_expr, "closure_ty", &self.closure_ty,
"adjustments", &self.adjustments, "fn_sig", &&self.fn_sig)
}
}Debug)]
979pub(crate) struct DeferredCallResolution<'tcx> {
980 call_expr: &'tcx hir::Expr<'tcx>,
981 callee_expr: &'tcx hir::Expr<'tcx>,
982 closure_ty: Ty<'tcx>,
983 adjustments: Vec<Adjustment<'tcx>>,
984 fn_sig: ty::FnSig<'tcx>,
985}
986
987impl<'a, 'tcx> DeferredCallResolution<'tcx> {
988 pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
989 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/callee.rs:989",
"rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(989u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("DeferredCallResolution::resolve() {0:?}",
self) as &dyn Value))])
});
} else { ; }
};debug!("DeferredCallResolution::resolve() {:?}", self);
990
991 if !fcx.closure_kind(self.closure_ty).is_some() {
::core::panicking::panic("assertion failed: fcx.closure_kind(self.closure_ty).is_some()")
};assert!(fcx.closure_kind(self.closure_ty).is_some());
994
995 match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
997 Some((autoref, method_callee)) => {
998 let method_sig = method_callee.sig;
1007
1008 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/callee.rs:1008",
"rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(1008u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("attempt_resolution: method_callee={0:?}",
method_callee) as &dyn Value))])
});
} else { ; }
};debug!("attempt_resolution: method_callee={:?}", method_callee);
1009
1010 for (method_arg_ty, self_arg_ty) in
1011 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1012 {
1013 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1014 }
1015
1016 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1017
1018 let mut adjustments = self.adjustments;
1019 adjustments.extend(autoref);
1020 fcx.apply_adjustments(self.callee_expr, adjustments);
1021
1022 fcx.write_method_call_and_enforce_effects(
1023 self.call_expr.hir_id,
1024 self.call_expr.span,
1025 method_callee,
1026 );
1027 }
1028 None => {
1029 ::rustc_middle::util::bug::span_bug_fmt(self.call_expr.span,
format_args!("Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{0}`",
self.closure_ty))span_bug!(
1030 self.call_expr.span,
1031 "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1032 self.closure_ty
1033 )
1034 }
1035 }
1036 }
1037}