1use std::iter;
2
3use rustc_abi::{CanonAbi, ExternAbi};
4use rustc_ast::util::parser::ExprPrecedence;
5use rustc_attr_ir::find_attr;
6use rustc_attr_ir::lang_items::LangItem;
7use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
8use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey, msg};
9use rustc_hir::def::{self, CtorKind, Namespace, Res};
10use rustc_hir::def_id::DefId;
11use rustc_hir::{self as hir, HirId};
12use rustc_hir_analysis::autoderef::Autoderef;
13use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes};
14use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode, WellFormedLoc};
15use rustc_middle::ty::adjustment::{
16 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
17};
18use rustc_middle::ty::{self, FnSig, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
19use rustc_span::def_id::LocalDefId;
20use rustc_span::{Ident, Span, bug, sym};
21use rustc_target::spec::{AbiMap, AbiMapping};
22use rustc_trait_selection::error_reporting::traits::DefIdOrName;
23use rustc_trait_selection::infer::InferCtxtExt as _;
24use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
25use tracing::{debug, instrument};
26
27use super::method::MethodCallee;
28use super::method::probe::ProbeScope;
29use super::{Expectation, FnCtxt, TupleArgumentsFlag};
30use crate::diagnostics;
31use crate::method::TreatNotYetDefinedOpaques;
32use crate::method::confirm::ConfirmContext;
33use crate::method::probe::{IsSuggestion, Mode};
34
35#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SplatLoweringInfo<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::FnDef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "FnDef",
&__self_0),
Self::FnPtr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "FnPtr",
&__self_0),
Self::Error(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Error",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for SplatLoweringInfo<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for SplatLoweringInfo<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SplatLoweringInfo<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for SplatLoweringInfo<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<DefId>;
let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
let _: ::core::cmp::AssertParamIsEq<ErrorGuaranteed>;
}
}Eq, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for SplatLoweringInfo<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for SplatLoweringInfo<'tcx> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::FnDef(__self_0), Self::FnDef(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::FnPtr(__self_0), Self::FnPtr(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Error(__self_0), Self::Error(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq)]
37pub(crate) enum SplatLoweringInfo<'tcx> {
38 FnDef(DefId),
41 FnPtr(Ty<'tcx>),
43 Error(ErrorGuaranteed),
45}
46
47pub(crate) fn check_legal_trait_for_method_call(
51 tcx: TyCtxt<'_>,
52 span: Span,
53 receiver: Option<Span>,
54 expr_span: Span,
55 trait_id: DefId,
56 body_def_id: DefId,
57) -> Result<(), ErrorGuaranteed> {
58 if tcx.is_lang_item(trait_id, LangItem::Drop)
59 && !tcx.is_lang_item(tcx.parent(body_def_id), LangItem::Drop)
61 {
62 let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
63 diagnostics::ExplicitDestructorCallSugg::Snippet {
64 lo: expr_span.shrink_to_lo().to(receiver.shrink_to_lo()),
65 hi: receiver.shrink_to_hi().to(expr_span.shrink_to_hi()),
66 }
67 } else {
68 diagnostics::ExplicitDestructorCallSugg::Empty(span)
69 };
70 return Err(tcx.dcx().emit_err(diagnostics::ExplicitDestructorCall { span, sugg }));
71 }
72 tcx.ensure_result().coherent_trait(trait_id)
73}
74
75#[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 {
Self::Builtin(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Builtin", &__self_0),
Self::DeferredClosure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"DeferredClosure", __self_0, &__self_1),
Self::Overloaded(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Overloaded", &__self_0),
}
}
}Debug)]
77enum CallStep<'tcx> {
78 Builtin(Ty<'tcx>),
81 DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
83 Overloaded(MethodCallee<'tcx>),
85}
86
87impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
88 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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("check_expr_call",
"rustc_hir_typeck::callee", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(88u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("call_expr")
}> =
::tracing::__macro_support::FieldName::new("call_expr");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("callee_expr")
}> =
::tracing::__macro_support::FieldName::new("callee_expr");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("arg_exprs")
}> =
::tracing::__macro_support::FieldName::new("arg_exprs");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_expr)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_expr)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_exprs)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::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: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let original_callee_ty =
match &callee_expr.kind {
hir::ExprKind::Path(hir::QPath::Resolved(..) |
hir::QPath::TypeRelative(..)) =>
self.check_expr_with_expectation_and_args(callee_expr,
Expectation::NoExpectation, Some((call_expr, arg_exprs))),
_ => self.check_expr(callee_expr),
};
let expr_ty =
self.deeply_resolve_ignoring_regions_with_obligations(original_callee_ty);
let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
let mut result = None;
while result.is_none() && autoderef.next().is_some() {
result =
self.try_overloaded_call_step(call_expr, callee_expr,
arg_exprs, &autoderef);
}
match *autoderef.final_ty().kind() {
ty::FnDef(def_id, _) => {
let abi =
self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi();
self.check_call_abi(abi, call_expr.span);
}
ty::FnPtr(_, header) => {
self.check_call_abi(header.abi(), call_expr.span);
}
_ => {}
}
if self.is_scalable_vector_ctor(autoderef.final_ty()) {
let mut err =
self.dcx().create_err(diagnostics::ScalableVectorCtor {
span: callee_expr.span,
ty: autoderef.final_ty(),
});
err.span_label(callee_expr.span,
"you can create scalable vectors using intrinsics");
Ty::new_error(self.tcx, err.emit_err());
}
self.register_predicates(autoderef.into_obligations());
let output =
match result {
None => {
for arg in arg_exprs { self.check_expr(arg); }
if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) =
&callee_expr.kind && let [segment] = path.segments {
self.dcx().try_steal_modify_and_emit_err(segment.ident.span,
StashKey::CallIntoMethod,
|err|
{
self.suggest_call_as_method(err, segment, arg_exprs,
call_expr, expected);
});
}
let guar =
self.report_invalid_callee(call_expr, callee_expr, expr_ty,
arg_exprs);
Ty::new_error(self.tcx, guar)
}
Some(CallStep::Builtin(callee_ty)) => {
self.confirm_builtin_call(call_expr, callee_expr, callee_ty,
arg_exprs, expected)
}
Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
self.confirm_deferred_closure_call(call_expr, arg_exprs,
expected, def_id, fn_sig)
}
Some(CallStep::Overloaded(method_callee)) => {
self.confirm_overloaded_call(call_expr, arg_exprs, expected,
method_callee)
}
};
self.register_wf_obligation(output.into(), call_expr.span,
ObligationCauseCode::WellFormed(WellFormedLoc::HirId(call_expr.hir_id)));
output
}
}
}#[tracing::instrument(skip(self))]
89 pub(crate) fn check_expr_call(
90 &self,
91 call_expr: &'tcx hir::Expr<'tcx>,
92 callee_expr: &'tcx hir::Expr<'tcx>,
93 arg_exprs: &'tcx [hir::Expr<'tcx>],
94 expected: Expectation<'tcx>,
95 ) -> Ty<'tcx> {
96 let original_callee_ty = match &callee_expr.kind {
97 hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
98 .check_expr_with_expectation_and_args(
99 callee_expr,
100 Expectation::NoExpectation,
101 Some((call_expr, arg_exprs)),
102 ),
103 _ => self.check_expr(callee_expr),
104 };
105
106 let expr_ty = self.deeply_resolve_ignoring_regions_with_obligations(original_callee_ty);
107
108 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
109 let mut result = None;
110 while result.is_none() && autoderef.next().is_some() {
111 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
112 }
113
114 match *autoderef.final_ty().kind() {
115 ty::FnDef(def_id, _) => {
116 let abi = self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi();
117 self.check_call_abi(abi, call_expr.span);
118 }
119 ty::FnPtr(_, header) => {
120 self.check_call_abi(header.abi(), call_expr.span);
121 }
122 _ => { }
123 }
124
125 if self.is_scalable_vector_ctor(autoderef.final_ty()) {
126 let mut err = self.dcx().create_err(diagnostics::ScalableVectorCtor {
127 span: callee_expr.span,
128 ty: autoderef.final_ty(),
129 });
130 err.span_label(callee_expr.span, "you can create scalable vectors using intrinsics");
131 Ty::new_error(self.tcx, err.emit_err());
132 }
133
134 self.register_predicates(autoderef.into_obligations());
135
136 let output = match result {
137 None => {
138 for arg in arg_exprs {
141 self.check_expr(arg);
142 }
143
144 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
145 && let [segment] = path.segments
146 {
147 self.dcx().try_steal_modify_and_emit_err(
148 segment.ident.span,
149 StashKey::CallIntoMethod,
150 |err| {
151 self.suggest_call_as_method(
153 err, segment, arg_exprs, call_expr, expected,
154 );
155 },
156 );
157 }
158
159 let guar = self.report_invalid_callee(call_expr, callee_expr, expr_ty, arg_exprs);
160 Ty::new_error(self.tcx, guar)
161 }
162
163 Some(CallStep::Builtin(callee_ty)) => {
164 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
165 }
166
167 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
168 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
169 }
170
171 Some(CallStep::Overloaded(method_callee)) => {
172 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
173 }
174 };
175
176 self.register_wf_obligation(
178 output.into(),
179 call_expr.span,
180 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(call_expr.hir_id)),
181 );
182
183 output
184 }
185
186 pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span) {
191 let canon_abi = match AbiMap::from_target(&self.sess().target).canonize_abi(abi, false) {
192 AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => canon_abi,
193 AbiMapping::Invalid => {
194 let guar = self.dcx().span_delayed_bug(
197 span,
198 ::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}"),
199 );
200 self.set_tainted_by_errors(guar);
201 return;
202 }
203 };
204
205 match canon_abi {
206 CanonAbi::Custom
208 | CanonAbi::Interrupt(_) => {
211 let err = crate::diagnostics::AbiCannotBeCalled { span, abi };
212 self.tcx.dcx().emit_err(err);
213 }
214
215 CanonAbi::GpuKernel => {
217 let err = crate::diagnostics::GpuKernelAbiCannotBeCalled { span };
218 self.tcx.dcx().emit_err(err);
219 }
220
221 CanonAbi::C
222 | CanonAbi::Rust
223 | CanonAbi::RustCold
224 | CanonAbi::RustPreserveNone
225 | CanonAbi::RustTail
226 | CanonAbi::Swift
227 | CanonAbi::Arm(_)
228 | CanonAbi::X86(_) => {}
229 }
230 }
231
232 {}
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("try_overloaded_call_step",
"rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(232u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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: Option<CallStep<'tcx>> =
loop {};
return __tracing_attr_fake_return;
}
{
let adjusted_ty =
self.deeply_resolve_ignoring_regions_with_obligations(autoderef.final_ty());
match *adjusted_ty.kind() {
ty::FnDef(..) | ty::FnPtr(..) => {
let adjustments = self.adjust_steps(autoderef);
self.apply_adjustments(callee_expr, adjustments);
return Some(CallStep::Builtin(adjusted_ty));
}
ty::Closure(def_id, args) if
self.closure_kind(adjusted_ty).is_none() => {
let def_id = def_id.expect_local();
let closure_sig = args.as_closure().sig();
let closure_sig =
self.instantiate_binder_with_fresh_vars(call_expr.span,
BoundRegionConversionTime::FnCall, closure_sig);
let adjustments = self.adjust_steps(autoderef);
self.record_deferred_call_resolution(def_id,
DeferredCallResolution {
call_expr,
callee_expr,
closure_ty: adjusted_ty,
adjustments,
fn_sig: closure_sig,
});
return Some(CallStep::DeferredClosure(def_id, closure_sig));
}
ty::CoroutineClosure(def_id, args) if
self.closure_kind(adjusted_ty).is_none() => {
let def_id = def_id.expect_local();
let closure_args = args.as_coroutine_closure();
let coroutine_closure_sig =
self.instantiate_binder_with_fresh_vars(call_expr.span,
BoundRegionConversionTime::FnCall,
closure_args.coroutine_closure_sig());
let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
let kind_ty = self.next_ty_var(callee_expr.span);
let call_sig =
self.tcx.mk_fn_sig([coroutine_closure_sig.tupled_inputs_ty],
coroutine_closure_sig.to_coroutine(self.tcx,
closure_args.parent_args(), kind_ty,
self.tcx.coroutine_for_closure(def_id), tupled_upvars_ty),
coroutine_closure_sig.fn_sig_kind);
let adjustments = self.adjust_steps(autoderef);
self.record_deferred_call_resolution(def_id,
DeferredCallResolution {
call_expr,
callee_expr,
closure_ty: adjusted_ty,
adjustments,
fn_sig: call_sig,
});
return Some(CallStep::DeferredClosure(def_id, call_sig));
}
ty::Ref(..) if autoderef.step_count() == 0 => {
return None;
}
ty::Infer(ty::TyVar(vid)) => {
if !self.has_opaques_with_sub_unified_hidden_type(vid) {
self.type_must_be_known_at_this_point(autoderef.span(),
adjusted_ty);
return None;
}
}
ty::Error(_) => { return None; }
_ => {}
}
self.try_overloaded_call_traits(call_expr, adjusted_ty,
Some(arg_exprs)).or_else(||
self.try_overloaded_call_traits(call_expr, adjusted_ty,
None)).map(|(autoref, method)|
{
let mut adjustments = self.adjust_steps(autoderef);
adjustments.extend(autoref);
self.apply_adjustments(callee_expr, adjustments);
CallStep::Overloaded(method)
})
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs:232",
"rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(232u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
233 fn try_overloaded_call_step(
234 &self,
235 call_expr: &'tcx hir::Expr<'tcx>,
236 callee_expr: &'tcx hir::Expr<'tcx>,
237 arg_exprs: &'tcx [hir::Expr<'tcx>],
238 autoderef: &Autoderef<'a, 'tcx>,
239 ) -> Option<CallStep<'tcx>> {
240 let adjusted_ty =
241 self.deeply_resolve_ignoring_regions_with_obligations(autoderef.final_ty());
242
243 match *adjusted_ty.kind() {
245 ty::FnDef(..) | ty::FnPtr(..) => {
246 let adjustments = self.adjust_steps(autoderef);
247 self.apply_adjustments(callee_expr, adjustments);
248 return Some(CallStep::Builtin(adjusted_ty));
249 }
250
251 ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
255 let def_id = def_id.expect_local();
256 let closure_sig = args.as_closure().sig();
257 let closure_sig = self.instantiate_binder_with_fresh_vars(
258 call_expr.span,
259 BoundRegionConversionTime::FnCall,
260 closure_sig,
261 );
262 let adjustments = self.adjust_steps(autoderef);
263 self.record_deferred_call_resolution(
264 def_id,
265 DeferredCallResolution {
266 call_expr,
267 callee_expr,
268 closure_ty: adjusted_ty,
269 adjustments,
270 fn_sig: closure_sig,
271 },
272 );
273 return Some(CallStep::DeferredClosure(def_id, closure_sig));
274 }
275
276 ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
282 let def_id = def_id.expect_local();
283 let closure_args = args.as_coroutine_closure();
284 let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
285 call_expr.span,
286 BoundRegionConversionTime::FnCall,
287 closure_args.coroutine_closure_sig(),
288 );
289 let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
290 let kind_ty = self.next_ty_var(callee_expr.span);
295 let call_sig = self.tcx.mk_fn_sig(
296 [coroutine_closure_sig.tupled_inputs_ty],
297 coroutine_closure_sig.to_coroutine(
298 self.tcx,
299 closure_args.parent_args(),
300 kind_ty,
301 self.tcx.coroutine_for_closure(def_id),
302 tupled_upvars_ty,
303 ),
304 coroutine_closure_sig.fn_sig_kind,
305 );
306 let adjustments = self.adjust_steps(autoderef);
307 self.record_deferred_call_resolution(
308 def_id,
309 DeferredCallResolution {
310 call_expr,
311 callee_expr,
312 closure_ty: adjusted_ty,
313 adjustments,
314 fn_sig: call_sig,
315 },
316 );
317 return Some(CallStep::DeferredClosure(def_id, call_sig));
318 }
319
320 ty::Ref(..) if autoderef.step_count() == 0 => {
333 return None;
334 }
335
336 ty::Infer(ty::TyVar(vid)) => {
337 if !self.has_opaques_with_sub_unified_hidden_type(vid) {
340 self.type_must_be_known_at_this_point(autoderef.span(), adjusted_ty);
341 return None;
342 }
343 }
344
345 ty::Error(_) => {
346 return None;
347 }
348
349 _ => {}
350 }
351
352 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
360 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
361 .map(|(autoref, method)| {
362 let mut adjustments = self.adjust_steps(autoderef);
363 adjustments.extend(autoref);
364 self.apply_adjustments(callee_expr, adjustments);
365 CallStep::Overloaded(method)
366 })
367 }
368
369 fn try_overloaded_call_traits(
370 &self,
371 call_expr: &hir::Expr<'_>,
372 adjusted_ty: Ty<'tcx>,
373 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
374 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
375 let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
388 [
389 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
390 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
391 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
392 (self.tcx.lang_items().fn_trait(), sym::call, true),
393 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
394 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
395 ]
396 } else {
397 [
398 (self.tcx.lang_items().fn_trait(), sym::call, true),
399 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
400 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
401 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
402 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
403 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
404 ]
405 };
406
407 for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
409 let Some(trait_def_id) = opt_trait_def_id else { continue };
410
411 let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
412 Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
413 });
414
415 if let Some(ok) = self.lookup_method_for_operator(
422 self.misc(call_expr.span),
423 method_name,
424 trait_def_id,
425 adjusted_ty,
426 opt_input_type,
427 TreatNotYetDefinedOpaques::AsRigid,
428 ) {
429 let method = self.register_infer_ok_obligations(ok);
430 let mut autoref = None;
431 if borrow {
432 let ty::Ref(_, _, mutbl) = *method.sig.inputs()[0].kind() else {
435 ::rustc_span::macros::bug_impl(None,
format_args!("Expected `FnMut`/`Fn` to take receiver by-ref/by-mut"),
Location::caller())bug!("Expected `FnMut`/`Fn` to take receiver by-ref/by-mut")
436 };
437
438 let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::No);
442
443 autoref = Some(Adjustment {
444 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
445 target: method.sig.inputs()[0],
446 });
447 }
448
449 return Some((autoref, method));
450 }
451 }
452
453 None
454 }
455
456 fn is_scalable_vector_ctor(&self, callee_ty: Ty<'_>) -> bool {
457 if let ty::FnDef(def_id, _) = *callee_ty.kind()
458 && let def::DefKind::Ctor(def::CtorOf::Struct, _) = self.tcx.def_kind(def_id)
459 {
460 self.tcx
461 .opt_parent(def_id)
462 .and_then(|id| self.tcx.adt_def(id).repr().scalable)
463 .is_some()
464 } else {
465 false
466 }
467 }
468
469 fn identify_bad_closure_def_and_call(
472 &self,
473 err: &mut Diag<'_>,
474 hir_id: hir::HirId,
475 callee_node: &hir::ExprKind<'_>,
476 callee_span: Span,
477 ) {
478 let hir::ExprKind::Block(..) = callee_node else {
479 return;
481 };
482
483 let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
484 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
485 ..
486 }) = self.tcx.parent_hir_node(hir_id)
487 {
488 fn_decl_span
489 } else if let Some((
490 _,
491 hir::Node::Expr(&hir::Expr {
492 hir_id: parent_hir_id,
493 kind:
494 hir::ExprKind::Closure(&hir::Closure {
495 kind:
496 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
497 hir::CoroutineDesugaring::Async,
498 hir::CoroutineSource::Closure,
499 )),
500 ..
501 }),
502 ..
503 }),
504 )) = self.tcx.hir_parent_iter(hir_id).nth(3)
505 {
506 let hir::Node::Expr(&hir::Expr {
509 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
510 ..
511 }) = self.tcx.parent_hir_node(parent_hir_id)
512 else {
513 return;
514 };
515 fn_decl_span
516 } else {
517 return;
518 };
519
520 let start = fn_decl_span.shrink_to_lo();
521 let end = callee_span.shrink_to_hi();
522 err.multipart_suggestion(
523 "if you meant to create this closure and immediately call it, surround the \
524 closure with parentheses",
525 ::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())],
526 Applicability::MaybeIncorrect,
527 );
528 }
529
530 fn maybe_suggest_bad_array_definition(
533 &self,
534 err: &mut Diag<'_>,
535 call_expr: &'tcx hir::Expr<'tcx>,
536 callee_expr: &'tcx hir::Expr<'tcx>,
537 ) -> bool {
538 let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
539 if let (
540 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
541 hir::ExprKind::Tup(exp),
542 hir::ExprKind::Call(_, args),
543 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
544 && args.len() == exp.len()
545 {
546 let start = callee_expr.span.shrink_to_hi();
547 err.span_suggestion(
548 start,
549 "consider separating array elements with a comma",
550 ",",
551 Applicability::MaybeIncorrect,
552 );
553 return true;
554 }
555 false
556 }
557
558 fn confirm_builtin_call(
559 &self,
560 call_expr: &'tcx hir::Expr<'tcx>,
561 callee_expr: &'tcx hir::Expr<'tcx>,
562 callee_ty: Ty<'tcx>,
563 arg_exprs: &'tcx [hir::Expr<'tcx>],
564 expected: Expectation<'tcx>,
565 ) -> Ty<'tcx> {
566 let (fn_sig, def_id, callee_generic_args) = match *callee_ty.kind() {
567 ty::FnDef(def_id, args) => {
568 let args = args.no_bound_vars().unwrap();
569 self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
570 let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args).skip_norm_wip();
571
572 if self.has_rustc_attrs && {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcEvaluateWhereClauses)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, def_id, RustcEvaluateWhereClauses) {
576 let clauses = self.tcx.clauses_of(def_id);
577 let clauses = clauses.instantiate(self.tcx, args);
578 for (clause, clause_span) in clauses {
579 let clause = clause.skip_norm_wip();
580 let obligation = Obligation::new(
581 self.tcx,
582 ObligationCause::dummy_with_span(callee_expr.span),
583 self.param_env,
584 clause,
585 );
586 let result = self.evaluate_obligation(&obligation);
587 self.dcx()
588 .struct_span_err(
589 callee_expr.span,
590 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("evaluate({0:?}) = {1:?}", clause,
result))
})format!("evaluate({clause:?}) = {result:?}"),
591 )
592 .with_span_label(clause_span, "predicate")
593 .emit();
594 }
595 }
596 (fn_sig, Some(def_id), Some(args))
597 }
598
599 ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None, None),
601
602 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
603 };
604
605 let fn_sig = self.instantiate_binder_with_fresh_vars(
611 call_expr.span,
612 BoundRegionConversionTime::FnCall,
613 fn_sig,
614 );
615 let fn_sig = self.normalize(call_expr.span, Unnormalized::new_wip(fn_sig));
616
617 let fn_id = match def_id {
619 Some(x) => SplatLoweringInfo::FnDef(x),
620 None => SplatLoweringInfo::FnPtr(callee_ty),
621 };
622
623 self.check_argument_types_maybe_method_like(
624 &fn_sig,
625 call_expr,
626 arg_exprs,
627 expected,
628 TupleArgumentsFlag::with_fn_sig_kind(fn_sig.fn_sig_kind, false),
629 fn_id,
630 callee_generic_args,
631 );
632
633 if fn_sig.abi() == rustc_abi::ExternAbi::RustCall {
635 let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
636 if let Some(ty) = fn_sig.inputs().last().copied()
637 && fn_sig.splatted().is_none()
638 {
639 self.register_bound(
640 ty,
641 self.tcx.require_lang_item(LangItem::Tuple, sp),
642 self.cause(sp, ObligationCauseCode::RustCall),
643 );
644 self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
645 } else {
646 self.dcx().emit_err(diagnostics::RustCallIncorrectArgs { span: sp });
647 }
648 }
649
650 fn_sig.output()
651 }
652
653 fn check_argument_types_maybe_method_like(
660 &self,
661 fn_sig: &FnSig<'tcx>,
662 call_expr: &'tcx hir::Expr<'tcx>,
663 arg_exprs: &'tcx [hir::Expr<'tcx>],
664 expected: Expectation<'tcx>,
665 tuple_arguments_flag: TupleArgumentsFlag,
666 fn_id: SplatLoweringInfo<'tcx>,
667 callee_generic_args: Option<GenericArgsRef<'tcx>>,
668 ) {
669 let do_check = || {
670 self.check_argument_types(
671 call_expr.span,
672 call_expr,
673 fn_sig.inputs(),
674 fn_sig.output(),
675 expected,
676 arg_exprs,
677 fn_sig.c_variadic(),
678 tuple_arguments_flag,
679 fn_id,
680 callee_generic_args,
681 );
682 };
683
684 let Some((candidate_res, args_to_map)) =
685 self.get_info_for_method_call_adjustments(call_expr, arg_exprs)
686 else {
687 return do_check();
688 };
689
690 let mut resolved_inputs = ::alloc::vec::Vec::new()vec![];
693 let mut prev_types = FxHashMap::default();
694 let formal_input_tys = fn_sig.inputs();
695
696 let args_to_map = arg_exprs
697 .iter()
698 .enumerate()
699 .filter(|(idx, _)| args_to_map.contains(idx))
700 .collect::<Vec<_>>();
701
702 for &(idx, arg) in &args_to_map {
703 let is_first_arg = idx == 0;
704 let self_ty_override = if is_first_arg { None } else { Some(resolved_inputs[idx]) };
705 let scope = ProbeScope::Single(candidate_res, self_ty_override);
706 let arg_type = self.check_expr(arg);
707
708 let pick = self.probe_for_name(
711 Mode::MethodCall,
712 Ident::dummy(),
713 None,
714 IsSuggestion(false),
715 arg_type,
716 call_expr.hir_id,
717 scope,
718 );
719
720 let Ok(ref pick) = pick else { return do_check() };
721
722 let mut ctx = ConfirmContext::new(self, arg.span, arg, arg);
723 let (adjusted_arg_type, method_adjustments) =
724 ctx.create_ty_adjustments_from_pick(arg_type, pick);
725
726 if is_first_arg && args_to_map.len() > 1 {
727 let cause = self.cause(
732 call_expr.span,
733 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(call_expr.hir_id)),
734 );
735 if self
736 .at(&cause, self.param_env)
737 .sup(DefineOpaqueTypes::Yes, formal_input_tys[0], adjusted_arg_type)
738 .is_err()
739 {
740 return do_check();
741 }
742
743 resolved_inputs = self.deeply_resolve_ignoring_regions(formal_input_tys.to_vec());
744 }
745
746 prev_types.insert(
749 arg.hir_id,
750 (
751 self.typeck_results
752 .borrow_mut()
753 .node_types_mut()
754 .insert(arg.hir_id, adjusted_arg_type)
755 .expect("must be set"),
756 method_adjustments,
757 ),
758 );
759 }
760
761 do_check();
762
763 for (_, arg) in args_to_map {
764 let mut results = self.typeck_results.borrow_mut();
765 let mut adjustments = results.adjustments_mut();
766
767 let (prev_type, method_adjustments) =
768 prev_types.remove(&arg.hir_id).expect("must be in a map");
769
770 let adjustments = adjustments.entry(arg.hir_id).or_default();
772 *adjustments = method_adjustments;
773
774 results.node_types_mut().insert(arg.hir_id, prev_type);
776 }
777 }
778
779 fn get_info_for_method_call_adjustments(
782 &self,
783 call_expr: &'tcx hir::Expr<'tcx>,
784 arg_exprs: &'tcx [hir::Expr<'tcx>],
785 ) -> Option<(DefId, &FxIndexSet<usize>)> {
786 let parent_def = self.tcx.hir_get_parent_item(call_expr.hir_id).def_id;
791 let Some(info) = self.tcx.hir_opt_delegation_info(parent_def) else {
792 return None;
793 };
794
795 if call_expr.hir_id != info.call_expr_id {
796 return None;
797 };
798
799 if arg_exprs.is_empty()
802 || !self.tcx.opt_associated_item(info.call_path_res).is_some_and(|i| i.is_method())
803 {
804 return None;
805 }
806
807 Some((info.call_path_res, &info.arguments_to_map))
808 }
809
810 fn suggest_call_as_method(
813 &self,
814 diag: &mut Diag<'_>,
815 segment: &'tcx hir::PathSegment<'tcx>,
816 arg_exprs: &'tcx [hir::Expr<'tcx>],
817 call_expr: &'tcx hir::Expr<'tcx>,
818 expected: Expectation<'tcx>,
819 ) {
820 if let [callee_expr, rest @ ..] = arg_exprs {
821 let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
822 else {
823 return;
824 };
825
826 let Ok(pick) = self.lookup_probe_for_diagnostic(
830 segment.ident,
831 callee_ty,
832 call_expr,
833 ProbeScope::AllTraits,
836 expected.only_has_type(self),
837 ) else {
838 return;
839 };
840
841 let pick = self.confirm_method_for_diagnostic(
842 call_expr.span,
843 callee_expr,
844 call_expr,
845 callee_ty,
846 &pick,
847 segment,
848 );
849 if pick.illegal_sized_bound.is_some() {
850 return;
851 }
852
853 let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
854 else {
855 return;
856 };
857 let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
858 let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
859 let rest_snippet = if let Some(first) = rest.first() {
860 self.tcx
861 .sess
862 .source_map()
863 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
864 } else {
865 Ok(")".to_string())
866 };
867
868 if let Ok(rest_snippet) = rest_snippet {
869 let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
870 ::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![
871 (up_to_rcvr_span, "".to_string()),
872 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
873 ]
874 } else {
875 ::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![
876 (up_to_rcvr_span, "(".to_string()),
877 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
878 ]
879 };
880 let self_ty = self.deeply_resolve_ignoring_regions(pick.callee.sig.inputs()[0]);
881 diag.multipart_suggestion(
882 ::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!(
883 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
884 self.tcx
885 .associated_item(pick.callee.def_id)
886 .trait_container(self.tcx)
887 .map_or_else(
888 || String::new(),
889 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
890 ),
891 segment.ident
892 ),
893 sugg,
894 Applicability::MaybeIncorrect,
895 );
896 }
897 }
898 }
899
900 fn report_invalid_callee(
901 &self,
902 call_expr: &'tcx hir::Expr<'tcx>,
903 callee_expr: &'tcx hir::Expr<'tcx>,
904 callee_ty: Ty<'tcx>,
905 arg_exprs: &'tcx [hir::Expr<'tcx>],
906 ) -> ErrorGuaranteed {
907 if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
910 && let Err(err) = args.error_reported()
911 {
912 return err;
913 }
914
915 let mut unit_variant = None;
916 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
917 && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
918 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
919 && arg_exprs.is_empty()
921 && call_expr.span.contains(callee_expr.span)
922 {
923 let descr = match kind {
924 def::CtorOf::Struct => "struct",
925 def::CtorOf::Variant => "enum variant",
926 };
927 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
928 unit_variant =
929 Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(self, qpath)));
930 }
931
932 let callee_ty = self.deeply_resolve_ignoring_regions(callee_ty);
933 let mut path = None;
934 let mut err = self.dcx().create_err(diagnostics::InvalidCallee {
935 span: callee_expr.span,
936 found: match &unit_variant {
937 Some((_, kind, path)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind, path))
})format!("{kind} `{path}`"),
938 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)),
939 },
940 });
941 *err.long_ty_path() = path;
942 if callee_ty.references_error() {
943 err.downgrade_to_delayed_bug();
944 }
945
946 self.identify_bad_closure_def_and_call(
947 &mut err,
948 call_expr.hir_id,
949 &callee_expr.kind,
950 callee_expr.span,
951 );
952
953 if let Some((removal_span, kind, path)) = &unit_variant {
954 err.span_suggestion_verbose(
955 *removal_span,
956 ::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!(
957 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
958 ),
959 "",
960 Applicability::MachineApplicable,
961 );
962 }
963
964 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
965 && let Res::Local(_) = path.res
966 && let [segment] = &path.segments
967 {
968 for id in self.tcx.hir_free_items() {
969 if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
970 && let hir::Node::Item(item) = node
971 && let hir::ItemKind::Fn { ident, .. } = item.kind
972 && ident.name == segment.ident.name
973 {
974 err.span_label(
975 self.tcx.def_span(id.owner_id),
976 "this function of the same name is available here, but it's shadowed by \
977 the local binding",
978 );
979 }
980 }
981 }
982
983 let mut inner_callee_path = None;
984 let def = match callee_expr.kind {
985 hir::ExprKind::Path(ref qpath) => {
986 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
987 }
988 hir::ExprKind::Call(inner_callee, _) => {
989 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
990 inner_callee_path = Some(inner_qpath);
991 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
992 } else {
993 Res::Err
994 }
995 }
996 _ => Res::Err,
997 };
998
999 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
1000 let call_is_multiline = self
1004 .tcx
1005 .sess
1006 .source_map()
1007 .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
1008 && call_expr.span.eq_ctxt(callee_expr.span);
1009 if call_is_multiline {
1010 err.span_suggestion(
1011 callee_expr.span.shrink_to_hi(),
1012 "consider using a semicolon here to finish the statement",
1013 ";",
1014 Applicability::MaybeIncorrect,
1015 );
1016 }
1017 if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
1018 && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
1019 {
1020 let descr = match maybe_def {
1021 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
1022 DefIdOrName::Name(name) => name,
1023 };
1024 err.span_label(
1025 callee_expr.span,
1026 ::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")
1027 );
1028 if let DefIdOrName::DefId(def_id) = maybe_def
1029 && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
1030 {
1031 err.span_label(def_span, "the callable type is defined here");
1032 }
1033 } else {
1034 err.span_label(call_expr.span, "call expression requires function");
1035 }
1036 }
1037
1038 if let Some(span) = self.tcx.hir_res_span(def) {
1039 let label = match (unit_variant, inner_callee_path) {
1040 (Some((_, kind, path)), _) => {
1041 err.arg("kind", kind);
1042 err.arg("path", path);
1043 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$kind} `{$path}` defined here"))msg!("{$kind} `{$path}` defined here"))
1044 }
1045 (_, Some(hir::QPath::Resolved(_, path))) => {
1046 self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
1047 err.arg("func", p);
1048 err.arg("ty", callee_ty);
1049 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$func}` defined here returns `{$ty}`"))msg!("`{$func}` defined here returns `{$ty}`")
1050 })
1051 }
1052 _ => {
1053 match def {
1054 Res::Local(hir_id) => {
1057 err.arg("local_name", self.tcx.hir_name(hir_id));
1058 err.arg("ty", callee_ty);
1059 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$local_name}` has type `{$ty}`"))msg!("`{$local_name}` has type `{$ty}`"))
1060 }
1061 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
1062 err.arg("path", self.tcx.def_path_str(def_id));
1063 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
1064 }
1065 _ => {
1066 err.arg("path", callee_ty.to_string());
1067 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
1068 }
1069 }
1070 }
1071 };
1072 if let Some(label) = label {
1073 err.span_label(span, label);
1074 }
1075 }
1076 err.emit_err()
1077 }
1078
1079 fn confirm_deferred_closure_call(
1080 &self,
1081 call_expr: &'tcx hir::Expr<'tcx>,
1082 arg_exprs: &'tcx [hir::Expr<'tcx>],
1083 expected: Expectation<'tcx>,
1084 closure_def_id: LocalDefId,
1085 fn_sig: ty::FnSig<'tcx>,
1086 ) -> Ty<'tcx> {
1087 self.check_argument_types(
1092 call_expr.span,
1093 call_expr,
1094 fn_sig.inputs(),
1095 fn_sig.output(),
1096 expected,
1097 arg_exprs,
1098 fn_sig.fn_sig_kind.c_variadic(),
1099 TupleArgumentsFlag::rust_fn_trait_call(),
1100 SplatLoweringInfo::FnDef(closure_def_id.to_def_id()),
1101 None,
1102 );
1103
1104 fn_sig.output()
1105 }
1106
1107 {}
#[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("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(1107u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("call_hir_id")
}> =
::tracing::__macro_support::FieldName::new("call_hir_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("callee_did")
}> =
::tracing::__macro_support::FieldName::new("callee_did");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("callee_args")
}> =
::tracing::__macro_support::FieldName::new("callee_args");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_hir_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_did)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_args)
as &dyn ::tracing::field::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;
}
{
let const_context =
self.tcx.hir_body_const_context(self.body_def_id);
if let hir::Constness::Const { always: true } =
self.tcx.constness(callee_did) {
match const_context {
Some(hir::ConstContext::Const { .. } |
hir::ConstContext::Static(_)) => {}
Some(hir::ConstContext::ConstFn) | None => {
self.dcx().emit_err(diagnostics::ComptimeFnCalledOutsideConstContext {
span,
const_block: diagnostics::WrapConstBlock {
left: span.shrink_to_lo(),
right: span.shrink_to_hi(),
},
});
}
}
}
if !self.tcx.features().const_trait_impl() { return; }
if self.has_rustc_attrs &&
{
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(self.body_def_id,
&self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDoNotConstCheck) =>
{
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some() {
return;
}
let host =
match const_context {
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))]
1108 pub(super) fn enforce_context_effects(
1109 &self,
1110 call_hir_id: Option<HirId>,
1111 span: Span,
1112 callee_did: DefId,
1113 callee_args: GenericArgsRef<'tcx>,
1114 ) {
1115 let const_context = self.tcx.hir_body_const_context(self.body_def_id);
1116
1117 if let hir::Constness::Const { always: true } = self.tcx.constness(callee_did) {
1118 match const_context {
1119 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {}
1120 Some(hir::ConstContext::ConstFn) | None => {
1121 self.dcx().emit_err(diagnostics::ComptimeFnCalledOutsideConstContext {
1122 span,
1123 const_block: diagnostics::WrapConstBlock {
1124 left: span.shrink_to_lo(),
1125 right: span.shrink_to_hi(),
1126 },
1127 });
1128 }
1129 }
1130 }
1131
1132 if !self.tcx.features().const_trait_impl() {
1137 return;
1138 }
1139
1140 if self.has_rustc_attrs && find_attr!(self.tcx, self.body_def_id, RustcDoNotConstCheck) {
1142 return;
1143 }
1144
1145 let host = match const_context {
1146 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
1147 ty::BoundConstness::Const
1148 }
1149 Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
1150 None => return,
1151 };
1152
1153 if self.tcx.is_conditionally_const(callee_did) {
1156 let q = self.tcx.const_conditions(callee_did);
1157 for (idx, (cond, pred_span)) in
1158 q.instantiate(self.tcx, callee_args).into_iter().enumerate()
1159 {
1160 let cause = self.cause(
1161 span,
1162 if let Some(hir_id) = call_hir_id {
1163 ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
1164 } else {
1165 ObligationCauseCode::WhereClause(callee_did, pred_span)
1166 },
1167 );
1168 self.register_predicate(Obligation::new(
1169 self.tcx,
1170 cause,
1171 self.param_env,
1172 cond.to_host_effect_clause(self.tcx, host).skip_norm_wip(),
1173 ));
1174 }
1175 } else {
1176 }
1179 }
1180
1181 fn confirm_overloaded_call(
1182 &self,
1183 call_expr: &'tcx hir::Expr<'tcx>,
1184 arg_exprs: &'tcx [hir::Expr<'tcx>],
1185 expected: Expectation<'tcx>,
1186 method: MethodCallee<'tcx>,
1187 ) -> Ty<'tcx> {
1188 {
match (&method.sig.fn_sig_kind.splatted(), &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("splatting is not supported on RustCall tuples")));
}
}
}
};assert_eq!(
1191 method.sig.fn_sig_kind.splatted(),
1192 None,
1193 "splatting is not supported on RustCall tuples",
1194 );
1195 self.check_argument_types(
1196 call_expr.span,
1197 call_expr,
1198 &method.sig.inputs()[1..],
1199 method.sig.output(),
1200 expected,
1201 arg_exprs,
1202 method.sig.fn_sig_kind.c_variadic(),
1203 TupleArgumentsFlag::rust_fn_trait_call(),
1204 SplatLoweringInfo::FnDef(method.def_id),
1205 None,
1206 );
1207
1208 self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
1209
1210 method.sig.output()
1211 }
1212}
1213
1214#[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)]
1215pub(crate) struct DeferredCallResolution<'tcx> {
1216 call_expr: &'tcx hir::Expr<'tcx>,
1217 callee_expr: &'tcx hir::Expr<'tcx>,
1218 closure_ty: Ty<'tcx>,
1219 adjustments: Vec<Adjustment<'tcx>>,
1220 fn_sig: ty::FnSig<'tcx>,
1221}
1222
1223impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1224 pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1225 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs:1225",
"rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(1225u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("DeferredCallResolution::resolve() {0:?}",
self) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("DeferredCallResolution::resolve() {:?}", self);
1226
1227 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());
1230
1231 match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1233 Some((autoref, method_callee)) => {
1234 let method_sig = method_callee.sig;
1243
1244 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs:1244",
"rustc_hir_typeck::callee", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/callee.rs"),
::tracing_core::__macro_support::Option::Some(1244u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("attempt_resolution: method_callee={0:?}",
method_callee) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("attempt_resolution: method_callee={:?}", method_callee);
1245
1246 for (method_arg_ty, self_arg_ty) in
1247 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1248 {
1249 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1250 }
1251
1252 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1253
1254 let mut adjustments = self.adjustments;
1255 adjustments.extend(autoref);
1256 fcx.apply_adjustments(self.callee_expr, adjustments);
1257
1258 fcx.write_method_call_and_enforce_effects(
1259 self.call_expr.hir_id,
1260 self.call_expr.span,
1261 method_callee,
1262 );
1263 }
1264 None => {
1265 let guar = fcx.tainted_by_errors().unwrap_or_else(|| {
1266 fcx.dcx().span_delayed_bug(
1267 self.call_expr.span,
1268 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{0}`",
self.closure_ty))
})format!(
1269 "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1270 self.closure_ty
1271 ),
1272 )
1273 });
1274 fcx.write_resolution(self.call_expr.hir_id, Err(guar));
1275 }
1276 }
1277 }
1278}