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
34pub(crate) fn check_legal_trait_for_method_call(
38 tcx: TyCtxt<'_>,
39 span: Span,
40 receiver: Option<Span>,
41 expr_span: Span,
42 trait_id: DefId,
43 body_def_id: DefId,
44) -> Result<(), ErrorGuaranteed> {
45 if tcx.is_lang_item(trait_id, LangItem::Drop)
46 && !tcx.is_lang_item(tcx.parent(body_def_id), LangItem::Drop)
48 {
49 let sugg = if let Some(receiver) = receiver.filter(|s| !s.is_empty()) {
50 diagnostics::ExplicitDestructorCallSugg::Snippet {
51 lo: expr_span.shrink_to_lo().to(receiver.shrink_to_lo()),
52 hi: receiver.shrink_to_hi().to(expr_span.shrink_to_hi()),
53 }
54 } else {
55 diagnostics::ExplicitDestructorCallSugg::Empty(span)
56 };
57 return Err(tcx.dcx().emit_err(diagnostics::ExplicitDestructorCall { span, sugg }));
58 }
59 tcx.ensure_result().coherent_trait(trait_id)
60}
61
62#[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)]
64enum CallStep<'tcx> {
65 Builtin(Ty<'tcx>),
68 DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
70 Overloaded(MethodCallee<'tcx>),
72}
73
74impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
75 #[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(75u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&["call_expr",
"callee_expr", "arg_exprs", "expected"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_expr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_expr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_exprs)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: 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))]
76 pub(crate) fn check_expr_call(
77 &self,
78 call_expr: &'tcx hir::Expr<'tcx>,
79 callee_expr: &'tcx hir::Expr<'tcx>,
80 arg_exprs: &'tcx [hir::Expr<'tcx>],
81 expected: Expectation<'tcx>,
82 ) -> Ty<'tcx> {
83 let original_callee_ty = match &callee_expr.kind {
84 hir::ExprKind::Path(hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)) => self
85 .check_expr_with_expectation_and_args(
86 callee_expr,
87 Expectation::NoExpectation,
88 Some((call_expr, arg_exprs)),
89 ),
90 _ => self.check_expr(callee_expr),
91 };
92
93 let expr_ty = self.resolve_vars_with_obligations(original_callee_ty);
94
95 let mut autoderef = self.autoderef(callee_expr.span, expr_ty);
96 let mut result = None;
97 while result.is_none() && autoderef.next().is_some() {
98 result = self.try_overloaded_call_step(call_expr, callee_expr, arg_exprs, &autoderef);
99 }
100
101 match *autoderef.final_ty().kind() {
102 ty::FnDef(def_id, _) => {
103 let abi = self.tcx.fn_sig(def_id).skip_binder().skip_binder().abi();
104 self.check_call_abi(abi, call_expr.span);
105 }
106 ty::FnPtr(_, header) => {
107 self.check_call_abi(header.abi(), call_expr.span);
108 }
109 _ => { }
110 }
111
112 if self.is_scalable_vector_ctor(autoderef.final_ty()) {
113 let mut err = self.dcx().create_err(diagnostics::ScalableVectorCtor {
114 span: callee_expr.span,
115 ty: autoderef.final_ty(),
116 });
117 err.span_label(callee_expr.span, "you can create scalable vectors using intrinsics");
118 Ty::new_error(self.tcx, err.emit());
119 }
120
121 self.register_predicates(autoderef.into_obligations());
122
123 let output = match result {
124 None => {
125 for arg in arg_exprs {
128 self.check_expr(arg);
129 }
130
131 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind
132 && let [segment] = path.segments
133 {
134 self.dcx().try_steal_modify_and_emit_err(
135 segment.ident.span,
136 StashKey::CallIntoMethod,
137 |err| {
138 self.suggest_call_as_method(
140 err, segment, arg_exprs, call_expr, expected,
141 );
142 },
143 );
144 }
145
146 let guar = self.report_invalid_callee(call_expr, callee_expr, expr_ty, arg_exprs);
147 Ty::new_error(self.tcx, guar)
148 }
149
150 Some(CallStep::Builtin(callee_ty)) => {
151 self.confirm_builtin_call(call_expr, callee_expr, callee_ty, arg_exprs, expected)
152 }
153
154 Some(CallStep::DeferredClosure(def_id, fn_sig)) => {
155 self.confirm_deferred_closure_call(call_expr, arg_exprs, expected, def_id, fn_sig)
156 }
157
158 Some(CallStep::Overloaded(method_callee)) => {
159 self.confirm_overloaded_call(call_expr, arg_exprs, expected, method_callee)
160 }
161 };
162
163 self.register_wf_obligation(
165 output.into(),
166 call_expr.span,
167 ObligationCauseCode::WellFormed(None),
168 );
169
170 output
171 }
172
173 pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span) {
178 let canon_abi = match AbiMap::from_target(&self.sess().target).canonize_abi(abi, false) {
179 AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => canon_abi,
180 AbiMapping::Invalid => {
181 let guar = self.dcx().span_delayed_bug(
184 span,
185 ::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}"),
186 );
187 self.set_tainted_by_errors(guar);
188 return;
189 }
190 };
191
192 match canon_abi {
193 CanonAbi::Custom
195 | CanonAbi::Interrupt(_) => {
198 let err = crate::diagnostics::AbiCannotBeCalled { span, abi };
199 self.tcx.dcx().emit_err(err);
200 }
201
202 CanonAbi::GpuKernel => {
204 let err = crate::diagnostics::GpuKernelAbiCannotBeCalled { span };
205 self.tcx.dcx().emit_err(err);
206 }
207
208 CanonAbi::C
209 | CanonAbi::Rust
210 | CanonAbi::RustCold
211 | CanonAbi::RustPreserveNone
212 | CanonAbi::RustTail
213 | CanonAbi::Swift
214 | CanonAbi::Arm(_)
215 | CanonAbi::X86(_) => {}
216 }
217 }
218
219 x;#[instrument(level = "debug", skip(self, call_expr, callee_expr, arg_exprs, autoderef), ret)]
220 fn try_overloaded_call_step(
221 &self,
222 call_expr: &'tcx hir::Expr<'tcx>,
223 callee_expr: &'tcx hir::Expr<'tcx>,
224 arg_exprs: &'tcx [hir::Expr<'tcx>],
225 autoderef: &Autoderef<'a, 'tcx>,
226 ) -> Option<CallStep<'tcx>> {
227 let adjusted_ty = self.resolve_vars_with_obligations(autoderef.final_ty());
228
229 match *adjusted_ty.kind() {
231 ty::FnDef(..) | ty::FnPtr(..) => {
232 let adjustments = self.adjust_steps(autoderef);
233 self.apply_adjustments(callee_expr, adjustments);
234 return Some(CallStep::Builtin(adjusted_ty));
235 }
236
237 ty::Closure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
241 let def_id = def_id.expect_local();
242 let closure_sig = args.as_closure().sig();
243 let closure_sig = self.instantiate_binder_with_fresh_vars(
244 call_expr.span,
245 BoundRegionConversionTime::FnCall,
246 closure_sig,
247 );
248 let adjustments = self.adjust_steps(autoderef);
249 self.record_deferred_call_resolution(
250 def_id,
251 DeferredCallResolution {
252 call_expr,
253 callee_expr,
254 closure_ty: adjusted_ty,
255 adjustments,
256 fn_sig: closure_sig,
257 },
258 );
259 return Some(CallStep::DeferredClosure(def_id, closure_sig));
260 }
261
262 ty::CoroutineClosure(def_id, args) if self.closure_kind(adjusted_ty).is_none() => {
268 let def_id = def_id.expect_local();
269 let closure_args = args.as_coroutine_closure();
270 let coroutine_closure_sig = self.instantiate_binder_with_fresh_vars(
271 call_expr.span,
272 BoundRegionConversionTime::FnCall,
273 closure_args.coroutine_closure_sig(),
274 );
275 let tupled_upvars_ty = self.next_ty_var(callee_expr.span);
276 let kind_ty = self.next_ty_var(callee_expr.span);
281 let call_sig = self.tcx.mk_fn_sig(
282 [coroutine_closure_sig.tupled_inputs_ty],
283 coroutine_closure_sig.to_coroutine(
284 self.tcx,
285 closure_args.parent_args(),
286 kind_ty,
287 self.tcx.coroutine_for_closure(def_id),
288 tupled_upvars_ty,
289 ),
290 coroutine_closure_sig.fn_sig_kind,
291 );
292 let adjustments = self.adjust_steps(autoderef);
293 self.record_deferred_call_resolution(
294 def_id,
295 DeferredCallResolution {
296 call_expr,
297 callee_expr,
298 closure_ty: adjusted_ty,
299 adjustments,
300 fn_sig: call_sig,
301 },
302 );
303 return Some(CallStep::DeferredClosure(def_id, call_sig));
304 }
305
306 ty::Ref(..) if autoderef.step_count() == 0 => {
319 return None;
320 }
321
322 ty::Infer(ty::TyVar(vid)) => {
323 if !self.has_opaques_with_sub_unified_hidden_type(vid) {
326 self.type_must_be_known_at_this_point(autoderef.span(), adjusted_ty);
327 return None;
328 }
329 }
330
331 ty::Error(_) => {
332 return None;
333 }
334
335 _ => {}
336 }
337
338 self.try_overloaded_call_traits(call_expr, adjusted_ty, Some(arg_exprs))
346 .or_else(|| self.try_overloaded_call_traits(call_expr, adjusted_ty, None))
347 .map(|(autoref, method)| {
348 let mut adjustments = self.adjust_steps(autoderef);
349 adjustments.extend(autoref);
350 self.apply_adjustments(callee_expr, adjustments);
351 CallStep::Overloaded(method)
352 })
353 }
354
355 fn try_overloaded_call_traits(
356 &self,
357 call_expr: &hir::Expr<'_>,
358 adjusted_ty: Ty<'tcx>,
359 opt_arg_exprs: Option<&'tcx [hir::Expr<'tcx>]>,
360 ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)> {
361 let call_trait_choices = if self.shallow_resolve(adjusted_ty).is_coroutine_closure() {
374 [
375 (self.tcx.lang_items().async_fn_trait(), sym::async_call, true),
376 (self.tcx.lang_items().async_fn_mut_trait(), sym::async_call_mut, true),
377 (self.tcx.lang_items().async_fn_once_trait(), sym::async_call_once, false),
378 (self.tcx.lang_items().fn_trait(), sym::call, true),
379 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
380 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
381 ]
382 } else {
383 [
384 (self.tcx.lang_items().fn_trait(), sym::call, true),
385 (self.tcx.lang_items().fn_mut_trait(), sym::call_mut, true),
386 (self.tcx.lang_items().fn_once_trait(), sym::call_once, false),
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 ]
391 };
392
393 for (opt_trait_def_id, method_name, borrow) in call_trait_choices {
395 let Some(trait_def_id) = opt_trait_def_id else { continue };
396
397 let opt_input_type = opt_arg_exprs.map(|arg_exprs| {
398 Ty::new_tup_from_iter(self.tcx, arg_exprs.iter().map(|e| self.next_ty_var(e.span)))
399 });
400
401 if let Some(ok) = self.lookup_method_for_operator(
408 self.misc(call_expr.span),
409 method_name,
410 trait_def_id,
411 adjusted_ty,
412 opt_input_type,
413 TreatNotYetDefinedOpaques::AsRigid,
414 ) {
415 let method = self.register_infer_ok_obligations(ok);
416 let mut autoref = None;
417 if borrow {
418 let ty::Ref(_, _, mutbl) = *method.sig.inputs()[0].kind() else {
421 ::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")
422 };
423
424 let mutbl = AutoBorrowMutability::new(mutbl, AllowTwoPhase::No);
428
429 autoref = Some(Adjustment {
430 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
431 target: method.sig.inputs()[0],
432 });
433 }
434
435 return Some((autoref, method));
436 }
437 }
438
439 None
440 }
441
442 fn is_scalable_vector_ctor(&self, callee_ty: Ty<'_>) -> bool {
443 if let ty::FnDef(def_id, _) = *callee_ty.kind()
444 && let def::DefKind::Ctor(def::CtorOf::Struct, _) = self.tcx.def_kind(def_id)
445 {
446 self.tcx
447 .opt_parent(def_id)
448 .and_then(|id| self.tcx.adt_def(id).repr().scalable)
449 .is_some()
450 } else {
451 false
452 }
453 }
454
455 fn identify_bad_closure_def_and_call(
458 &self,
459 err: &mut Diag<'_>,
460 hir_id: hir::HirId,
461 callee_node: &hir::ExprKind<'_>,
462 callee_span: Span,
463 ) {
464 let hir::ExprKind::Block(..) = callee_node else {
465 return;
467 };
468
469 let fn_decl_span = if let hir::Node::Expr(&hir::Expr {
470 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
471 ..
472 }) = self.tcx.parent_hir_node(hir_id)
473 {
474 fn_decl_span
475 } else if let Some((
476 _,
477 hir::Node::Expr(&hir::Expr {
478 hir_id: parent_hir_id,
479 kind:
480 hir::ExprKind::Closure(&hir::Closure {
481 kind:
482 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
483 hir::CoroutineDesugaring::Async,
484 hir::CoroutineSource::Closure,
485 )),
486 ..
487 }),
488 ..
489 }),
490 )) = self.tcx.hir_parent_iter(hir_id).nth(3)
491 {
492 let hir::Node::Expr(&hir::Expr {
495 kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }),
496 ..
497 }) = self.tcx.parent_hir_node(parent_hir_id)
498 else {
499 return;
500 };
501 fn_decl_span
502 } else {
503 return;
504 };
505
506 let start = fn_decl_span.shrink_to_lo();
507 let end = callee_span.shrink_to_hi();
508 err.multipart_suggestion(
509 "if you meant to create this closure and immediately call it, surround the \
510 closure with parentheses",
511 ::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())],
512 Applicability::MaybeIncorrect,
513 );
514 }
515
516 fn maybe_suggest_bad_array_definition(
519 &self,
520 err: &mut Diag<'_>,
521 call_expr: &'tcx hir::Expr<'tcx>,
522 callee_expr: &'tcx hir::Expr<'tcx>,
523 ) -> bool {
524 let parent_node = self.tcx.parent_hir_node(call_expr.hir_id);
525 if let (
526 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }),
527 hir::ExprKind::Tup(exp),
528 hir::ExprKind::Call(_, args),
529 ) = (parent_node, &callee_expr.kind, &call_expr.kind)
530 && args.len() == exp.len()
531 {
532 let start = callee_expr.span.shrink_to_hi();
533 err.span_suggestion(
534 start,
535 "consider separating array elements with a comma",
536 ",",
537 Applicability::MaybeIncorrect,
538 );
539 return true;
540 }
541 false
542 }
543
544 fn confirm_builtin_call(
545 &self,
546 call_expr: &'tcx hir::Expr<'tcx>,
547 callee_expr: &'tcx hir::Expr<'tcx>,
548 callee_ty: Ty<'tcx>,
549 arg_exprs: &'tcx [hir::Expr<'tcx>],
550 expected: Expectation<'tcx>,
551 ) -> Ty<'tcx> {
552 let (fn_sig, def_id, callee_generic_args) = match *callee_ty.kind() {
553 ty::FnDef(def_id, args) => {
554 self.enforce_context_effects(Some(call_expr.hir_id), call_expr.span, def_id, args);
555 let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args).skip_norm_wip();
556
557 if self.has_rustc_attrs && {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcEvaluateWhereClauses) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, def_id, RustcEvaluateWhereClauses) {
561 let predicates = self.tcx.predicates_of(def_id);
562 let predicates = predicates.instantiate(self.tcx, args);
563 for (predicate, predicate_span) in predicates {
564 let predicate = predicate.skip_norm_wip();
565 let obligation = Obligation::new(
566 self.tcx,
567 ObligationCause::dummy_with_span(callee_expr.span),
568 self.param_env,
569 predicate,
570 );
571 let result = self.evaluate_obligation(&obligation);
572 self.dcx()
573 .struct_span_err(
574 callee_expr.span,
575 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("evaluate({0:?}) = {1:?}",
predicate, result))
})format!("evaluate({predicate:?}) = {result:?}"),
576 )
577 .with_span_label(predicate_span, "predicate")
578 .emit();
579 }
580 }
581 (fn_sig, Some(def_id), Some(args))
582 }
583
584 ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None, None),
586
587 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
588 };
589
590 let fn_sig = self.instantiate_binder_with_fresh_vars(
596 call_expr.span,
597 BoundRegionConversionTime::FnCall,
598 fn_sig,
599 );
600 let fn_sig = self.normalize(call_expr.span, Unnormalized::new_wip(fn_sig));
601
602 self.check_argument_types_maybe_method_like(
603 &fn_sig,
604 call_expr,
605 arg_exprs,
606 expected,
607 TupleArgumentsFlag::with_fn_sig_kind(fn_sig.fn_sig_kind, false),
608 def_id,
609 callee_generic_args,
610 );
611
612 if fn_sig.abi() == rustc_abi::ExternAbi::RustCall {
614 let sp = arg_exprs.last().map_or(call_expr.span, |expr| expr.span);
615 if let Some(ty) = fn_sig.inputs().last().copied()
616 && fn_sig.splatted().is_none()
617 {
618 self.register_bound(
619 ty,
620 self.tcx.require_lang_item(hir::LangItem::Tuple, sp),
621 self.cause(sp, ObligationCauseCode::RustCall),
622 );
623 self.require_type_is_sized(ty, sp, ObligationCauseCode::RustCall);
624 } else {
625 self.dcx().emit_err(diagnostics::RustCallIncorrectArgs { span: sp });
626 }
627 }
628
629 fn_sig.output()
630 }
631
632 fn check_argument_types_maybe_method_like(
639 &self,
640 fn_sig: &FnSig<'tcx>,
641 call_expr: &'tcx hir::Expr<'tcx>,
642 arg_exprs: &'tcx [hir::Expr<'tcx>],
643 expected: Expectation<'tcx>,
644 tuple_arguments_flag: TupleArgumentsFlag,
645 def_id: Option<DefId>,
646 callee_generic_args: Option<GenericArgsRef<'tcx>>,
647 ) {
648 let do_check = || {
649 self.check_argument_types(
650 call_expr.span,
651 call_expr,
652 fn_sig.inputs(),
653 fn_sig.output(),
654 expected,
655 arg_exprs,
656 fn_sig.c_variadic(),
657 tuple_arguments_flag,
658 def_id,
659 callee_generic_args,
660 );
661 };
662
663 let Some((candidate_res, args_to_map)) =
664 self.get_info_for_method_call_adjustments(call_expr, arg_exprs)
665 else {
666 return do_check();
667 };
668
669 let mut resolved_inputs = ::alloc::vec::Vec::new()vec![];
672 let mut prev_types = FxHashMap::default();
673 let formal_input_tys = fn_sig.inputs();
674
675 let args_to_map = arg_exprs
676 .iter()
677 .enumerate()
678 .filter(|(idx, _)| args_to_map.contains(idx))
679 .collect::<Vec<_>>();
680
681 for &(idx, arg) in &args_to_map {
682 let is_first_arg = idx == 0;
683 let self_ty_override = if is_first_arg { None } else { Some(resolved_inputs[idx]) };
684 let scope = ProbeScope::Single(candidate_res, self_ty_override);
685 let arg_type = self.check_expr(arg);
686
687 let pick = self.probe_for_name(
690 Mode::MethodCall,
691 Ident::dummy(),
692 None,
693 IsSuggestion(false),
694 arg_type,
695 call_expr.hir_id,
696 scope,
697 );
698
699 let Ok(pick) = pick else { return do_check() };
700
701 if is_first_arg && args_to_map.len() > 1 {
702 let cause = self.cause(call_expr.span, ObligationCauseCode::Misc);
707 if self
708 .at(&cause, self.param_env)
709 .sup(DefineOpaqueTypes::Yes, formal_input_tys[0], pick.self_ty)
710 .is_err()
711 {
712 return do_check();
713 }
714
715 resolved_inputs = self.resolve_vars_if_possible(formal_input_tys.to_vec());
716 }
717
718 prev_types.insert(
721 arg.hir_id,
722 (
723 self.typeck_results
724 .borrow_mut()
725 .node_types_mut()
726 .insert(arg.hir_id, pick.self_ty)
727 .expect("must be set"),
728 pick,
729 ),
730 );
731 }
732
733 do_check();
734
735 for (_, arg) in args_to_map {
736 let mut results = self.typeck_results.borrow_mut();
737 let mut adjustments = results.adjustments_mut();
738
739 let (prev_type, pick) = prev_types.remove(&arg.hir_id).expect("must be in a map");
740
741 let adjustments = adjustments.entry(arg.hir_id).or_default();
743
744 let mut ctx = ConfirmContext::new(self, arg.span, arg, arg);
745 *adjustments = ctx.create_ty_adjustments_from_pick(prev_type, &pick).1;
746
747 results.node_types_mut().insert(arg.hir_id, prev_type);
749 }
750 }
751
752 fn get_info_for_method_call_adjustments(
755 &self,
756 call_expr: &'tcx hir::Expr<'tcx>,
757 arg_exprs: &'tcx [hir::Expr<'tcx>],
758 ) -> Option<(DefId, &FxIndexSet<usize>)> {
759 let parent_def = self.tcx.hir_get_parent_item(call_expr.hir_id).def_id;
764 let Some(info) = self.tcx.hir_opt_delegation_info(parent_def) else {
765 return None;
766 };
767
768 if call_expr.hir_id != info.call_expr_id {
769 return None;
770 };
771
772 if arg_exprs.is_empty()
775 || !self.tcx.opt_associated_item(info.call_path_res).is_some_and(|i| i.is_method())
776 {
777 return None;
778 }
779
780 Some((info.call_path_res, &info.arguments_to_map))
781 }
782
783 fn suggest_call_as_method(
786 &self,
787 diag: &mut Diag<'_>,
788 segment: &'tcx hir::PathSegment<'tcx>,
789 arg_exprs: &'tcx [hir::Expr<'tcx>],
790 call_expr: &'tcx hir::Expr<'tcx>,
791 expected: Expectation<'tcx>,
792 ) {
793 if let [callee_expr, rest @ ..] = arg_exprs {
794 let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)
795 else {
796 return;
797 };
798
799 let Ok(pick) = self.lookup_probe_for_diagnostic(
803 segment.ident,
804 callee_ty,
805 call_expr,
806 ProbeScope::AllTraits,
809 expected.only_has_type(self),
810 ) else {
811 return;
812 };
813
814 let pick = self.confirm_method_for_diagnostic(
815 call_expr.span,
816 callee_expr,
817 call_expr,
818 callee_ty,
819 &pick,
820 segment,
821 );
822 if pick.illegal_sized_bound.is_some() {
823 return;
824 }
825
826 let Some(callee_expr_span) = callee_expr.span.find_ancestor_inside(call_expr.span)
827 else {
828 return;
829 };
830 let up_to_rcvr_span = segment.ident.span.until(callee_expr_span);
831 let rest_span = callee_expr_span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
832 let rest_snippet = if let Some(first) = rest.first() {
833 self.tcx
834 .sess
835 .source_map()
836 .span_to_snippet(first.span.to(call_expr.span.shrink_to_hi()))
837 } else {
838 Ok(")".to_string())
839 };
840
841 if let Ok(rest_snippet) = rest_snippet {
842 let sugg = if self.precedence(callee_expr) >= ExprPrecedence::Unambiguous {
843 ::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![
844 (up_to_rcvr_span, "".to_string()),
845 (rest_span, format!(".{}({rest_snippet}", segment.ident)),
846 ]
847 } else {
848 ::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![
849 (up_to_rcvr_span, "(".to_string()),
850 (rest_span, format!(").{}({rest_snippet}", segment.ident)),
851 ]
852 };
853 let self_ty = self.resolve_vars_if_possible(pick.callee.sig.inputs()[0]);
854 diag.multipart_suggestion(
855 ::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!(
856 "use the `.` operator to call the method `{}{}` on `{self_ty}`",
857 self.tcx
858 .associated_item(pick.callee.def_id)
859 .trait_container(self.tcx)
860 .map_or_else(
861 || String::new(),
862 |trait_def_id| self.tcx.def_path_str(trait_def_id) + "::"
863 ),
864 segment.ident
865 ),
866 sugg,
867 Applicability::MaybeIncorrect,
868 );
869 }
870 }
871 }
872
873 fn report_invalid_callee(
874 &self,
875 call_expr: &'tcx hir::Expr<'tcx>,
876 callee_expr: &'tcx hir::Expr<'tcx>,
877 callee_ty: Ty<'tcx>,
878 arg_exprs: &'tcx [hir::Expr<'tcx>],
879 ) -> ErrorGuaranteed {
880 if let Some((_, _, args)) = self.extract_callable_info(callee_ty)
883 && let Err(err) = args.error_reported()
884 {
885 return err;
886 }
887
888 let mut unit_variant = None;
889 if let hir::ExprKind::Path(qpath) = &callee_expr.kind
890 && let Res::Def(def::DefKind::Ctor(kind, CtorKind::Const), _)
891 = self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
892 && arg_exprs.is_empty()
894 && call_expr.span.contains(callee_expr.span)
895 {
896 let descr = match kind {
897 def::CtorOf::Struct => "struct",
898 def::CtorOf::Variant => "enum variant",
899 };
900 let removal_span = callee_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi());
901 unit_variant =
902 Some((removal_span, descr, rustc_hir_pretty::qpath_to_string(&self.tcx, qpath)));
903 }
904
905 let callee_ty = self.resolve_vars_if_possible(callee_ty);
906 let mut path = None;
907 let mut err = self.dcx().create_err(diagnostics::InvalidCallee {
908 span: callee_expr.span,
909 found: match &unit_variant {
910 Some((_, kind, path)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind, path))
})format!("{kind} `{path}`"),
911 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)),
912 },
913 });
914 *err.long_ty_path() = path;
915 if callee_ty.references_error() {
916 err.downgrade_to_delayed_bug();
917 }
918
919 self.identify_bad_closure_def_and_call(
920 &mut err,
921 call_expr.hir_id,
922 &callee_expr.kind,
923 callee_expr.span,
924 );
925
926 if let Some((removal_span, kind, path)) = &unit_variant {
927 err.span_suggestion_verbose(
928 *removal_span,
929 ::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!(
930 "`{path}` is a unit {kind}, and does not take parentheses to be constructed",
931 ),
932 "",
933 Applicability::MachineApplicable,
934 );
935 }
936
937 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = callee_expr.kind
938 && let Res::Local(_) = path.res
939 && let [segment] = &path.segments
940 {
941 for id in self.tcx.hir_free_items() {
942 if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
943 && let hir::Node::Item(item) = node
944 && let hir::ItemKind::Fn { ident, .. } = item.kind
945 && ident.name == segment.ident.name
946 {
947 err.span_label(
948 self.tcx.def_span(id.owner_id),
949 "this function of the same name is available here, but it's shadowed by \
950 the local binding",
951 );
952 }
953 }
954 }
955
956 let mut inner_callee_path = None;
957 let def = match callee_expr.kind {
958 hir::ExprKind::Path(ref qpath) => {
959 self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id)
960 }
961 hir::ExprKind::Call(inner_callee, _) => {
962 if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind {
963 inner_callee_path = Some(inner_qpath);
964 self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)
965 } else {
966 Res::Err
967 }
968 }
969 _ => Res::Err,
970 };
971
972 if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) {
973 let call_is_multiline = self
977 .tcx
978 .sess
979 .source_map()
980 .is_multiline(call_expr.span.with_lo(callee_expr.span.hi()))
981 && call_expr.span.eq_ctxt(callee_expr.span);
982 if call_is_multiline {
983 err.span_suggestion(
984 callee_expr.span.shrink_to_hi(),
985 "consider using a semicolon here to finish the statement",
986 ";",
987 Applicability::MaybeIncorrect,
988 );
989 }
990 if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty)
991 && !self.type_is_sized_modulo_regions(self.param_env, output_ty)
992 {
993 let descr = match maybe_def {
994 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
995 DefIdOrName::Name(name) => name,
996 };
997 err.span_label(
998 callee_expr.span,
999 ::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")
1000 );
1001 if let DefIdOrName::DefId(def_id) = maybe_def
1002 && let Some(def_span) = self.tcx.hir_span_if_local(def_id)
1003 {
1004 err.span_label(def_span, "the callable type is defined here");
1005 }
1006 } else {
1007 err.span_label(call_expr.span, "call expression requires function");
1008 }
1009 }
1010
1011 if let Some(span) = self.tcx.hir_res_span(def) {
1012 let label = match (unit_variant, inner_callee_path) {
1013 (Some((_, kind, path)), _) => {
1014 err.arg("kind", kind);
1015 err.arg("path", path);
1016 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$kind} `{$path}` defined here"))msg!("{$kind} `{$path}` defined here"))
1017 }
1018 (_, Some(hir::QPath::Resolved(_, path))) => {
1019 self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| {
1020 err.arg("func", p);
1021 err.arg("ty", callee_ty);
1022 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$func}` defined here returns `{$ty}`"))msg!("`{$func}` defined here returns `{$ty}`")
1023 })
1024 }
1025 _ => {
1026 match def {
1027 Res::Local(hir_id) => {
1030 err.arg("local_name", self.tcx.hir_name(hir_id));
1031 err.arg("ty", callee_ty);
1032 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$local_name}` has type `{$ty}`"))msg!("`{$local_name}` has type `{$ty}`"))
1033 }
1034 Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {
1035 err.arg("path", self.tcx.def_path_str(def_id));
1036 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
1037 }
1038 _ => {
1039 err.arg("path", callee_ty.to_string());
1040 Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$path}` defined here"))msg!("`{$path}` defined here"))
1041 }
1042 }
1043 }
1044 };
1045 if let Some(label) = label {
1046 err.span_label(span, label);
1047 }
1048 }
1049 err.emit()
1050 }
1051
1052 fn confirm_deferred_closure_call(
1053 &self,
1054 call_expr: &'tcx hir::Expr<'tcx>,
1055 arg_exprs: &'tcx [hir::Expr<'tcx>],
1056 expected: Expectation<'tcx>,
1057 closure_def_id: LocalDefId,
1058 fn_sig: ty::FnSig<'tcx>,
1059 ) -> Ty<'tcx> {
1060 self.check_argument_types(
1065 call_expr.span,
1066 call_expr,
1067 fn_sig.inputs(),
1068 fn_sig.output(),
1069 expected,
1070 arg_exprs,
1071 fn_sig.fn_sig_kind.c_variadic(),
1072 TupleArgumentsFlag::rust_fn_trait_call(),
1073 Some(closure_def_id.to_def_id()),
1074 None,
1075 );
1076
1077 fn_sig.output()
1078 }
1079
1080 #[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(1080u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&["call_hir_id",
"callee_did", "callee_args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_did)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
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_hir::attrs::HasAttrs::get_attrs(self.body_def_id,
&self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDoNotConstCheck) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some() {
return;
}
let host =
match 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))]
1081 pub(super) fn enforce_context_effects(
1082 &self,
1083 call_hir_id: Option<HirId>,
1084 span: Span,
1085 callee_did: DefId,
1086 callee_args: GenericArgsRef<'tcx>,
1087 ) {
1088 let const_context = self.tcx.hir_body_const_context(self.body_def_id);
1089
1090 if let hir::Constness::Const { always: true } = self.tcx.constness(callee_did) {
1091 match const_context {
1092 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {}
1093 Some(hir::ConstContext::ConstFn) | None => {
1094 self.dcx().span_err(span, "comptime fns can only be called at compile time");
1095 }
1096 }
1097 }
1098
1099 if !self.tcx.features().const_trait_impl() {
1104 return;
1105 }
1106
1107 if self.has_rustc_attrs && find_attr!(self.tcx, self.body_def_id, RustcDoNotConstCheck) {
1109 return;
1110 }
1111
1112 let host = match const_context {
1113 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
1114 ty::BoundConstness::Const
1115 }
1116 Some(hir::ConstContext::ConstFn) => ty::BoundConstness::Maybe,
1117 None => return,
1118 };
1119
1120 if self.tcx.is_conditionally_const(callee_did) {
1123 let q = self.tcx.const_conditions(callee_did);
1124 for (idx, (cond, pred_span)) in
1125 q.instantiate(self.tcx, callee_args).into_iter().enumerate()
1126 {
1127 let cause = self.cause(
1128 span,
1129 if let Some(hir_id) = call_hir_id {
1130 ObligationCauseCode::HostEffectInExpr(callee_did, pred_span, hir_id, idx)
1131 } else {
1132 ObligationCauseCode::WhereClause(callee_did, pred_span)
1133 },
1134 );
1135 self.register_predicate(Obligation::new(
1136 self.tcx,
1137 cause,
1138 self.param_env,
1139 cond.to_host_effect_clause(self.tcx, host).skip_norm_wip(),
1140 ));
1141 }
1142 } else {
1143 }
1146 }
1147
1148 fn confirm_overloaded_call(
1149 &self,
1150 call_expr: &'tcx hir::Expr<'tcx>,
1151 arg_exprs: &'tcx [hir::Expr<'tcx>],
1152 expected: Expectation<'tcx>,
1153 method: MethodCallee<'tcx>,
1154 ) -> Ty<'tcx> {
1155 {
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!(
1158 method.sig.fn_sig_kind.splatted(),
1159 None,
1160 "splatting is not supported on RustCall tuples",
1161 );
1162 self.check_argument_types(
1163 call_expr.span,
1164 call_expr,
1165 &method.sig.inputs()[1..],
1166 method.sig.output(),
1167 expected,
1168 arg_exprs,
1169 method.sig.fn_sig_kind.c_variadic(),
1170 TupleArgumentsFlag::rust_fn_trait_call(),
1171 Some(method.def_id),
1172 None,
1173 );
1174
1175 self.write_method_call_and_enforce_effects(call_expr.hir_id, call_expr.span, method);
1176
1177 method.sig.output()
1178 }
1179}
1180
1181#[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)]
1182pub(crate) struct DeferredCallResolution<'tcx> {
1183 call_expr: &'tcx hir::Expr<'tcx>,
1184 callee_expr: &'tcx hir::Expr<'tcx>,
1185 closure_ty: Ty<'tcx>,
1186 adjustments: Vec<Adjustment<'tcx>>,
1187 fn_sig: ty::FnSig<'tcx>,
1188}
1189
1190impl<'a, 'tcx> DeferredCallResolution<'tcx> {
1191 pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) {
1192 {
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:1192",
"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(1192u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("DeferredCallResolution::resolve() {0:?}",
self) as &dyn Value))])
});
} else { ; }
};debug!("DeferredCallResolution::resolve() {:?}", self);
1193
1194 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());
1197
1198 match fcx.try_overloaded_call_traits(self.call_expr, self.closure_ty, None) {
1200 Some((autoref, method_callee)) => {
1201 let method_sig = method_callee.sig;
1210
1211 {
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:1211",
"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(1211u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::callee"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("attempt_resolution: method_callee={0:?}",
method_callee) as &dyn Value))])
});
} else { ; }
};debug!("attempt_resolution: method_callee={:?}", method_callee);
1212
1213 for (method_arg_ty, self_arg_ty) in
1214 iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
1215 {
1216 fcx.demand_eqtype(self.call_expr.span, *self_arg_ty, *method_arg_ty);
1217 }
1218
1219 fcx.demand_eqtype(self.call_expr.span, method_sig.output(), self.fn_sig.output());
1220
1221 let mut adjustments = self.adjustments;
1222 adjustments.extend(autoref);
1223 fcx.apply_adjustments(self.callee_expr, adjustments);
1224
1225 fcx.write_method_call_and_enforce_effects(
1226 self.call_expr.hir_id,
1227 self.call_expr.span,
1228 method_callee,
1229 );
1230 }
1231 None => {
1232 let guar = fcx.tainted_by_errors().unwrap_or_else(|| {
1233 fcx.dcx().span_delayed_bug(
1234 self.call_expr.span,
1235 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{0}`",
self.closure_ty))
})format!(
1236 "Expected to find a suitable `Fn`/`FnMut`/`FnOnce` implementation for `{}`",
1237 self.closure_ty
1238 ),
1239 )
1240 });
1241 fcx.write_resolution(self.call_expr.hir_id, Err(guar));
1242 }
1243 }
1244 }
1245}