]> git.lizzy.rs Git - rust.git/blob - src/returns.rs
Rustup to *1.10.0-nightly (cd6a40017 2016-05-16)*
[rust.git] / 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_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 [#31439](https://github.com/rust-lang/rust/issues/31439), so if you get lifetime errors, please roll back the change until that issue is fixed.
13 ///
14 /// **Example:** `fn foo(x: usize) { return x; }`
15 declare_lint! {
16     pub NEEDLESS_RETURN, Warn,
17     "using a return statement like `return expr;` where an expression would suffice"
18 }
19
20 /// **What it does:** This lint checks for `let`-bindings, which are subsequently returned.
21 ///
22 /// **Why is this bad?** It is just extraneous code. Remove it to make your code more rusty.
23 ///
24 /// **Known problems:** Following this lint's advice may currently run afoul of Rust issue [#31439](https://github.com/rust-lang/rust/issues/31439), so if you get lifetime errors, please roll back the change until that issue is fixed.
25 ///
26 /// **Example:** `{ let x = ..; x }`
27 declare_lint! {
28     pub LET_AND_RETURN, Warn,
29     "creating a let-binding and then immediately returning it like `let x = expr; x` at \
30      the end of a block"
31 }
32
33 #[derive(Copy, Clone)]
34 pub struct ReturnPass;
35
36 impl ReturnPass {
37     // Check the final stmt or expr in a block for unnecessary return.
38     fn check_block_return(&mut self, cx: &EarlyContext, block: &Block) {
39         if let Some(ref expr) = block.expr {
40             self.check_final_expr(cx, expr);
41         } else if let Some(stmt) = block.stmts.last() {
42             if let StmtKind::Semi(ref expr, _) = stmt.node {
43                 if let ExprKind::Ret(Some(ref inner)) = expr.node {
44                     self.emit_return_lint(cx, (stmt.span, inner.span));
45                 }
46             }
47         }
48     }
49
50     // Check a the final expression in a block if it's a return.
51     fn check_final_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
52         match expr.node {
53             // simple return is always "bad"
54             ExprKind::Ret(Some(ref inner)) => {
55                 self.emit_return_lint(cx, (expr.span, inner.span));
56             }
57             // a whole block? check it!
58             ExprKind::Block(ref block) => {
59                 self.check_block_return(cx, block);
60             }
61             // an if/if let expr, check both exprs
62             // note, if without else is going to be a type checking error anyways
63             // (except for unit type functions) so we don't match it
64             ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
65                 self.check_block_return(cx, ifblock);
66                 self.check_final_expr(cx, elsexpr);
67             }
68             // a match expr, check all arms
69             ExprKind::Match(_, ref arms) => {
70                 for arm in arms {
71                     self.check_final_expr(cx, &arm.body);
72                 }
73             }
74             _ => (),
75         }
76     }
77
78     fn emit_return_lint(&mut self, cx: &EarlyContext, spans: (Span, Span)) {
79         if in_external_macro(cx, spans.1) {
80             return;
81         }
82         span_lint_and_then(cx, NEEDLESS_RETURN, spans.0, "unneeded return statement", |db| {
83             if let Some(snippet) = snippet_opt(cx, spans.1) {
84                 db.span_suggestion(spans.0, "remove `return` as shown:", snippet);
85             }
86         });
87     }
88
89     // Check for "let x = EXPR; x"
90     fn check_let_return(&mut self, cx: &EarlyContext, block: &Block) {
91         // we need both a let-binding stmt and an expr
92         if_let_chain! {
93             [
94                 let Some(stmt) = block.stmts.last(),
95                 let Some(ref retexpr) = block.expr,
96                 let StmtKind::Decl(ref decl, _) = stmt.node,
97                 let DeclKind::Local(ref local) = decl.node,
98                 let Some(ref initexpr) = local.init,
99                 let PatKind::Ident(_, Spanned { node: id, .. }, _) = local.pat.node,
100                 let ExprKind::Path(_, ref path) = retexpr.node,
101                 match_path_ast(path, &[&id.name.as_str()])
102             ], {
103                 self.emit_let_lint(cx, retexpr.span, initexpr.span);
104             }
105         }
106     }
107
108     fn emit_let_lint(&mut self, cx: &EarlyContext, lint_span: Span, note_span: Span) {
109         if in_external_macro(cx, note_span) {
110             return;
111         }
112         let mut db = span_lint(cx,
113                                LET_AND_RETURN,
114                                lint_span,
115                                "returning the result of a let binding from a block. Consider returning the \
116                                 expression directly.");
117         if cx.current_level(LET_AND_RETURN) != Level::Allow {
118             db.span_note(note_span, "this expression can be directly returned");
119         }
120     }
121 }
122
123 impl LintPass for ReturnPass {
124     fn get_lints(&self) -> LintArray {
125         lint_array!(NEEDLESS_RETURN, LET_AND_RETURN)
126     }
127 }
128
129 impl EarlyLintPass for ReturnPass {
130     fn check_fn(&mut self, cx: &EarlyContext, _: FnKind, _: &FnDecl, block: &Block, _: Span, _: NodeId) {
131         self.check_block_return(cx, block);
132     }
133
134     fn check_block(&mut self, cx: &EarlyContext, block: &Block) {
135         self.check_let_return(cx, block);
136     }
137 }