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