1use rustc_abi::ExternAbi;
2use rustc_data_structures::stack::ensure_sufficient_stack;
3use rustc_errors::Applicability;
4use rustc_hir::LangItem;
5use rustc_hir::def::DefKind;
6use rustc_hir::def_id::CRATE_DEF_ID;
7use rustc_middle::span_bug;
8use rustc_middle::thir::visit::{self, Visitor};
9use rustc_middle::thir::{BodyTy, Expr, ExprId, ExprKind, Thir};
10use rustc_middle::ty::{self, Ty, TyCtxt};
11use rustc_span::def_id::{DefId, LocalDefId};
12use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
13
14pub(crate) fn check_tail_calls(tcx: TyCtxt<'_>, def: LocalDefId) -> Result<(), ErrorGuaranteed> {
15 let (thir, expr) = tcx.thir_body(def)?;
16 let thir = &thir.borrow();
17
18 if thir.exprs.is_empty() {
20 return Ok(());
21 }
22
23 let is_closure = matches!(tcx.def_kind(def), DefKind::Closure);
24 let caller_ty = tcx.type_of(def).skip_binder();
25
26 let mut visitor = TailCallCkVisitor {
27 tcx,
28 thir,
29 found_errors: Ok(()),
30 typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
32 is_closure,
33 caller_ty,
34 };
35
36 visitor.visit_expr(&thir[expr]);
37
38 visitor.found_errors
39}
40
41struct TailCallCkVisitor<'a, 'tcx> {
42 tcx: TyCtxt<'tcx>,
43 thir: &'a Thir<'tcx>,
44 typing_env: ty::TypingEnv<'tcx>,
45 is_closure: bool,
47 found_errors: Result<(), ErrorGuaranteed>,
50 caller_ty: Ty<'tcx>,
52}
53
54impl<'tcx> TailCallCkVisitor<'_, 'tcx> {
55 fn check_tail_call(&mut self, call: &Expr<'_>, expr: &Expr<'_>) {
56 if self.is_closure {
57 self.report_in_closure(expr);
58 return;
59 }
60
61 let BodyTy::Fn(caller_sig) = self.thir.body_type else {
62 span_bug!(
63 call.span,
64 "`become` outside of functions should have been disallowed by hir_typeck"
65 )
66 };
67 let caller_sig = self.tcx.erase_and_anonymize_regions(caller_sig);
71
72 let ExprKind::Scope { value, .. } = call.kind else {
73 span_bug!(call.span, "expected scope, found: {call:?}")
74 };
75 let value = &self.thir[value];
76
77 if matches!(
78 value.kind,
79 ExprKind::Binary { .. }
80 | ExprKind::Unary { .. }
81 | ExprKind::AssignOp { .. }
82 | ExprKind::Index { .. }
83 ) {
84 self.report_builtin_op(call, expr);
85 return;
86 }
87
88 let ExprKind::Call { ty, fun, ref args, from_hir_call, fn_span } = value.kind else {
89 self.report_non_call(value, expr);
90 return;
91 };
92
93 if !from_hir_call {
94 self.report_op(ty, args, fn_span, expr);
95 }
96
97 if let &ty::FnDef(did, args) = ty.kind() {
98 let parent = self.tcx.parent(did);
102 if self.tcx.fn_trait_kind_from_def_id(parent).is_some()
103 && let Some(this) = args.first()
104 && let Some(this) = this.as_type()
105 {
106 if this.is_closure() {
107 self.report_calling_closure(&self.thir[fun], args[1].as_type().unwrap(), expr);
108 } else {
109 self.report_nonfn_callee(fn_span, self.thir[fun].span, this);
111 }
112
113 return;
116 };
117
118 if self.tcx.intrinsic(did).is_some() {
119 self.report_calling_intrinsic(expr);
120 }
121 }
122
123 let (ty::FnDef(..) | ty::FnPtr(..)) = ty.kind() else {
124 self.report_nonfn_callee(fn_span, self.thir[fun].span, ty);
125
126 return;
128 };
129
130 let callee_sig =
132 self.tcx.normalize_erasing_late_bound_regions(self.typing_env, ty.fn_sig(self.tcx));
133
134 if caller_sig.abi != callee_sig.abi {
135 self.report_abi_mismatch(expr.span, caller_sig.abi, callee_sig.abi);
136 }
137
138 if !callee_sig.abi.supports_guaranteed_tail_call() {
139 self.report_unsupported_abi(expr.span, callee_sig.abi);
140 }
141
142 if caller_sig.inputs_and_output != callee_sig.inputs_and_output {
151 self.report_signature_mismatch(
152 expr.span,
153 self.tcx.liberate_late_bound_regions(
154 CRATE_DEF_ID.to_def_id(),
155 self.caller_ty.fn_sig(self.tcx),
156 ),
157 self.tcx.liberate_late_bound_regions(CRATE_DEF_ID.to_def_id(), ty.fn_sig(self.tcx)),
158 );
159 }
160
161 {
162 let caller_needs_location = self.needs_location(self.caller_ty);
177
178 if caller_needs_location {
179 self.report_track_caller_caller(expr.span);
180 }
181 }
182
183 if caller_sig.c_variadic {
184 self.report_c_variadic_caller(expr.span);
185 }
186
187 if callee_sig.c_variadic {
188 self.report_c_variadic_callee(expr.span);
189 }
190 }
191
192 fn needs_location(&self, ty: Ty<'tcx>) -> bool {
197 if let &ty::FnDef(did, substs) = ty.kind() {
198 let instance =
199 ty::Instance::expect_resolve(self.tcx, self.typing_env, did, substs, DUMMY_SP);
200
201 instance.def.requires_caller_location(self.tcx)
202 } else {
203 false
204 }
205 }
206
207 fn report_in_closure(&mut self, expr: &Expr<'_>) {
208 let err = self.tcx.dcx().span_err(expr.span, "`become` is not allowed in closures");
209 self.found_errors = Err(err);
210 }
211
212 fn report_builtin_op(&mut self, value: &Expr<'_>, expr: &Expr<'_>) {
213 let err = self
214 .tcx
215 .dcx()
216 .struct_span_err(value.span, "`become` does not support operators")
217 .with_note("using `become` on a builtin operator is not useful")
218 .with_span_suggestion(
219 value.span.until(expr.span),
220 "try using `return` instead",
221 "return ",
222 Applicability::MachineApplicable,
223 )
224 .emit();
225 self.found_errors = Err(err);
226 }
227
228 fn report_op(&mut self, fun_ty: Ty<'_>, args: &[ExprId], fn_span: Span, expr: &Expr<'_>) {
229 let mut err =
230 self.tcx.dcx().struct_span_err(fn_span, "`become` does not support operators");
231
232 if let &ty::FnDef(did, _substs) = fun_ty.kind()
233 && let parent = self.tcx.parent(did)
234 && matches!(self.tcx.def_kind(parent), DefKind::Trait)
235 && let Some(method) = op_trait_as_method_name(self.tcx, parent)
236 {
237 match args {
238 &[arg] => {
239 let arg = &self.thir[arg];
240
241 err.multipart_suggestion(
242 "try using the method directly",
243 vec![
244 (fn_span.shrink_to_lo().until(arg.span), "(".to_owned()),
245 (arg.span.shrink_to_hi(), format!(").{method}()")),
246 ],
247 Applicability::MaybeIncorrect,
248 );
249 }
250 &[lhs, rhs] => {
251 let lhs = &self.thir[lhs];
252 let rhs = &self.thir[rhs];
253
254 err.multipart_suggestion(
255 "try using the method directly",
256 vec![
257 (lhs.span.shrink_to_lo(), format!("(")),
258 (lhs.span.between(rhs.span), format!(").{method}(")),
259 (rhs.span.between(expr.span.shrink_to_hi()), ")".to_owned()),
260 ],
261 Applicability::MaybeIncorrect,
262 );
263 }
264 _ => span_bug!(expr.span, "operator with more than 2 args? {args:?}"),
265 }
266 }
267
268 self.found_errors = Err(err.emit());
269 }
270
271 fn report_non_call(&mut self, value: &Expr<'_>, expr: &Expr<'_>) {
272 let err = self
273 .tcx
274 .dcx()
275 .struct_span_err(value.span, "`become` requires a function call")
276 .with_span_note(value.span, "not a function call")
277 .with_span_suggestion(
278 value.span.until(expr.span),
279 "try using `return` instead",
280 "return ",
281 Applicability::MaybeIncorrect,
282 )
283 .emit();
284 self.found_errors = Err(err);
285 }
286
287 fn report_calling_closure(&mut self, fun: &Expr<'_>, tupled_args: Ty<'_>, expr: &Expr<'_>) {
288 let underscored_args = match tupled_args.kind() {
289 ty::Tuple(tys) if tys.is_empty() => "".to_owned(),
290 ty::Tuple(tys) => std::iter::repeat_n("_, ", tys.len() - 1).chain(["_"]).collect(),
291 _ => "_".to_owned(),
292 };
293
294 let err = self
295 .tcx
296 .dcx()
297 .struct_span_err(expr.span, "tail calling closures directly is not allowed")
298 .with_multipart_suggestion(
299 "try casting the closure to a function pointer type",
300 vec![
301 (fun.span.shrink_to_lo(), "(".to_owned()),
302 (fun.span.shrink_to_hi(), format!(" as fn({underscored_args}) -> _)")),
303 ],
304 Applicability::MaybeIncorrect,
305 )
306 .emit();
307 self.found_errors = Err(err);
308 }
309
310 fn report_calling_intrinsic(&mut self, expr: &Expr<'_>) {
311 let err = self
312 .tcx
313 .dcx()
314 .struct_span_err(expr.span, "tail calling intrinsics is not allowed")
315 .emit();
316
317 self.found_errors = Err(err);
318 }
319
320 fn report_nonfn_callee(&mut self, call_sp: Span, fun_sp: Span, ty: Ty<'_>) {
321 let mut err = self
322 .tcx
323 .dcx()
324 .struct_span_err(
325 call_sp,
326 "tail calls can only be performed with function definitions or pointers",
327 )
328 .with_note(format!("callee has type `{ty}`"));
329
330 let mut ty = ty;
331 let mut refs = 0;
332 while ty.is_box() || ty.is_ref() {
333 ty = ty.builtin_deref(false).unwrap();
334 refs += 1;
335 }
336
337 if refs > 0 && ty.is_fn() {
338 let thing = if ty.is_fn_ptr() { "pointer" } else { "definition" };
339
340 let derefs =
341 std::iter::once('(').chain(std::iter::repeat_n('*', refs)).collect::<String>();
342
343 err.multipart_suggestion(
344 format!("consider dereferencing the expression to get a function {thing}"),
345 vec![(fun_sp.shrink_to_lo(), derefs), (fun_sp.shrink_to_hi(), ")".to_owned())],
346 Applicability::MachineApplicable,
347 );
348 }
349
350 let err = err.emit();
351 self.found_errors = Err(err);
352 }
353
354 fn report_abi_mismatch(&mut self, sp: Span, caller_abi: ExternAbi, callee_abi: ExternAbi) {
355 let err = self
356 .tcx
357 .dcx()
358 .struct_span_err(sp, "mismatched function ABIs")
359 .with_note("`become` requires caller and callee to have the same ABI")
360 .with_note(format!("caller ABI is `{caller_abi}`, while callee ABI is `{callee_abi}`"))
361 .emit();
362 self.found_errors = Err(err);
363 }
364
365 fn report_unsupported_abi(&mut self, sp: Span, callee_abi: ExternAbi) {
366 let err = self
367 .tcx
368 .dcx()
369 .struct_span_err(sp, "ABI does not support guaranteed tail calls")
370 .with_note(format!("`become` is not supported for `extern {callee_abi}` functions"))
371 .emit();
372 self.found_errors = Err(err);
373 }
374
375 fn report_signature_mismatch(
376 &mut self,
377 sp: Span,
378 caller_sig: ty::FnSig<'_>,
379 callee_sig: ty::FnSig<'_>,
380 ) {
381 let err = self
382 .tcx
383 .dcx()
384 .struct_span_err(sp, "mismatched signatures")
385 .with_note("`become` requires caller and callee to have matching signatures")
386 .with_note(format!("caller signature: `{caller_sig}`"))
387 .with_note(format!("callee signature: `{callee_sig}`"))
388 .emit();
389 self.found_errors = Err(err);
390 }
391
392 fn report_track_caller_caller(&mut self, sp: Span) {
393 let err = self
394 .tcx
395 .dcx()
396 .struct_span_err(
397 sp,
398 "a function marked with `#[track_caller]` cannot perform a tail-call",
399 )
400 .emit();
401
402 self.found_errors = Err(err);
403 }
404
405 fn report_c_variadic_caller(&mut self, sp: Span) {
406 let err = self
407 .tcx
408 .dcx()
409 .struct_span_err(sp, "tail-calls are not allowed in c-variadic functions")
411 .emit();
412
413 self.found_errors = Err(err);
414 }
415
416 fn report_c_variadic_callee(&mut self, sp: Span) {
417 let err = self
418 .tcx
419 .dcx()
420 .struct_span_err(sp, "c-variadic functions can't be tail-called")
422 .emit();
423
424 self.found_errors = Err(err);
425 }
426}
427
428impl<'a, 'tcx> Visitor<'a, 'tcx> for TailCallCkVisitor<'a, 'tcx> {
429 fn thir(&self) -> &'a Thir<'tcx> {
430 &self.thir
431 }
432
433 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
434 ensure_sufficient_stack(|| {
435 if let ExprKind::Become { value } = expr.kind {
436 let call = &self.thir[value];
437 self.check_tail_call(call, expr);
438 }
439
440 visit::walk_expr(self, expr);
441 });
442 }
443}
444
445fn op_trait_as_method_name(tcx: TyCtxt<'_>, trait_did: DefId) -> Option<&'static str> {
446 let m = match tcx.as_lang_item(trait_did)? {
447 LangItem::Add => "add",
448 LangItem::Sub => "sub",
449 LangItem::Mul => "mul",
450 LangItem::Div => "div",
451 LangItem::Rem => "rem",
452 LangItem::Neg => "neg",
453 LangItem::Not => "not",
454 LangItem::BitXor => "bitxor",
455 LangItem::BitAnd => "bitand",
456 LangItem::BitOr => "bitor",
457 LangItem::Shl => "shl",
458 LangItem::Shr => "shr",
459 LangItem::AddAssign => "add_assign",
460 LangItem::SubAssign => "sub_assign",
461 LangItem::MulAssign => "mul_assign",
462 LangItem::DivAssign => "div_assign",
463 LangItem::RemAssign => "rem_assign",
464 LangItem::BitXorAssign => "bitxor_assign",
465 LangItem::BitAndAssign => "bitand_assign",
466 LangItem::BitOrAssign => "bitor_assign",
467 LangItem::ShlAssign => "shl_assign",
468 LangItem::ShrAssign => "shr_assign",
469 LangItem::Index => "index",
470 LangItem::IndexMut => "index_mut",
471 _ => return None,
472 };
473
474 Some(m)
475}