]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/returns.rs
Merge pull request #3285 from devonhollowood/pedantic-dogfood-items-after-statements
[rust.git] / clippy_lints / src / returns.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, in_external_macro, LintContext};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use if_chain::if_chain;
14 use crate::syntax::ast;
15 use crate::syntax::source_map::Span;
16 use crate::syntax::visit::FnKind;
17 use crate::rustc_errors::Applicability;
18
19 use crate::utils::{in_macro, match_path_ast, snippet_opt, span_lint_and_then, span_note_and_lint};
20
21 /// **What it does:** Checks for return statements at the end of a block.
22 ///
23 /// **Why is this bad?** Removing the `return` and semicolon will make the code
24 /// more rusty.
25 ///
26 /// **Known problems:** If the computation returning the value borrows a local
27 /// variable, removing the `return` may run afoul of the borrow checker.
28 ///
29 /// **Example:**
30 /// ```rust
31 /// fn foo(x: usize) { return x; }
32 /// ```
33 /// simplify to
34 /// ```rust
35 /// fn foo(x: usize) { x }
36 /// ```
37 declare_clippy_lint! {
38     pub NEEDLESS_RETURN,
39     style,
40     "using a return statement like `return expr;` where an expression would suffice"
41 }
42
43 /// **What it does:** Checks for `let`-bindings, which are subsequently
44 /// returned.
45 ///
46 /// **Why is this bad?** It is just extraneous code. Remove it to make your code
47 /// more rusty.
48 ///
49 /// **Known problems:** None.
50 ///
51 /// **Example:**
52 /// ```rust
53 /// fn foo() -> String {
54 ///    let x = String::new();
55 ///    x
56 ///}
57 /// ```
58 /// instead, use
59 /// ```
60 /// fn foo() -> String {
61 ///    String::new()
62 ///}
63 /// ```
64 declare_clippy_lint! {
65     pub LET_AND_RETURN,
66     style,
67     "creating a let-binding and then immediately returning it like `let x = expr; x` at \
68      the end of a block"
69 }
70
71 #[derive(Copy, Clone)]
72 pub struct ReturnPass;
73
74 impl ReturnPass {
75     // Check the final stmt or expr in a block for unnecessary return.
76     fn check_block_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
77         if let Some(stmt) = block.stmts.last() {
78             match stmt.node {
79                 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
80                     self.check_final_expr(cx, expr, Some(stmt.span));
81                 },
82                 _ => (),
83             }
84         }
85     }
86
87     // Check a the final expression in a block if it's a return.
88     fn check_final_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr, span: Option<Span>) {
89         match expr.node {
90             // simple return is always "bad"
91             ast::ExprKind::Ret(Some(ref inner)) => {
92                 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
93                 if !expr.attrs.iter().any(attr_is_cfg) {
94                     self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
95                 }
96             },
97             // a whole block? check it!
98             ast::ExprKind::Block(ref block, _) => {
99                 self.check_block_return(cx, block);
100             },
101             // an if/if let expr, check both exprs
102             // note, if without else is going to be a type checking error anyways
103             // (except for unit type functions) so we don't match it
104             ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
105                 self.check_block_return(cx, ifblock);
106                 self.check_final_expr(cx, elsexpr, None);
107             },
108             // a match expr, check all arms
109             ast::ExprKind::Match(_, ref arms) => for arm in arms {
110                 self.check_final_expr(cx, &arm.body, Some(arm.body.span));
111             },
112             _ => (),
113         }
114     }
115
116     fn emit_return_lint(&mut self, cx: &EarlyContext<'_>, ret_span: Span, inner_span: Span) {
117         if in_external_macro(cx.sess(), inner_span) || in_macro(inner_span) {
118             return;
119         }
120         span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
121             if let Some(snippet) = snippet_opt(cx, inner_span) {
122                 db.span_suggestion_with_applicability(
123                     ret_span,
124                     "remove `return` as shown",
125                     snippet,
126                     Applicability::MachineApplicable,
127                 );
128             }
129         });
130     }
131
132     // Check for "let x = EXPR; x"
133     fn check_let_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
134         let mut it = block.stmts.iter();
135
136         // we need both a let-binding stmt and an expr
137         if_chain! {
138             if let Some(retexpr) = it.next_back();
139             if let ast::StmtKind::Expr(ref retexpr) = retexpr.node;
140             if let Some(stmt) = it.next_back();
141             if let ast::StmtKind::Local(ref local) = stmt.node;
142             // don't lint in the presence of type inference
143             if local.ty.is_none();
144             if !local.attrs.iter().any(attr_is_cfg);
145             if let Some(ref initexpr) = local.init;
146             if let ast::PatKind::Ident(_, ident, _) = local.pat.node;
147             if let ast::ExprKind::Path(_, ref path) = retexpr.node;
148             if match_path_ast(path, &[&ident.as_str()]);
149             if !in_external_macro(cx.sess(), initexpr.span);
150             then {
151                     span_note_and_lint(cx,
152                                        LET_AND_RETURN,
153                                        retexpr.span,
154                                        "returning the result of a let binding from a block. \
155                                        Consider returning the expression directly.",
156                                        initexpr.span,
157                                        "this expression can be directly returned");
158             }
159         }
160     }
161 }
162
163 impl LintPass for ReturnPass {
164     fn get_lints(&self) -> LintArray {
165         lint_array!(NEEDLESS_RETURN, LET_AND_RETURN)
166     }
167 }
168
169 impl EarlyLintPass for ReturnPass {
170     fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
171         match kind {
172             FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
173             FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
174         }
175     }
176
177     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
178         self.check_let_return(cx, block);
179     }
180 }
181
182 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
183     attr.meta_item_list().is_some() && attr.name() == "cfg"
184 }