]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Auto merge of #3808 - mikerite:useless-format-suggestions, r=oli-obk
[rust.git] / clippy_lints / src / implicit_return.rs
1 use crate::utils::{in_macro, 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_tool_lint, lint_array};
5 use rustc_errors::Applicability;
6 use syntax::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(
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, source) => {
85                 let check_all_arms = match source {
86                     MatchSource::IfLetDesugar {
87                         contains_else_clause: has_else,
88                     } => *has_else,
89                     _ => true,
90                 };
91
92                 if check_all_arms {
93                     for arm in arms {
94                         Self::expr_match(cx, &arm.body);
95                     }
96                 } else {
97                     Self::expr_match(cx, &arms.first().expect("if let doesn't have a single arm").body);
98                 }
99             },
100             // skip if it already has a return statement
101             ExprKind::Ret(..) => (),
102             // everything else is missing `return`
103             _ => {
104                 // make sure it's not just an unreachable expression
105                 if is_expn_of(expr.span, "unreachable").is_none() {
106                     Self::lint(cx, expr.span, expr.span, "add `return` as shown")
107                 }
108             },
109         }
110     }
111 }
112
113 impl LintPass for Pass {
114     fn get_lints(&self) -> LintArray {
115         lint_array!(IMPLICIT_RETURN)
116     }
117
118     fn name(&self) -> &'static str {
119         "ImplicitReturn"
120     }
121 }
122
123 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
124     fn check_fn(
125         &mut self,
126         cx: &LateContext<'a, 'tcx>,
127         _: FnKind<'tcx>,
128         _: &'tcx FnDecl,
129         body: &'tcx Body,
130         span: Span,
131         _: HirId,
132     ) {
133         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
134         let mir = cx.tcx.optimized_mir(def_id);
135
136         // checking return type through MIR, HIR is not able to determine inferred closure return types
137         // make sure it's not a macro
138         if !mir.return_ty().is_unit() && !in_macro(span) {
139             Self::expr_match(cx, &body.value);
140         }
141     }
142 }