1use std::iter;
2
3use rustc_abi::{CanonAbi, ExternAbi};
4use rustc_ast::util::parser::ExprPrecedence;
5use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey, msg};
6use rustc_hir::def::{self, CtorKind, Namespace, Res};
7use rustc_hir::def_id::DefId;
8use rustc_hir::{self as hir, HirId, LangItem, find_attr};
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, Unnormalized};
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;
29use crate::method::TreatNotYetDefinedOpaques;
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_result().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.resolve_vars_with_obligations(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 if self.is_scalable_vector_ctor(autoderef.final_ty()) {
102 let mut err = self.dcx().create_err(errors::ScalableVectorCtor {
103 span: callee_expr.span,
104 ty: autoderef.final_ty(),
105 });
106 err.span_label(callee_expr.span, "you can create scalable vectors using intrinsics");
107 Ty::new_error(self.tcx, err.emit());
108 }
109
110 self.register_predicates(autoderef.into_obligations());
111
112 let output = match result {
113 None => {
114 for arg in arg_exprs {
117 self.check_expr(arg);
118 }
119
120 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
121 && let [segment] = path.segments
122 {
123 self.dcx().try_steal_modify_and_emit_err(
124 segment.ident.span,
125 StashKey::CallIntoMethod,
126 |err| {
127 self.suggest_call_as_method(
129 err, segment, arg_exprs, call_expr, expected,
130 );
131 },
132 );
133 }
134
135 let guar = self.report_invalid_callee(call_expr, callee_expr, expr_ty, arg_exprs);
136 Ty::new_error(self.tcx, guar)
137 }
138
139 Some(CallStep::Builtin(callee_ty)) => {
140 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
141 }
142
143 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
144 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
145 }
146
147 Some(CallStep::Overloaded(method_callee)) => {
148 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
149 }
150 };
151
152 self.register_wf_obligation(
154 output.into(),
155 call_expr.span,
156 ObligationCauseCode::WellFormed(None),
157 );
158
159 output
160 }
161
162 pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span) {
167 let canon_abi = match AbiMap::from_target(&self.sess().target).canonize_abi(abi, false) {
168 AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => canon_abi,
169 AbiMapping::Invalid => {
170 let guar = self.dcx().span_delayed_bug(
173 span,
174 ::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}"),
175 );
176 self.set_tainted_by_errors(guar);
177 return;
178 }
179 };
180
181 match canon_abi {
182 CanonAbi::Custom
184 | CanonAbi::Interrupt(_) => {
187 let err = crate::errors::AbiCannotBeCalled { span, abi };
188 self.tcx.dcx().emit_err(err);
189 }
190
191 CanonAbi::GpuKernel => {
193 let err = crate::errors::GpuKernelAbiCannotBeCalled { span };
194 self.tcx.dcx().emit_err(err);
195 }
196
197 CanonAbi::C
198 | CanonAbi::Rust
199 | CanonAbi::RustCold
200 | CanonAbi::RustPreserveNone
201 | CanonAbi::Arm(_)
202 | CanonAbi::X86(_) => {}
203 }
204 }
205
206 x;#[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
207 fn try_overloaded_call_step(
208 &self,
209 call_expr: &'tcx hir::Expr<'tcx>,
210 callee_expr: &'tcx hir::Expr<'tcx>,
211 arg_exprs: &'tcx [hir::Expr<'tcx>],
212 autoderef: &Autoderef<'a, 'tcx>,
213 ) -> Option<CallStep<'tcx>> {
214 let adjusted_ty = self.resolve_vars_with_obligations(autoderef.final_ty());
215
216 match *adjusted_ty.kind() {
218 ty::FnDef(..) | ty::FnPtr(..) => {
219 let adjustments = self.adjust_steps(autoderef);
220 self.apply_adjustments(callee_expr, adjustments);
221 return Some(CallStep::Builtin(adjusted_ty));
222 }
223
224 ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
228 let def_id = def_id.expect_local();
229 let closure_sig = args.as_closure().sig();
230 let closure_sig = self.instantiate_binder_with_fresh_vars(
231 call_expr.span,
232 BoundRegionConversionTime::FnCall,
233 closure_sig,
234 );
235 let adjustments = self.adjust_steps(autoderef);
236 self.record_deferred_call_resolution(
237 def_id,
238 DeferredCallResolution {
239 call_expr,
240 callee_expr,
241 closure_ty: adjusted_ty,
242 adjustments,
243 fn_sig: closure_sig,
244 },
245 );
246 return Some(CallStep::DeferredClosure(def_id, closure_sig));
247 }
248
249 ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
255 let def_id = def_id.expect_local();
256 let closure_args = args.as_coroutine_closure();
257 let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
258 call_expr.span,
259 BoundRegionConversionTime::FnCall,
260 closure_args.coroutine_closure_sig(),
261 );
262 let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
263 let kind_ty = self.next_ty_var(callee_expr.span);
268 let call_sig = self.tcx.mk_fn_sig(
269 [coroutine_closure_sig.tupled_inputs_ty],
270 coroutine_closure_sig.to_coroutine(
271 self.tcx,
272 closure_args.parent_args(),
273 kind_ty,
274 self.tcx.coroutine_for_closure(def_id),
275 tupled_upvars_ty,
276 ),
277 coroutine_closure_sig.fn_sig_kind,
278 );
279 let adjustments = self.adjust_steps(autoderef);
280 self.record_deferred_call_resolution(
281 def_id,
282 DeferredCallResolution {
283 call_expr,
284 callee_expr,
285 closure_ty: adjusted_ty,
286 adjustments,
287 fn_sig: call_sig,
288 },
289 );
290 return Some(CallStep::DeferredClosure(def_id, call_sig));
291 }
292
293 ty::Ref(..) if autoderef.step_count() == 0 => {
306 return None;
307 }
308
309 ty::Infer(ty::TyVar(vid)) => {
310 if !self.has_opaques_with_sub_unified_hidden_type(vid) {
313 self.type_must_be_known_at_this_point(autoderef.span(), adjusted_ty);
314 return None;
315 }
316 }
317
318 ty::Error(_) => {
319 return None;
320 }
321
322 _ => {}
323 }
324
325 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
333 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
334 .map(|(autoref, method)| {
335 let mut adjustments = self.adjust_steps(autoderef);
336 adjustments.extend(autoref);
337 self.apply_adjustments(callee_expr, adjustments);
338 CallStep::Overloaded(method)
339 })
340 }
341
342 fn try_overloaded_call_traits(
343 &self,
344 call_expr: &hir::Expr<'_>,
345 adjusted_ty: Ty<'tcx>,
346 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
347 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
348 let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
361 [
362 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
363 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
364 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
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 ]
369 } else {
370 [
371 (self.tcx.lang_items().fn_trait(), sym::call, true),
372 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
373 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
374 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
375 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
376 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
377 ]
378 };
379
380 for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
382 let Some(trait_def_id) = opt_trait_def_id else { continue };
383
384 let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
385 Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
386 });
387
388 if let Some(ok) = self.lookup_method_for_operator(
395 self.misc(call_expr.span),
396 method_name,
397 trait_def_id,
398 adjusted_ty,
399 opt_input_type,
400 TreatNotYetDefinedOpaques::AsRigid,
401 ) {
402 let method = self.register_infer_ok_obligations(ok);
403 let mut autoref = None;
404 if borrow {
405 let ty::Ref(_, _, mutbl) = *method.sig.inputs()[0].kind() else {
408 ::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")
409 };
410
411 let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::No);
415
416 autoref = Some(Adjustment {
417 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
418 target: method.sig.inputs()[0],
419 });
420 }
421
422 return Some((autoref, method));
423 }
424 }
425
426 None
427 }
428
429 fn is_scalable_vector_ctor(&self, callee_ty: Ty<'_>) -> bool {
430 if let ty::FnDef(def_id, _) = *callee_ty.kind()
431 && let def::DefKind::Ctor(def::CtorOf::Struct, _) = self.tcx.def_kind(def_id)
432 {
433 self.tcx
434 .opt_parent(def_id)
435 .and_then(|id| self.tcx.adt_def(id).repr().scalable)
436 .is_some()
437 } else {
438 false
439 }
440 }
441
442 fn identify_bad_closure_def_and_call(
445 &self,
446 err: &mut Diag<'_>,
447 hir_id: hir::HirId,
448 callee_node: &hir::ExprKind<'_>,
449 callee_span: Span,
450 ) {
451 let hir::ExprKind::Block(..) = callee_node else {
452 return;
454 };
455
456 let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
457 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
458 ..
459 }) = self.tcx.parent_hir_node(hir_id)
460 {
461 fn_decl_span
462 } else if let Some((
463 _,
464 hir::Node::Expr(&hir::Expr {
465 hir_id: parent_hir_id,
466 kind:
467 hir::ExprKind::Closure(&hir::Closure {
468 kind:
469 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
470 hir::CoroutineDesugaring::Async,
471 hir::CoroutineSource::Closure,
472 )),
473 ..
474 }),
475 ..
476 }),
477 )) = self.tcx.hir_parent_iter(hir_id).nth(3)
478 {
479 let hir::Node::Expr(&hir::Expr {
482 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
483 ..
484 }) = self.tcx.parent_hir_node(parent_hir_id)
485 else {
486 return;
487 };
488 fn_decl_span
489 } else {
490 return;
491 };
492
493 let start = fn_decl_span.shrink_to_lo();
494 let end = callee_span.shrink_to_hi();
495 err.multipart_suggestion(
496 "if you meant to create this closure and immediately call it, surround the \
497 closure with parentheses",
498 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(start, "(".to_string()), (end, ")".to_string())]))vec![(start, "(".to_string()), (end, ")".to_string())],
499 Applicability::MaybeIncorrect,
500 );
501 }
502
503 fn maybe_suggest_bad_array_definition(
506 &self,
507 err: &mut Diag<'_>,
508 call_expr: &'tcx hir::Expr<'tcx>,
509 callee_expr: &'tcx hir::Expr<'tcx>,
510 ) -> bool {
511 let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
512 if let (
513 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
514 hir::ExprKind::Tup(exp),
515 hir::ExprKind::Call(_, args),
516 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
517 && args.len() == exp.len()
518 {
519 let start = callee_expr.span.shrink_to_hi();
520 err.span_suggestion(
521 start,
522 "consider separating array elements with a comma",
523 ",",
524 Applicability::MaybeIncorrect,
525 );
526 return true;
527 }
528 false
529 }
530
531 fn confirm_builtin_call(
532 &self,
533 call_expr: &'tcx hir::Expr<'tcx>,
534 callee_expr: &'tcx hir::Expr<'tcx>,
535 callee_ty: Ty<'tcx>,
536 arg_exprs: &'tcx [hir::Expr<'tcx>],
537 expected: Expectation<'tcx>,
538 ) -> Ty<'tcx> {
539 let (fn_sig, def_id) = match *callee_ty.kind() {
540 ty::FnDef(def_id, args) => {
541 self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
542 let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args).skip_norm_wip();
543
544 if self.has_rustc_attrs && {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcEvaluateWhereClauses) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, def_id, RustcEvaluateWhereClauses) {
548 let predicates = self.tcx.predicates_of(def_id);
549 let predicates = predicates.instantiate(self.tcx, args);
550 for (predicate, predicate_span) in predicates {
551 let predicate = predicate.skip_norm_wip();
552 let obligation = Obligation::new(
553 self.tcx,
554 ObligationCause::dummy_with_span(callee_expr.span),
555 self.param_env,
556 predicate,
557 );
558 let result = self.evaluate_obligation(&obligation);
559 self.dcx()
560 .struct_span_err(
561 callee_expr.span,
562 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("evaluate({0:?}) = {1:?}",
predicate, result))
})format!("evaluate({predicate:?}) = {result:?}"),
563 )
564 .with_span_label(predicate_span, "predicate")
565 .emit();
566 }
567 }
568 (fn_sig, Some(def_id))
569 }
570
571 ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None),
573
574 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
575 };
576
577 let fn_sig = self.instantiate_binder_with_fresh_vars(
583 call_expr.span,
584 BoundRegionConversionTime::FnCall,
585 fn_sig,
586 );
587 let fn_sig = self.normalize(call_expr.span, Unnormalized::new_wip(fn_sig));
588
589 self.check_argument_types(
590 call_expr.span,
591 call_expr,
592 fn_sig.inputs(),
593 fn_sig.output(),
594 expected,
595 arg_exprs,
596 fn_sig.c_variadic(),
597 TupleArgumentsFlag::DontTupleArguments,
598 def_id,
599 );
600
601 if fn_sig.abi() == rustc_abi::ExternAbi::RustCall {
602 let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
603 if let Some(ty) = fn_sig.inputs().last().copied() {
604 self.register_bound(
605 ty,
606 self.tcx.require_lang_item(hir::LangItem::Tuple, sp),
607 self.cause(sp, ObligationCauseCode::RustCall),
608 );
609 self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
610 } else {
611 self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
612 }
613 }
614
615 fn_sig.output()
616 }
617
618 fn suggest_call_as_method(
621 &self,
622 diag: &mut Diag<'_>,
623 segment: &'tcx hir::PathSegment<'tcx>,
624 arg_exprs: &'tcx [hir::Expr<'tcx>],
625 call_expr: &'tcx hir::Expr<'tcx>,
626 expected: Expectation<'tcx>,
627 ) {
628 if let [callee_expr, rest @ ..] = arg_exprs {
629 let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
630 else {
631 return;
632 };
633
634 let Ok(pick) = self.lookup_probe_for_diagnostic(
638 segment.ident,
639 callee_ty,
640 call_expr,
641 ProbeScope::AllTraits,
644 expected.only_has_type(self),
645 ) else {
646 return;
647 };
648
649 let pick = self.confirm_method_for_diagnostic(
650 call_expr.span,
651 callee_expr,
652 call_expr,
653 callee_ty,
654 &pick,
655 segment,
656 );
657 if pick.illegal_sized_bound.is_some() {
658 return;
659 }
660
661 let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
662 else {
663 return;
664 };
665 let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
666 let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
667 let rest_snippet = if let Some(first) = rest.first() {
668 self.tcx
669 .sess
670 .source_map()
671 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
672 } else {
673 Ok(")".to_string())
674 };
675
676 if let Ok(rest_snippet) = rest_snippet {
677 let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
678 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(up_to_rcvr_span, "".to_string()),
(rest_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(".{0}({1}", segment.ident,
rest_snippet))
}))]))vec![
679 (up_to_rcvr_span, "".to_string()),
680 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
681 ]
682 } else {
683 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(up_to_rcvr_span, "(".to_string()),
(rest_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(").{0}({1}",
segment.ident, rest_snippet))
}))]))vec![
684 (up_to_rcvr_span, "(".to_string()),
685 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
686 ]
687 };
688 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
689 diag.multipart_suggestion(
690 ::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!(
691 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
692 self.tcx
693 .associated_item(pick.callee.def_id)
694 .trait_container(self.tcx)
695 .map_or_else(
696 || String::new(),
697 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
698 ),
699 segment.ident
700 ),
701 sugg,
702 Applicability::MaybeIncorrect,
703 );
704 }
705 }
706 }
707
708 fn report_invalid_callee(
709 &self,
710 call_expr: &'tcx hir::Expr<'tcx>,
711 callee_expr: &'tcx hir::Expr<'tcx>,
712 callee_ty: Ty<'tcx>,
713 arg_exprs: &'tcx [hir::Expr<'tcx>],
714 ) -> ErrorGuaranteed {
715 if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
718 && let Err(err) = args.error_reported()
719 {
720 return err;
721 }
722
723 let mut unit_variant = None;
724 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
725 && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
726 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
727 && arg_exprs.is_empty()
729 && call_expr.span.contains(callee_expr.span)
730 {
731 let descr = match kind {
732 def::CtorOf::Struct => "struct",
733 def::CtorOf::Variant => "enum variant",
734 };
735 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
736 unit_variant =
737 Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
738 }
739
740 let callee_ty = self.resolve_vars_if_possible(callee_ty);
741 let mut path = None;
742 let mut err = self.dcx().create_err(errors::InvalidCallee {
743 span: callee_expr.span,
744 ty: callee_ty,
745 found: match &unit_variant {
746 Some((_, kind, path)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind, path))
})format!("{kind} `{path}`"),
747 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)),
748 },
749 });
750 *err.long_ty_path() = path;
751 if callee_ty.references_error() {
752 err.downgrade_to_delayed_bug();
753 }
754
755 self.identify_bad_closure_def_and_call(
756 &mut err,
757 call_expr.hir_id,
758 &callee_expr.kind,
759 callee_expr.span,
760 );
761
762 if let Some((removal_span, kind, path)) = &unit_variant {
763 err.span_suggestion_verbose(
764 *removal_span,
765 ::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!(
766 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
767 ),
768 "",
769 Applicability::MachineApplicable,
770 );
771 }
772
773 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
774 && let Res::Local(_) = path.res
775 && let [segment] = &path.segments
776 {
777 for id in self.tcx.hir_free_items() {
778 if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
779 && let hir::Node::Item(item) = node
780 && let hir::ItemKind::Fn { ident, .. } = item.kind
781 && ident.name == segment.ident.name
782 {
783 err.span_label(
784 self.tcx.def_span(id.owner_id),
785 "this function of the same name is available here, but it's shadowed by \
786 the local binding",
787 );
788 }
789 }
790 }
791
792 let mut inner_callee_path = None;
793 let def = match callee_expr.kind {
794 hir::ExprKind::Path(ref qpath) => {
795 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
796 }
797 hir::ExprKind::Call(inner_callee, _) => {
798 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
799 inner_callee_path = Some(inner_qpath);
800 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
801 } else {
802 Res::Err
803 }
804 }
805 _ => Res::Err,
806 };
807
808 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
809 let call_is_multiline = self
813 .tcx
814 .sess
815 .source_map()
816 .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
817 && call_expr.span.eq_ctxt(callee_expr.span);
818 if call_is_multiline {
819 err.span_suggestion(
820 callee_expr.span.shrink_to_hi(),
821 "consider using a semicolon here to finish the statement",
822 ";",
823 Applicability::MaybeIncorrect,
824 );
825 }
826 if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
827 && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
828 {
829 let descr = match maybe_def {
830 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
831 DefIdOrName::Name(name) => name,
832 };
833 err.span_label(
834 callee_expr.span,
835 ::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")
836 );
837 if let DefIdOrName::DefId(def_id) = maybe_def
838 && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
839 {
840 err.span_label(def_span, "the callable type is defined here");
841 }
842 } else {
843 err.span_label(call_expr.span, "call expression requires function");
844 }
845 }
846
847 if let Some(span) = self.tcx.hir_res_span(def) {
848 let callee_ty = callee_ty.to_string();
849 let label = match (unit_variant, inner_callee_path) {
850 (Some((_, kind, path)), _) => {
851 err.arg("kind", kind);
852 err.arg("path", path);
853 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$kind} `{$path}` defined here"))msg!("{$kind} `{$path}` defined here"))
854 }
855 (_, Some(hir::QPath::Resolved(_, path))) => {
856 self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
857 err.arg("func", p);
858 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$func}` defined here returns `{$ty}`"))msg!("`{$func}` defined here returns `{$ty}`")
859 })
860 }
861 _ => {
862 match def {
863 Res::Local(hir_id) => {
866 err.arg("local_name", self.tcx.hir_name(hir_id));
867 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$local_name}` has type `{$ty}`"))msg!("`{$local_name}` has type `{$ty}`"))
868 }
869 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
870 err.arg("path", self.tcx.def_path_str(def_id));
871 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
872 }
873 _ => {
874 err.arg("path", callee_ty);
875 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
876 }
877 }
878 }
879 };
880 if let Some(label) = label {
881 err.span_label(span, label);
882 }
883 }
884 err.emit()
885 }
886
887 fn confirm_deferred_closure_call(
888 &self,
889 call_expr: &'tcx hir::Expr<'tcx>,
890 arg_exprs: &'tcx [hir::Expr<'tcx>],
891 expected: Expectation<'tcx>,
892 closure_def_id: LocalDefId,
893 fn_sig: ty::FnSig<'tcx>,
894 ) -> Ty<'tcx> {
895 self.check_argument_types(
900 call_expr.span,
901 call_expr,
902 fn_sig.inputs(),
903 fn_sig.output(),
904 expected,
905 arg_exprs,
906 fn_sig.c_variadic(),
907 TupleArgumentsFlag::TupleArguments,
908 Some(closure_def_id.to_def_id()),
909 );
910
911 fn_sig.output()
912 }
913
914 #[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(914u32),
::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 &&
{
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(self.body_id,
&self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDoNotConstCheck) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some() {
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).skip_norm_wip()));
}
} else {}
}
}
}#[tracing::instrument(level = "debug", skip(self, span))]
915 pub(super) fn enforce_context_effects(
916 &self,
917 call_hir_id: Option<HirId>,
918 span: Span,
919 callee_did: DefId,
920 callee_args: GenericArgsRef<'tcx>,
921 ) {
922 if !self.tcx.features().const_trait_impl() {
927 return;
928 }
929
930 if self.has_rustc_attrs && find_attr!(self.tcx, self.body_id, RustcDoNotConstCheck) {
932 return;
933 }
934
935 let host = match self.tcx.hir_body_const_context(self.body_id) {
936 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
937 ty::BoundConstness::Const
938 }
939 Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
940 None => return,
941 };
942
943 if self.tcx.is_conditionally_const(callee_did) {
946 let q = self.tcx.const_conditions(callee_did);
947 for (idx, (cond, pred_span)) in
948 q.instantiate(self.tcx, callee_args).into_iter().enumerate()
949 {
950 let cause = self.cause(
951 span,
952 if let Some(hir_id) = call_hir_id {
953 ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
954 } else {
955 ObligationCauseCode::WhereClause(callee_did, pred_span)
956 },
957 );
958 self.register_predicate(Obligation::new(
959 self.tcx,
960 cause,
961 self.param_env,
962 cond.to_host_effect_clause(self.tcx, host).skip_norm_wip(),
963 ));
964 }
965 } else {
966 }
969 }
970
971 fn confirm_overloaded_call(
972 &self,
973 call_expr: &'tcx hir::Expr<'tcx>,
974 arg_exprs: &'tcx [hir::Expr<'tcx>],
975 expected: Expectation<'tcx>,
976 method: MethodCallee<'tcx>,
977 ) -> Ty<'tcx> {
978 self.check_argument_types(
979 call_expr.span,
980 call_expr,
981 &method.sig.inputs()[1..],
982 method.sig.output(),
983 expected,
984 arg_exprs,
985 method.sig.c_variadic(),
986 TupleArgumentsFlag::TupleArguments,
987 Some(method.def_id),
988 );
989
990 self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
991
992 method.sig.output()
993 }
994}
995
996#[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)]
997pub(crate) struct DeferredCallResolution<'tcx> {
998 call_expr: &'tcx hir::Expr<'tcx>,
999 callee_expr: &'tcx hir::Expr<'tcx>,
1000 closure_ty: Ty<'tcx>,
1001 adjustments: Vec<Adjustment<'tcx>>,
1002 fn_sig: ty::FnSig<'tcx>,
1003}
1004
1005impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1006 pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1007 {
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:1007",
"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(1007u32),
::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);
1008
1009 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());
1012
1013 match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1015 Some((autoref, method_callee)) => {
1016 let method_sig = method_callee.sig;
1025
1026 {
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:1026",
"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(1026u32),
::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);
1027
1028 for (method_arg_ty, self_arg_ty) in
1029 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1030 {
1031 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1032 }
1033
1034 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1035
1036 let mut adjustments = self.adjustments;
1037 adjustments.extend(autoref);
1038 fcx.apply_adjustments(self.callee_expr, adjustments);
1039
1040 fcx.write_method_call_and_enforce_effects(
1041 self.call_expr.hir_id,
1042 self.call_expr.span,
1043 method_callee,
1044 );
1045 }
1046 None => {
1047 ::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!(
1048 self.call_expr.span,
1049 "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1050 self.closure_ty
1051 )
1052 }
1053 }
1054 }
1055}