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