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};
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_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 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 =
215 self.try_structurally_resolve_type(autoderef.span(), autoderef.final_ty());
216
217 match *adjusted_ty.kind() {
219 ty::FnDef(..) | ty::FnPtr(..) => {
220 let adjustments = self.adjust_steps(autoderef);
221 self.apply_adjustments(callee_expr, adjustments);
222 return Some(CallStep::Builtin(adjusted_ty));
223 }
224
225 ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
229 let def_id = def_id.expect_local();
230 let closure_sig = args.as_closure().sig();
231 let closure_sig = self.instantiate_binder_with_fresh_vars(
232 call_expr.span,
233 BoundRegionConversionTime::FnCall,
234 closure_sig,
235 );
236 let adjustments = self.adjust_steps(autoderef);
237 self.record_deferred_call_resolution(
238 def_id,
239 DeferredCallResolution {
240 call_expr,
241 callee_expr,
242 closure_ty: adjusted_ty,
243 adjustments,
244 fn_sig: closure_sig,
245 },
246 );
247 return Some(CallStep::DeferredClosure(def_id, closure_sig));
248 }
249
250 ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
256 let def_id = def_id.expect_local();
257 let closure_args = args.as_coroutine_closure();
258 let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
259 call_expr.span,
260 BoundRegionConversionTime::FnCall,
261 closure_args.coroutine_closure_sig(),
262 );
263 let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
264 let kind_ty = self.next_ty_var(callee_expr.span);
269 let call_sig = self.tcx.mk_fn_sig(
270 [coroutine_closure_sig.tupled_inputs_ty],
271 coroutine_closure_sig.to_coroutine(
272 self.tcx,
273 closure_args.parent_args(),
274 kind_ty,
275 self.tcx.coroutine_for_closure(def_id),
276 tupled_upvars_ty,
277 ),
278 coroutine_closure_sig.c_variadic,
279 coroutine_closure_sig.safety,
280 coroutine_closure_sig.abi,
281 );
282 let adjustments = self.adjust_steps(autoderef);
283 self.record_deferred_call_resolution(
284 def_id,
285 DeferredCallResolution {
286 call_expr,
287 callee_expr,
288 closure_ty: adjusted_ty,
289 adjustments,
290 fn_sig: call_sig,
291 },
292 );
293 return Some(CallStep::DeferredClosure(def_id, call_sig));
294 }
295
296 ty::Ref(..) if autoderef.step_count() == 0 => {
309 return None;
310 }
311
312 ty::Infer(ty::TyVar(vid)) => {
313 if !self.has_opaques_with_sub_unified_hidden_type(vid) {
316 self.type_must_be_known_at_this_point(autoderef.span(), adjusted_ty);
317 return None;
318 }
319 }
320
321 ty::Error(_) => {
322 return None;
323 }
324
325 _ => {}
326 }
327
328 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
336 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
337 .map(|(autoref, method)| {
338 let mut adjustments = self.adjust_steps(autoderef);
339 adjustments.extend(autoref);
340 self.apply_adjustments(callee_expr, adjustments);
341 CallStep::Overloaded(method)
342 })
343 }
344
345 fn try_overloaded_call_traits(
346 &self,
347 call_expr: &hir::Expr<'_>,
348 adjusted_ty: Ty<'tcx>,
349 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
350 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
351 let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
364 [
365 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
366 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
367 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
368 (self.tcx.lang_items().fn_trait(), sym::call, true),
369 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
370 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
371 ]
372 } else {
373 [
374 (self.tcx.lang_items().fn_trait(), sym::call, true),
375 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
376 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
377 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
378 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
379 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
380 ]
381 };
382
383 for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
385 let Some(trait_def_id) = opt_trait_def_id else { continue };
386
387 let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
388 Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
389 });
390
391 if let Some(ok) = self.lookup_method_for_operator(
398 self.misc(call_expr.span),
399 method_name,
400 trait_def_id,
401 adjusted_ty,
402 opt_input_type,
403 TreatNotYetDefinedOpaques::AsRigid,
404 ) {
405 let method = self.register_infer_ok_obligations(ok);
406 let mut autoref = None;
407 if borrow {
408 let ty::Ref(_, _, mutbl) = *method.sig.inputs()[0].kind() else {
411 ::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")
412 };
413
414 let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::No);
418
419 autoref = Some(Adjustment {
420 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
421 target: method.sig.inputs()[0],
422 });
423 }
424
425 return Some((autoref, method));
426 }
427 }
428
429 None
430 }
431
432 fn is_scalable_vector_ctor(&self, callee_ty: Ty<'_>) -> bool {
433 if let ty::FnDef(def_id, _) = *callee_ty.kind()
434 && let def::DefKind::Ctor(def::CtorOf::Struct, _) = self.tcx.def_kind(def_id)
435 {
436 self.tcx
437 .opt_parent(def_id)
438 .and_then(|id| self.tcx.adt_def(id).repr().scalable)
439 .is_some()
440 } else {
441 false
442 }
443 }
444
445 fn identify_bad_closure_def_and_call(
448 &self,
449 err: &mut Diag<'_>,
450 hir_id: hir::HirId,
451 callee_node: &hir::ExprKind<'_>,
452 callee_span: Span,
453 ) {
454 let hir::ExprKind::Block(..) = callee_node else {
455 return;
457 };
458
459 let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
460 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
461 ..
462 }) = self.tcx.parent_hir_node(hir_id)
463 {
464 fn_decl_span
465 } else if let Some((
466 _,
467 hir::Node::Expr(&hir::Expr {
468 hir_id: parent_hir_id,
469 kind:
470 hir::ExprKind::Closure(&hir::Closure {
471 kind:
472 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
473 hir::CoroutineDesugaring::Async,
474 hir::CoroutineSource::Closure,
475 )),
476 ..
477 }),
478 ..
479 }),
480 )) = self.tcx.hir_parent_iter(hir_id).nth(3)
481 {
482 let hir::Node::Expr(&hir::Expr {
485 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
486 ..
487 }) = self.tcx.parent_hir_node(parent_hir_id)
488 else {
489 return;
490 };
491 fn_decl_span
492 } else {
493 return;
494 };
495
496 let start = fn_decl_span.shrink_to_lo();
497 let end = callee_span.shrink_to_hi();
498 err.multipart_suggestion(
499 "if you meant to create this closure and immediately call it, surround the \
500 closure with parentheses",
501 ::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())],
502 Applicability::MaybeIncorrect,
503 );
504 }
505
506 fn maybe_suggest_bad_array_definition(
509 &self,
510 err: &mut Diag<'_>,
511 call_expr: &'tcx hir::Expr<'tcx>,
512 callee_expr: &'tcx hir::Expr<'tcx>,
513 ) -> bool {
514 let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
515 if let (
516 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
517 hir::ExprKind::Tup(exp),
518 hir::ExprKind::Call(_, args),
519 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
520 && args.len() == exp.len()
521 {
522 let start = callee_expr.span.shrink_to_hi();
523 err.span_suggestion(
524 start,
525 "consider separating array elements with a comma",
526 ",",
527 Applicability::MaybeIncorrect,
528 );
529 return true;
530 }
531 false
532 }
533
534 fn confirm_builtin_call(
535 &self,
536 call_expr: &'tcx hir::Expr<'tcx>,
537 callee_expr: &'tcx hir::Expr<'tcx>,
538 callee_ty: Ty<'tcx>,
539 arg_exprs: &'tcx [hir::Expr<'tcx>],
540 expected: Expectation<'tcx>,
541 ) -> Ty<'tcx> {
542 let (fn_sig, def_id) = match *callee_ty.kind() {
543 ty::FnDef(def_id, args) => {
544 self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
545 let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args);
546
547 if self.has_rustc_attrs && {
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(def_id) {
#[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) {
551 let predicates = self.tcx.predicates_of(def_id);
552 let predicates = predicates.instantiate(self.tcx, args);
553 for (predicate, predicate_span) in predicates {
554 let obligation = Obligation::new(
555 self.tcx,
556 ObligationCause::dummy_with_span(callee_expr.span),
557 self.param_env,
558 predicate,
559 );
560 let result = self.evaluate_obligation(&obligation);
561 self.dcx()
562 .struct_span_err(
563 callee_expr.span,
564 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("evaluate({0:?}) = {1:?}",
predicate, result))
})format!("evaluate({predicate:?}) = {result:?}"),
565 )
566 .with_span_label(predicate_span, "predicate")
567 .emit();
568 }
569 }
570 (fn_sig, Some(def_id))
571 }
572
573 ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None),
575
576 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
577 };
578
579 let fn_sig = self.instantiate_binder_with_fresh_vars(
585 call_expr.span,
586 BoundRegionConversionTime::FnCall,
587 fn_sig,
588 );
589 let fn_sig = self.normalize(call_expr.span, fn_sig);
590
591 self.check_argument_types(
592 call_expr.span,
593 call_expr,
594 fn_sig.inputs(),
595 fn_sig.output(),
596 expected,
597 arg_exprs,
598 fn_sig.c_variadic,
599 TupleArgumentsFlag::DontTupleArguments,
600 def_id,
601 );
602
603 if fn_sig.abi == rustc_abi::ExternAbi::RustCall {
604 let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
605 if let Some(ty) = fn_sig.inputs().last().copied() {
606 self.register_bound(
607 ty,
608 self.tcx.require_lang_item(hir::LangItem::Tuple, sp),
609 self.cause(sp, ObligationCauseCode::RustCall),
610 );
611 self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
612 } else {
613 self.dcx().emit_err(errors::RustCallIncorrectArgs { span: sp });
614 }
615 }
616
617 fn_sig.output()
618 }
619
620 fn suggest_call_as_method(
623 &self,
624 diag: &mut Diag<'_>,
625 segment: &'tcx hir::PathSegment<'tcx>,
626 arg_exprs: &'tcx [hir::Expr<'tcx>],
627 call_expr: &'tcx hir::Expr<'tcx>,
628 expected: Expectation<'tcx>,
629 ) {
630 if let [callee_expr, rest @ ..] = arg_exprs {
631 let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
632 else {
633 return;
634 };
635
636 let Ok(pick) = self.lookup_probe_for_diagnostic(
640 segment.ident,
641 callee_ty,
642 call_expr,
643 ProbeScope::AllTraits,
646 expected.only_has_type(self),
647 ) else {
648 return;
649 };
650
651 let pick = self.confirm_method_for_diagnostic(
652 call_expr.span,
653 callee_expr,
654 call_expr,
655 callee_ty,
656 &pick,
657 segment,
658 );
659 if pick.illegal_sized_bound.is_some() {
660 return;
661 }
662
663 let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
664 else {
665 return;
666 };
667 let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
668 let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
669 let rest_snippet = if let Some(first) = rest.first() {
670 self.tcx
671 .sess
672 .source_map()
673 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
674 } else {
675 Ok(")".to_string())
676 };
677
678 if let Ok(rest_snippet) = rest_snippet {
679 let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
680 ::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![
681 (up_to_rcvr_span, "".to_string()),
682 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
683 ]
684 } else {
685 ::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![
686 (up_to_rcvr_span, "(".to_string()),
687 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
688 ]
689 };
690 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
691 diag.multipart_suggestion(
692 ::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!(
693 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
694 self.tcx
695 .associated_item(pick.callee.def_id)
696 .trait_container(self.tcx)
697 .map_or_else(
698 || String::new(),
699 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
700 ),
701 segment.ident
702 ),
703 sugg,
704 Applicability::MaybeIncorrect,
705 );
706 }
707 }
708 }
709
710 fn report_invalid_callee(
711 &self,
712 call_expr: &'tcx hir::Expr<'tcx>,
713 callee_expr: &'tcx hir::Expr<'tcx>,
714 callee_ty: Ty<'tcx>,
715 arg_exprs: &'tcx [hir::Expr<'tcx>],
716 ) -> ErrorGuaranteed {
717 if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
720 && let Err(err) = args.error_reported()
721 {
722 return err;
723 }
724
725 let mut unit_variant = None;
726 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
727 && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
728 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
729 && arg_exprs.is_empty()
731 && call_expr.span.contains(callee_expr.span)
732 {
733 let descr = match kind {
734 def::CtorOf::Struct => "struct",
735 def::CtorOf::Variant => "enum variant",
736 };
737 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
738 unit_variant =
739 Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
740 }
741
742 let callee_ty = self.resolve_vars_if_possible(callee_ty);
743 let mut path = None;
744 let mut err = self.dcx().create_err(errors::InvalidCallee {
745 span: callee_expr.span,
746 ty: callee_ty,
747 found: match &unit_variant {
748 Some((_, kind, path)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind, path))
})format!("{kind} `{path}`"),
749 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)),
750 },
751 });
752 *err.long_ty_path() = path;
753 if callee_ty.references_error() {
754 err.downgrade_to_delayed_bug();
755 }
756
757 self.identify_bad_closure_def_and_call(
758 &mut err,
759 call_expr.hir_id,
760 &callee_expr.kind,
761 callee_expr.span,
762 );
763
764 if let Some((removal_span, kind, path)) = &unit_variant {
765 err.span_suggestion_verbose(
766 *removal_span,
767 ::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!(
768 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
769 ),
770 "",
771 Applicability::MachineApplicable,
772 );
773 }
774
775 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
776 && let Res::Local(_) = path.res
777 && let [segment] = &path.segments
778 {
779 for id in self.tcx.hir_free_items() {
780 if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
781 && let hir::Node::Item(item) = node
782 && let hir::ItemKind::Fn { ident, .. } = item.kind
783 && ident.name == segment.ident.name
784 {
785 err.span_label(
786 self.tcx.def_span(id.owner_id),
787 "this function of the same name is available here, but it's shadowed by \
788 the local binding",
789 );
790 }
791 }
792 }
793
794 let mut inner_callee_path = None;
795 let def = match callee_expr.kind {
796 hir::ExprKind::Path(ref qpath) => {
797 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
798 }
799 hir::ExprKind::Call(inner_callee, _) => {
800 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
801 inner_callee_path = Some(inner_qpath);
802 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
803 } else {
804 Res::Err
805 }
806 }
807 _ => Res::Err,
808 };
809
810 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
811 let call_is_multiline = self
815 .tcx
816 .sess
817 .source_map()
818 .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
819 && call_expr.span.eq_ctxt(callee_expr.span);
820 if call_is_multiline {
821 err.span_suggestion(
822 callee_expr.span.shrink_to_hi(),
823 "consider using a semicolon here to finish the statement",
824 ";",
825 Applicability::MaybeIncorrect,
826 );
827 }
828 if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
829 && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
830 {
831 let descr = match maybe_def {
832 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
833 DefIdOrName::Name(name) => name,
834 };
835 err.span_label(
836 callee_expr.span,
837 ::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")
838 );
839 if let DefIdOrName::DefId(def_id) = maybe_def
840 && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
841 {
842 err.span_label(def_span, "the callable type is defined here");
843 }
844 } else {
845 err.span_label(call_expr.span, "call expression requires function");
846 }
847 }
848
849 if let Some(span) = self.tcx.hir_res_span(def) {
850 let callee_ty = callee_ty.to_string();
851 let label = match (unit_variant, inner_callee_path) {
852 (Some((_, kind, path)), _) => {
853 err.arg("kind", kind);
854 err.arg("path", path);
855 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$kind} `{$path}` defined here"))msg!("{$kind} `{$path}` defined here"))
856 }
857 (_, Some(hir::QPath::Resolved(_, path))) => {
858 self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
859 err.arg("func", p);
860 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$func}` defined here returns `{$ty}`"))msg!("`{$func}` defined here returns `{$ty}`")
861 })
862 }
863 _ => {
864 match def {
865 Res::Local(hir_id) => {
868 err.arg("local_name", self.tcx.hir_name(hir_id));
869 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$local_name}` has type `{$ty}`"))msg!("`{$local_name}` has type `{$ty}`"))
870 }
871 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
872 err.arg("path", self.tcx.def_path_str(def_id));
873 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
874 }
875 _ => {
876 err.arg("path", callee_ty);
877 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
878 }
879 }
880 }
881 };
882 if let Some(label) = label {
883 err.span_label(span, label);
884 }
885 }
886 err.emit()
887 }
888
889 fn confirm_deferred_closure_call(
890 &self,
891 call_expr: &'tcx hir::Expr<'tcx>,
892 arg_exprs: &'tcx [hir::Expr<'tcx>],
893 expected: Expectation<'tcx>,
894 closure_def_id: LocalDefId,
895 fn_sig: ty::FnSig<'tcx>,
896 ) -> Ty<'tcx> {
897 self.check_argument_types(
902 call_expr.span,
903 call_expr,
904 fn_sig.inputs(),
905 fn_sig.output(),
906 expected,
907 arg_exprs,
908 fn_sig.c_variadic,
909 TupleArgumentsFlag::TupleArguments,
910 Some(closure_def_id.to_def_id()),
911 );
912
913 fn_sig.output()
914 }
915
916 #[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(916u32),
::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.has_rustc_attrs &&
{
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(self.body_id) {
#[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)));
}
} else {}
}
}
}#[tracing::instrument(level = "debug", skip(self, span))]
917 pub(super) fn enforce_context_effects(
918 &self,
919 call_hir_id: Option<HirId>,
920 span: Span,
921 callee_did: DefId,
922 callee_args: GenericArgsRef<'tcx>,
923 ) {
924 if self.has_rustc_attrs && find_attr!(self.tcx, self.body_id, RustcDoNotConstCheck) {
926 return;
927 }
928
929 let host = match self.tcx.hir_body_const_context(self.body_id) {
930 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
931 ty::BoundConstness::Const
932 }
933 Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
934 None => return,
935 };
936
937 if self.tcx.is_conditionally_const(callee_did) {
940 let q = self.tcx.const_conditions(callee_did);
941 for (idx, (cond, pred_span)) in
942 q.instantiate(self.tcx, callee_args).into_iter().enumerate()
943 {
944 let cause = self.cause(
945 span,
946 if let Some(hir_id) = call_hir_id {
947 ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
948 } else {
949 ObligationCauseCode::WhereClause(callee_did, pred_span)
950 },
951 );
952 self.register_predicate(Obligation::new(
953 self.tcx,
954 cause,
955 self.param_env,
956 cond.to_host_effect_clause(self.tcx, host),
957 ));
958 }
959 } else {
960 }
963 }
964
965 fn confirm_overloaded_call(
966 &self,
967 call_expr: &'tcx hir::Expr<'tcx>,
968 arg_exprs: &'tcx [hir::Expr<'tcx>],
969 expected: Expectation<'tcx>,
970 method: MethodCallee<'tcx>,
971 ) -> Ty<'tcx> {
972 self.check_argument_types(
973 call_expr.span,
974 call_expr,
975 &method.sig.inputs()[1..],
976 method.sig.output(),
977 expected,
978 arg_exprs,
979 method.sig.c_variadic,
980 TupleArgumentsFlag::TupleArguments,
981 Some(method.def_id),
982 );
983
984 self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
985
986 method.sig.output()
987 }
988}
989
990#[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)]
991pub(crate) struct DeferredCallResolution<'tcx> {
992 call_expr: &'tcx hir::Expr<'tcx>,
993 callee_expr: &'tcx hir::Expr<'tcx>,
994 closure_ty: Ty<'tcx>,
995 adjustments: Vec<Adjustment<'tcx>>,
996 fn_sig: ty::FnSig<'tcx>,
997}
998
999impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1000 pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1001 {
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:1001",
"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(1001u32),
::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);
1002
1003 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());
1006
1007 match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1009 Some((autoref, method_callee)) => {
1010 let method_sig = method_callee.sig;
1019
1020 {
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:1020",
"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(1020u32),
::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);
1021
1022 for (method_arg_ty, self_arg_ty) in
1023 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1024 {
1025 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1026 }
1027
1028 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1029
1030 let mut adjustments = self.adjustments;
1031 adjustments.extend(autoref);
1032 fcx.apply_adjustments(self.callee_expr, adjustments);
1033
1034 fcx.write_method_call_and_enforce_effects(
1035 self.call_expr.hir_id,
1036 self.call_expr.span,
1037 method_callee,
1038 );
1039 }
1040 None => {
1041 ::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!(
1042 self.call_expr.span,
1043 "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1044 self.closure_ty
1045 )
1046 }
1047 }
1048 }
1049}