]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
cd5db359628a1226f4b56190034f9ca1e2547dcf
[rust.git] / clippy_lints / src / implicit_return.rs
1 use crate::utils::{in_macro, snippet_opt, span_lint_and_then};
2 use rustc::hir::{intravisit::FnKind, Body, ExprKind, FnDecl};
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5 use rustc_errors::Applicability;
6 use syntax::{ast::NodeId, source_map::Span};
7
8 /// **What it does:** Checks for missing return statements at the end of a block.
9 ///
10 /// **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers
11 /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
12 /// the last returning statement because the only difference is a missing `;`. Especially in bigger
13 /// code with multiple return paths having a `return` keyword makes it easier to find the
14 /// corresponding statements.
15 ///
16 /// **Known problems:** None.
17 ///
18 /// **Example:**
19 /// ```rust
20 /// fn foo(x: usize) {
21 ///     x
22 /// }
23 /// ```
24 /// add return
25 /// ```rust
26 /// fn foo(x: usize) {
27 ///     return x;
28 /// }
29 /// ```
30 declare_clippy_lint! {
31     pub IMPLICIT_RETURN,
32     restriction,
33     "use a return statement like `return expr` instead of an expression"
34 }
35
36 pub struct Pass;
37
38 impl Pass {
39     fn lint(cx: &LateContext<'_, '_>, outer_span: syntax_pos::Span, inner_span: syntax_pos::Span, msg: &str) {
40         span_lint_and_then(cx, IMPLICIT_RETURN, outer_span, "missing return statement", |db| {
41             if let Some(snippet) = snippet_opt(cx, inner_span) {
42                 db.span_suggestion_with_applicability(
43                     outer_span,
44                     msg,
45                     format!("return {}", snippet),
46                     Applicability::MachineApplicable,
47                 );
48             }
49         });
50     }
51
52     fn expr_match(cx: &LateContext<'_, '_>, expr: &rustc::hir::Expr) {
53         match &expr.node {
54             // loops could be using `break` instead of `return`
55             ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => {
56                 if let Some(expr) = &block.expr {
57                     Self::expr_match(cx, expr);
58                 }
59                 // only needed in the case of `break` with `;` at the end
60                 else if let Some(stmt) = block.stmts.last() {
61                     if let rustc::hir::StmtKind::Semi(expr, ..) = &stmt.node {
62                         // make sure it's a break, otherwise we want to skip
63                         if let ExprKind::Break(.., break_expr) = &expr.node {
64                             if let Some(break_expr) = break_expr {
65                                 Self::lint(cx, expr.span, break_expr.span, "change `break` to `return` as shown");
66                             }
67                         }
68                     }
69                 }
70             },
71             // use `return` instead of `break`
72             ExprKind::Break(.., break_expr) => {
73                 if let Some(break_expr) = break_expr {
74                     Self::lint(cx, expr.span, break_expr.span, "change `break` to `return` as shown");
75                 }
76             },
77             ExprKind::If(.., if_expr, else_expr) => {
78                 Self::expr_match(cx, if_expr);
79
80                 if let Some(else_expr) = else_expr {
81                     Self::expr_match(cx, else_expr);
82                 }
83             },
84             ExprKind::Match(_, arms, ..) => {
85                 for arm in arms {
86                     Self::expr_match(cx, &arm.body);
87                 }
88             },
89             // skip if it already has a return statement
90             ExprKind::Ret(..) => (),
91             // everything else is missing `return`
92             _ => Self::lint(cx, expr.span, expr.span, "add `return` as shown"),
93         }
94     }
95 }
96
97 impl LintPass for Pass {
98     fn get_lints(&self) -> LintArray {
99         lint_array!(IMPLICIT_RETURN)
100     }
101 }
102
103 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
104     fn check_fn(
105         &mut self,
106         cx: &LateContext<'a, 'tcx>,
107         _: FnKind<'tcx>,
108         _: &'tcx FnDecl,
109         body: &'tcx Body,
110         span: Span,
111         _: NodeId,
112     ) {
113         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
114         let mir = cx.tcx.optimized_mir(def_id);
115
116         // checking return type through MIR, HIR is not able to determine inferred closure return types
117         // make sure it's not a macro
118         if !mir.return_ty().is_unit() && !in_macro(span) {
119             Self::expr_match(cx, &body.value);
120         }
121     }
122 }