]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/returns.rs
Improve docs
[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:** This lint 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 more rusty.
11 ///
12 /// **Known problems:** Following this lint's advice may currently run afoul of Rust issue
13 /// [#31439](https://github.com/rust-lang/rust/issues/31439), so if you get lifetime errors, please
14 /// roll back the change until that issue is fixed.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// fn foo(x: usize) { return x; }
19 /// ```
20 declare_lint! {
21     pub NEEDLESS_RETURN, Warn,
22     "using a return statement like `return expr;` where an expression would suffice"
23 }
24
25 /// **What it does:** This lint 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 more rusty.
28 ///
29 /// **Known problems:** Following this lint's advice may currently run afoul of Rust issue
30 /// [#31439](https://github.com/rust-lang/rust/issues/31439), so if you get lifetime errors, please
31 /// roll back the change until that issue is fixed.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// { let x = ..; x }
36 /// ```
37 declare_lint! {
38     pub LET_AND_RETURN, 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: &Block) {
49         if let Some(stmt) = block.stmts.last() {
50             match stmt.node {
51                 StmtKind::Expr(ref expr) | 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: &Expr, span: Option<Span>) {
61         match expr.node {
62             // simple return is always "bad"
63             ExprKind::Ret(Some(ref inner)) => {
64                 self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
65             }
66             // a whole block? check it!
67             ExprKind::Block(ref block) => {
68                 self.check_block_return(cx, block);
69             }
70             // an if/if let expr, check both exprs
71             // note, if without else is going to be a type checking error anyways
72             // (except for unit type functions) so we don't match it
73             ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
74                 self.check_block_return(cx, ifblock);
75                 self.check_final_expr(cx, elsexpr, None);
76             }
77             // a match expr, check all arms
78             ExprKind::Match(_, ref arms) => {
79                 for arm in arms {
80                     self.check_final_expr(cx, &arm.body, Some(arm.body.span));
81                 }
82             }
83             _ => (),
84         }
85     }
86
87     fn emit_return_lint(&mut self, cx: &EarlyContext, ret_span: Span, inner_span: Span) {
88         if in_external_macro(cx, inner_span) {
89             return;
90         }
91         span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
92             if let Some(snippet) = snippet_opt(cx, inner_span) {
93                 db.span_suggestion(ret_span, "remove `return` as shown:", snippet);
94             }
95         });
96     }
97
98     // Check for "let x = EXPR; x"
99     fn check_let_return(&mut self, cx: &EarlyContext, block: &Block) {
100         let mut it = block.stmts.iter();
101
102         // we need both a let-binding stmt and an expr
103         if_let_chain! {[
104             let Some(ref retexpr) = it.next_back(),
105             let StmtKind::Expr(ref retexpr) = retexpr.node,
106             let Some(stmt) = it.next_back(),
107             let StmtKind::Local(ref local) = stmt.node,
108             let Some(ref initexpr) = local.init,
109             let PatKind::Ident(_, Spanned { node: id, .. }, _) = local.pat.node,
110             let ExprKind::Path(_, ref path) = retexpr.node,
111             match_path_ast(path, &[&id.name.as_str()]),
112             !in_external_macro(cx, initexpr.span),
113         ], {
114                 span_note_and_lint(cx,
115                                    LET_AND_RETURN,
116                                    retexpr.span,
117                                    "returning the result of a let binding from a block. \
118                                    Consider returning the expression directly.",
119                                    initexpr.span,
120                                    "this expression can be directly returned");
121         }}
122     }
123 }
124
125 impl LintPass for ReturnPass {
126     fn get_lints(&self) -> LintArray {
127         lint_array!(NEEDLESS_RETURN, LET_AND_RETURN)
128     }
129 }
130
131 impl EarlyLintPass for ReturnPass {
132     fn check_fn(&mut self, cx: &EarlyContext, _: FnKind, _: &FnDecl, block: &Block, _: Span, _: NodeId) {
133         self.check_block_return(cx, block);
134     }
135
136     fn check_block(&mut self, cx: &EarlyContext, block: &Block) {
137         self.check_let_return(cx, block);
138     }
139 }