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