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