2 diagnostics::span_lint_and_sugg,
3 source::{snippet_with_applicability, snippet_with_context, walk_span_to_context},
4 visitors::visit_break_exprs,
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::FnKind;
8 use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::{Span, SyntaxContext};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for missing return statements at the end of a block.
17 /// **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers
18 /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
19 /// the last returning statement because the only difference is a missing `;`. Especially in bigger
20 /// code with multiple return paths having a `return` keyword makes it easier to find the
21 /// corresponding statements.
23 /// **Known problems:** None.
27 /// fn foo(x: usize) -> usize {
33 /// fn foo(x: usize) -> usize {
39 "use a return statement like `return expr` instead of an expression"
42 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
44 fn lint_return(cx: &LateContext<'_>, span: Span) {
45 let mut app = Applicability::MachineApplicable;
46 let snip = snippet_with_applicability(cx, span, "..", &mut app);
51 "missing `return` statement",
52 "add `return` as shown",
53 format!("return {}", snip),
58 fn lint_break(cx: &LateContext<'_>, break_span: Span, expr_span: Span) {
59 let mut app = Applicability::MachineApplicable;
60 let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
65 "missing `return` statement",
66 "change `break` to `return` as shown",
67 format!("return {}", snip),
73 /// The lint was applied to a parent expression.
75 /// The lint was applied to this expression, a child, or not applied.
79 fn still_parent(self, b: bool) -> Self {
80 if b { self } else { Self::Inner }
83 fn is_parent(&self) -> bool {
84 matches!(*self, Self::Parent)
88 // Gets the call site if the span is in a child context. Otherwise returns `None`.
89 fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> {
90 (span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span))
93 fn lint_implicit_returns(
94 cx: &LateContext<'tcx>,
96 // The context of the function body.
98 // Whether the expression is from a macro expansion.
99 call_site_span: Option<Span>,
104 expr: Some(block_expr), ..
107 ) => lint_implicit_returns(
111 call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)),
113 .still_parent(call_site_span.is_some()),
115 ExprKind::If(_, then_expr, Some(else_expr)) => {
116 // Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't
118 let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some());
120 // The return was added as a parent of this if expression.
123 lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some())
126 ExprKind::Match(_, arms, _) => {
128 let res = lint_implicit_returns(
132 call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)),
134 .still_parent(call_site_span.is_some());
136 // The return was added as a parent of this match expression.
143 ExprKind::Loop(block, ..) => {
144 let mut add_return = false;
145 visit_break_exprs(block, |break_expr, dest, sub_expr| {
146 if dest.target_id.ok() == Some(expr.hir_id) {
147 if call_site_span.is_none() && break_expr.span.ctxt() == ctxt {
148 lint_break(cx, break_expr.span, sub_expr.unwrap().span);
150 // the break expression is from a macro call, add a return to the loop
156 #[allow(clippy::option_if_let_else)]
157 if let Some(span) = call_site_span {
158 lint_return(cx, span);
161 lint_return(cx, expr.span);
169 // If expressions without an else clause, and blocks without a final expression can only be the final expression
170 // if they are divergent, or return the unit type.
171 ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => {
175 // Any divergent expression doesn't need a return statement.
176 ExprKind::MethodCall(..)
178 | ExprKind::Binary(..)
179 | ExprKind::Unary(..)
180 | ExprKind::Index(..)
181 if cx.typeck_results().expr_ty(expr).is_never() =>
188 #[allow(clippy::option_if_let_else)]
189 if let Some(span) = call_site_span {
190 lint_return(cx, span);
193 lint_return(cx, expr.span);
200 impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
203 cx: &LateContext<'tcx>,
205 decl: &'tcx FnDecl<'_>,
206 body: &'tcx Body<'_>,
210 if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_)))
211 || span.ctxt() != body.value.span.ctxt()
212 || in_external_macro(cx.sess(), span)
217 let res_ty = cx.typeck_results().expr_ty(&body.value);
218 if res_ty.is_unit() || res_ty.is_never() {
222 lint_implicit_returns(cx, &body.value, body.value.span.ctxt(), None);