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