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