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