]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Auto merge of #4100 - phansch:add_stderr_length_check, r=flip1995
[rust.git] / clippy_lints / src / implicit_return.rs
1 use crate::utils::{in_macro_or_desugar, is_expn_of, snippet_opt, span_lint_and_then};
2 use rustc::hir::{intravisit::FnKind, Body, ExprKind, FnDecl, HirId, MatchSource};
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_lint_pass, declare_tool_lint};
5 use rustc_errors::Applicability;
6 use syntax::source_map::Span;
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for missing return statements at the end of a block.
10     ///
11     /// **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers
12     /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
13     /// the last returning statement because the only difference is a missing `;`. Especially in bigger
14     /// code with multiple return paths having a `return` keyword makes it easier to find the
15     /// corresponding statements.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```rust
21     /// fn foo(x: usize) {
22     ///     x
23     /// }
24     /// ```
25     /// add return
26     /// ```rust
27     /// fn foo(x: usize) {
28     ///     return x;
29     /// }
30     /// ```
31     pub IMPLICIT_RETURN,
32     restriction,
33     "use a return statement like `return expr` instead of an expression"
34 }
35
36 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
37
38 impl ImplicitReturn {
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(
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::Match(.., arms, source) => {
78                 let check_all_arms = match source {
79                     MatchSource::IfLetDesugar {
80                         contains_else_clause: has_else,
81                     } => *has_else,
82                     _ => true,
83                 };
84
85                 if check_all_arms {
86                     for arm in arms {
87                         Self::expr_match(cx, &arm.body);
88                     }
89                 } else {
90                     Self::expr_match(cx, &arms.first().expect("if let doesn't have a single arm").body);
91                 }
92             },
93             // skip if it already has a return statement
94             ExprKind::Ret(..) => (),
95             // everything else is missing `return`
96             _ => {
97                 // make sure it's not just an unreachable expression
98                 if is_expn_of(expr.span, "unreachable").is_none() {
99                     Self::lint(cx, expr.span, expr.span, "add `return` as shown")
100                 }
101             },
102         }
103     }
104 }
105
106 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitReturn {
107     fn check_fn(
108         &mut self,
109         cx: &LateContext<'a, 'tcx>,
110         _: FnKind<'tcx>,
111         _: &'tcx FnDecl,
112         body: &'tcx Body,
113         span: Span,
114         _: HirId,
115     ) {
116         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
117         let mir = cx.tcx.optimized_mir(def_id);
118
119         // checking return type through MIR, HIR is not able to determine inferred closure return types
120         // make sure it's not a macro
121         if !mir.return_ty().is_unit() && !in_macro_or_desugar(span) {
122             Self::expr_match(cx, &body.value);
123         }
124     }
125 }