2 diagnostics::span_lint_hir_and_then,
3 get_async_fn_body, is_async_fn,
4 source::{snippet_with_applicability, snippet_with_context, walk_span_to_context},
5 visitors::for_each_expr,
7 use core::ops::ControlFlow;
8 use rustc_errors::Applicability;
9 use rustc_hir::intravisit::FnKind;
10 use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::def_id::LocalDefId;
15 use rustc_span::{Span, SyntaxContext};
17 declare_clippy_lint! {
19 /// Checks for missing return statements at the end of a block.
21 /// ### Why is this bad?
22 /// Actually omitting the return keyword is idiomatic Rust code. Programmers
23 /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
24 /// the last returning statement because the only difference is a missing `;`. Especially in bigger
25 /// code with multiple return paths having a `return` keyword makes it easier to find the
26 /// corresponding statements.
30 /// fn foo(x: usize) -> usize {
36 /// fn foo(x: usize) -> usize {
40 #[clippy::version = "1.33.0"]
43 "use a return statement like `return expr` instead of an expression"
46 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
48 fn lint_return(cx: &LateContext<'_>, emission_place: HirId, span: Span) {
49 let mut app = Applicability::MachineApplicable;
50 let snip = snippet_with_applicability(cx, span, "..", &mut app);
51 span_lint_hir_and_then(
56 "missing `return` statement",
58 diag.span_suggestion(span, "add `return` as shown", format!("return {snip}"), app);
63 fn lint_break(cx: &LateContext<'_>, emission_place: HirId, break_span: Span, expr_span: Span) {
64 let mut app = Applicability::MachineApplicable;
65 let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
66 span_lint_hir_and_then(
71 "missing `return` statement",
75 "change `break` to `return` as shown",
76 format!("return {snip}"),
83 #[derive(Clone, Copy, PartialEq, Eq)]
85 /// The lint was applied to a parent expression.
87 /// The lint was applied to this expression, a child, or not applied.
91 fn still_parent(self, b: bool) -> Self {
92 if b { self } else { Self::Inner }
95 fn is_parent(self) -> bool {
100 // Gets the call site if the span is in a child context. Otherwise returns `None`.
101 fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> {
102 (span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span))
105 fn lint_implicit_returns(
106 cx: &LateContext<'_>,
108 // The context of the function body.
110 // Whether the expression is from a macro expansion.
111 call_site_span: Option<Span>,
116 expr: Some(block_expr), ..
119 ) => lint_implicit_returns(
123 call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)),
125 .still_parent(call_site_span.is_some()),
127 ExprKind::If(_, then_expr, Some(else_expr)) => {
128 // Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't
130 let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some());
132 // The return was added as a parent of this if expression.
135 lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some())
138 ExprKind::Match(_, arms, _) => {
140 let res = lint_implicit_returns(
144 call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)),
146 .still_parent(call_site_span.is_some());
148 // The return was added as a parent of this match expression.
155 ExprKind::Loop(block, ..) => {
156 let mut add_return = false;
157 let _: Option<!> = for_each_expr(block, |e| {
158 if let ExprKind::Break(dest, sub_expr) = e.kind {
159 if dest.target_id.ok() == Some(expr.hir_id) {
160 if call_site_span.is_none() && e.span.ctxt() == ctxt {
161 // At this point sub_expr can be `None` in async functions which either diverge, or return
163 if let Some(sub_expr) = sub_expr {
164 lint_break(cx, e.hir_id, e.span, sub_expr.span);
167 // the break expression is from a macro call, add a return to the loop
172 ControlFlow::Continue(())
175 #[expect(clippy::option_if_let_else)]
176 if let Some(span) = call_site_span {
177 lint_return(cx, expr.hir_id, span);
180 lint_return(cx, expr.hir_id, expr.span);
188 // If expressions without an else clause, and blocks without a final expression can only be the final expression
189 // if they are divergent, or return the unit type.
190 ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => {
194 // Any divergent expression doesn't need a return statement.
195 ExprKind::MethodCall(..)
197 | ExprKind::Binary(..)
198 | ExprKind::Unary(..)
199 | ExprKind::Index(..)
200 if cx.typeck_results().expr_ty(expr).is_never() =>
207 #[expect(clippy::option_if_let_else)]
208 if let Some(span) = call_site_span {
209 lint_return(cx, expr.hir_id, span);
212 lint_return(cx, expr.hir_id, expr.span);
219 impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
222 cx: &LateContext<'tcx>,
224 decl: &'tcx FnDecl<'_>,
225 body: &'tcx Body<'_>,
229 if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_)))
230 || span.ctxt() != body.value.span.ctxt()
231 || in_external_macro(cx.sess(), span)
236 let res_ty = cx.typeck_results().expr_ty(body.value);
237 if res_ty.is_unit() || res_ty.is_never() {
241 let expr = if is_async_fn(kind) {
242 match get_async_fn_body(cx.tcx, body) {
249 lint_implicit_returns(cx, expr, expr.span.ctxt(), None);