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