2 diagnostics::span_lint_and_sugg,
3 get_async_fn_body, is_async_fn,
4 source::{snippet_with_applicability, snippet_with_context, walk_span_to_context},
5 visitors::expr_visitor_no_bodies,
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::{FnKind, Visitor};
9 use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::{Span, SyntaxContext};
15 declare_clippy_lint! {
17 /// Checks for missing return statements at the end of a block.
19 /// ### Why is this bad?
20 /// Actually omitting the return keyword is idiomatic Rust code. Programmers
21 /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
22 /// the last returning statement because the only difference is a missing `;`. Especially in bigger
23 /// code with multiple return paths having a `return` keyword makes it easier to find the
24 /// corresponding statements.
28 /// fn foo(x: usize) -> usize {
34 /// fn foo(x: usize) -> usize {
40 "use a return statement like `return expr` instead of an expression"
43 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
45 fn lint_return(cx: &LateContext<'_>, span: Span) {
46 let mut app = Applicability::MachineApplicable;
47 let snip = snippet_with_applicability(cx, span, "..", &mut app);
52 "missing `return` statement",
53 "add `return` as shown",
54 format!("return {}", snip),
59 fn lint_break(cx: &LateContext<'_>, break_span: Span, expr_span: Span) {
60 let mut app = Applicability::MachineApplicable;
61 let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
66 "missing `return` statement",
67 "change `break` to `return` as shown",
68 format!("return {}", snip),
73 #[derive(Clone, Copy, PartialEq, Eq)]
75 /// The lint was applied to a parent expression.
77 /// The lint was applied to this expression, a child, or not applied.
81 fn still_parent(self, b: bool) -> Self {
82 if b { self } else { Self::Inner }
85 fn is_parent(self) -> bool {
90 // Gets the call site if the span is in a child context. Otherwise returns `None`.
91 fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> {
92 (span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span))
95 fn lint_implicit_returns(
96 cx: &LateContext<'tcx>,
98 // The context of the function body.
100 // Whether the expression is from a macro expansion.
101 call_site_span: Option<Span>,
106 expr: Some(block_expr), ..
109 ) => lint_implicit_returns(
113 call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)),
115 .still_parent(call_site_span.is_some()),
117 ExprKind::If(_, then_expr, Some(else_expr)) => {
118 // Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't
120 let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some());
122 // The return was added as a parent of this if expression.
125 lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some())
128 ExprKind::Match(_, arms, _) => {
130 let res = lint_implicit_returns(
134 call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)),
136 .still_parent(call_site_span.is_some());
138 // The return was added as a parent of this match expression.
145 ExprKind::Loop(block, ..) => {
146 let mut add_return = false;
147 expr_visitor_no_bodies(|e| {
148 if let ExprKind::Break(dest, sub_expr) = e.kind {
149 if dest.target_id.ok() == Some(expr.hir_id) {
150 if call_site_span.is_none() && e.span.ctxt() == ctxt {
151 // At this point sub_expr can be `None` in async functions which either diverge, or return
153 if let Some(sub_expr) = sub_expr {
154 lint_break(cx, e.span, sub_expr.span);
157 // the break expression is from a macro call, add a return to the loop
166 #[allow(clippy::option_if_let_else)]
167 if let Some(span) = call_site_span {
168 lint_return(cx, span);
171 lint_return(cx, expr.span);
179 // If expressions without an else clause, and blocks without a final expression can only be the final expression
180 // if they are divergent, or return the unit type.
181 ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => {
185 // Any divergent expression doesn't need a return statement.
186 ExprKind::MethodCall(..)
188 | ExprKind::Binary(..)
189 | ExprKind::Unary(..)
190 | ExprKind::Index(..)
191 if cx.typeck_results().expr_ty(expr).is_never() =>
198 #[allow(clippy::option_if_let_else)]
199 if let Some(span) = call_site_span {
200 lint_return(cx, span);
203 lint_return(cx, expr.span);
210 impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
213 cx: &LateContext<'tcx>,
215 decl: &'tcx FnDecl<'_>,
216 body: &'tcx Body<'_>,
220 if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_)))
221 || span.ctxt() != body.value.span.ctxt()
222 || in_external_macro(cx.sess(), span)
227 let res_ty = cx.typeck_results().expr_ty(&body.value);
228 if res_ty.is_unit() || res_ty.is_never() {
232 let expr = if is_async_fn(kind) {
233 match get_async_fn_body(cx.tcx, body) {
240 lint_implicit_returns(cx, expr, expr.span.ctxt(), None);