]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/returns.rs
Merge pull request #1827 from erickt/master
[rust.git] / clippy_lints / src / returns.rs
1 use rustc::lint::*;
2 use syntax::ast;
3 use syntax::codemap::{Span, Spanned};
4 use syntax::visit::FnKind;
5
6 use utils::{span_note_and_lint, span_lint_and_then, snippet_opt, match_path_ast, in_macro,
7             in_external_macro};
8
9 /// **What it does:** Checks for return statements at the end of a block.
10 ///
11 /// **Why is this bad?** Removing the `return` and semicolon will make the code
12 /// more rusty.
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// fn foo(x: usize) { return x; }
19 /// ```
20 declare_lint! {
21     pub NEEDLESS_RETURN,
22     Warn,
23     "using a return statement like `return expr;` where an expression would suffice"
24 }
25
26 /// **What it does:** Checks for `let`-bindings, which are subsequently returned.
27 ///
28 /// **Why is this bad?** It is just extraneous code. Remove it to make your code
29 /// more rusty.
30 ///
31 /// **Known problems:** None.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// { let x = ..; x }
36 /// ```
37 declare_lint! {
38     pub LET_AND_RETURN,
39     Warn,
40     "creating a let-binding and then immediately returning it like `let x = expr; x` at \
41      the end of a block"
42 }
43
44 #[derive(Copy, Clone)]
45 pub struct ReturnPass;
46
47 impl ReturnPass {
48     // Check the final stmt or expr in a block for unnecessary return.
49     fn check_block_return(&mut self, cx: &EarlyContext, block: &ast::Block) {
50         if let Some(stmt) = block.stmts.last() {
51             match stmt.node {
52                 ast::StmtKind::Expr(ref expr) |
53                 ast::StmtKind::Semi(ref expr) => {
54                     self.check_final_expr(cx, expr, Some(stmt.span));
55                 },
56                 _ => (),
57             }
58         }
59     }
60
61     // Check a the final expression in a block if it's a return.
62     fn check_final_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr, span: Option<Span>) {
63         match expr.node {
64             // simple return is always "bad"
65             ast::ExprKind::Ret(Some(ref inner)) => {
66                 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
67                 if !expr.attrs.iter().any(attr_is_cfg) {
68                     self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
69                 }
70             },
71             // a whole block? check it!
72             ast::ExprKind::Block(ref block) => {
73                 self.check_block_return(cx, block);
74             },
75             // an if/if let expr, check both exprs
76             // note, if without else is going to be a type checking error anyways
77             // (except for unit type functions) so we don't match it
78             ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
79                 self.check_block_return(cx, ifblock);
80                 self.check_final_expr(cx, elsexpr, None);
81             },
82             // a match expr, check all arms
83             ast::ExprKind::Match(_, ref arms) => {
84                 for arm in arms {
85                     self.check_final_expr(cx, &arm.body, Some(arm.body.span));
86                 }
87             },
88             _ => (),
89         }
90     }
91
92     fn emit_return_lint(&mut self, cx: &EarlyContext, ret_span: Span, inner_span: Span) {
93         if in_external_macro(cx, inner_span) || in_macro(inner_span) {
94             return;
95         }
96         span_lint_and_then(cx,
97                            NEEDLESS_RETURN,
98                            ret_span,
99                            "unneeded return statement",
100                            |db| if let Some(snippet) = snippet_opt(cx, inner_span) {
101                                db.span_suggestion(ret_span, "remove `return` as shown:", snippet);
102                            });
103     }
104
105     // Check for "let x = EXPR; x"
106     fn check_let_return(&mut self, cx: &EarlyContext, block: &ast::Block) {
107         let mut it = block.stmts.iter();
108
109         // we need both a let-binding stmt and an expr
110         if_let_chain! {[
111             let Some(retexpr) = it.next_back(),
112             let ast::StmtKind::Expr(ref retexpr) = retexpr.node,
113             let Some(stmt) = it.next_back(),
114             let ast::StmtKind::Local(ref local) = stmt.node,
115             // don't lint in the presence of type inference
116             local.ty.is_none(),
117             !local.attrs.iter().any(attr_is_cfg),
118             let Some(ref initexpr) = local.init,
119             let ast::PatKind::Ident(_, Spanned { node: id, .. }, _) = local.pat.node,
120             let ast::ExprKind::Path(_, ref path) = retexpr.node,
121             match_path_ast(path, &[&id.name.as_str()]),
122             !in_external_macro(cx, initexpr.span),
123         ], {
124                 span_note_and_lint(cx,
125                                    LET_AND_RETURN,
126                                    retexpr.span,
127                                    "returning the result of a let binding from a block. \
128                                    Consider returning the expression directly.",
129                                    initexpr.span,
130                                    "this expression can be directly returned");
131         }}
132     }
133 }
134
135 impl LintPass for ReturnPass {
136     fn get_lints(&self) -> LintArray {
137         lint_array!(NEEDLESS_RETURN, LET_AND_RETURN)
138     }
139 }
140
141 impl EarlyLintPass for ReturnPass {
142     fn check_fn(&mut self, cx: &EarlyContext, kind: FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
143         match kind {
144             FnKind::ItemFn(.., block) |
145             FnKind::Method(.., block) => self.check_block_return(cx, block),
146             FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
147         }
148     }
149
150     fn check_block(&mut self, cx: &EarlyContext, block: &ast::Block) {
151         self.check_let_return(cx, block);
152     }
153 }
154
155 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
156     attr.meta_item_list().is_some() && attr.name().map_or(false, |n| n == "cfg")
157 }