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