]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/returns.rs
Merge #3399
[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::syntax_pos::BytePos;
18 use crate::rustc_errors::Applicability;
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 /// **What it does:** Checks for unit (`()`) expressions that can be removed.
72 ///
73 /// **Why is this bad?** Such expressions add no value, but can make the code
74 /// less readable. Depending on formatting they can make a `break` or `return`
75 /// statement look like a function call.
76 ///
77 /// **Known problems:** The lint currently misses unit return types in types,
78 /// e.g. the `F` in `fn generic_unit<F: Fn() -> ()>(f: F) { .. }`.
79 ///
80 /// **Example:**
81 /// ```rust
82 /// fn return_unit() -> () { () }
83 /// ```
84 declare_clippy_lint! {
85     pub UNUSED_UNIT,
86     style,
87     "needless unit expression"
88 }
89
90 #[derive(Copy, Clone)]
91 pub struct ReturnPass;
92
93 impl ReturnPass {
94     // Check the final stmt or expr in a block for unnecessary return.
95     fn check_block_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
96         if let Some(stmt) = block.stmts.last() {
97             match stmt.node {
98                 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
99                     self.check_final_expr(cx, expr, Some(stmt.span));
100                 },
101                 _ => (),
102             }
103         }
104     }
105
106     // Check a the final expression in a block if it's a return.
107     fn check_final_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr, span: Option<Span>) {
108         match expr.node {
109             // simple return is always "bad"
110             ast::ExprKind::Ret(Some(ref inner)) => {
111                 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
112                 if !expr.attrs.iter().any(attr_is_cfg) {
113                     self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
114                 }
115             },
116             // a whole block? check it!
117             ast::ExprKind::Block(ref block, _) => {
118                 self.check_block_return(cx, block);
119             },
120             // an if/if let expr, check both exprs
121             // note, if without else is going to be a type checking error anyways
122             // (except for unit type functions) so we don't match it
123             ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
124                 self.check_block_return(cx, ifblock);
125                 self.check_final_expr(cx, elsexpr, None);
126             },
127             // a match expr, check all arms
128             ast::ExprKind::Match(_, ref arms) => for arm in arms {
129                 self.check_final_expr(cx, &arm.body, Some(arm.body.span));
130             },
131             _ => (),
132         }
133     }
134
135     fn emit_return_lint(&mut self, cx: &EarlyContext<'_>, ret_span: Span, inner_span: Span) {
136         if in_external_macro(cx.sess(), inner_span) || in_macro(inner_span) {
137             return;
138         }
139         span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
140             if let Some(snippet) = snippet_opt(cx, inner_span) {
141                 db.span_suggestion_with_applicability(
142                     ret_span,
143                     "remove `return` as shown",
144                     snippet,
145                     Applicability::MachineApplicable,
146                 );
147             }
148         });
149     }
150
151     // Check for "let x = EXPR; x"
152     fn check_let_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
153         let mut it = block.stmts.iter();
154
155         // we need both a let-binding stmt and an expr
156         if_chain! {
157             if let Some(retexpr) = it.next_back();
158             if let ast::StmtKind::Expr(ref retexpr) = retexpr.node;
159             if let Some(stmt) = it.next_back();
160             if let ast::StmtKind::Local(ref local) = stmt.node;
161             // don't lint in the presence of type inference
162             if local.ty.is_none();
163             if !local.attrs.iter().any(attr_is_cfg);
164             if let Some(ref initexpr) = local.init;
165             if let ast::PatKind::Ident(_, ident, _) = local.pat.node;
166             if let ast::ExprKind::Path(_, ref path) = retexpr.node;
167             if match_path_ast(path, &[&ident.as_str()]);
168             if !in_external_macro(cx.sess(), initexpr.span);
169             then {
170                     span_note_and_lint(cx,
171                                        LET_AND_RETURN,
172                                        retexpr.span,
173                                        "returning the result of a let binding from a block. \
174                                        Consider returning the expression directly.",
175                                        initexpr.span,
176                                        "this expression can be directly returned");
177             }
178         }
179     }
180 }
181
182 impl LintPass for ReturnPass {
183     fn get_lints(&self) -> LintArray {
184         lint_array!(NEEDLESS_RETURN, LET_AND_RETURN, UNUSED_UNIT)
185     }
186 }
187
188 impl EarlyLintPass for ReturnPass {
189     fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, decl: &ast::FnDecl, span: Span, _: ast::NodeId) {
190         match kind {
191             FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
192             FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
193         }
194         if_chain! {
195             if let ast::FunctionRetTy::Ty(ref ty) = decl.output;
196             if let ast::TyKind::Tup(ref vals) = ty.node;
197             if vals.is_empty() && !in_macro(ty.span) && get_def(span) == get_def(ty.span);
198             then {
199                 let (rspan, appl) = if let Ok(fn_source) =
200                         cx.sess().source_map()
201                                  .span_to_snippet(span.with_hi(ty.span.hi())) {
202                     if let Some(rpos) = fn_source.rfind("->") {
203                         #[allow(clippy::cast_possible_truncation)]
204                         (ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
205                             Applicability::MachineApplicable)
206                     } else {
207                         (ty.span, Applicability::MaybeIncorrect)
208                     }
209                 } else {
210                     (ty.span, Applicability::MaybeIncorrect)
211                 };
212                 span_lint_and_then(cx, UNUSED_UNIT, rspan, "unneeded unit return type", |db| {
213                     db.span_suggestion_with_applicability(
214                         rspan,
215                         "remove the `-> ()`",
216                         String::new(),
217                         appl,
218                     );
219                 });
220             }
221         }
222     }
223
224     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
225         self.check_let_return(cx, block);
226         if_chain! {
227             if let Some(ref stmt) = block.stmts.last();
228             if let ast::StmtKind::Expr(ref expr) = stmt.node;
229             if is_unit_expr(expr) && !in_macro(expr.span);
230             then {
231                 let sp = expr.span;
232                 span_lint_and_then(cx, UNUSED_UNIT, sp, "unneeded unit expression", |db| {
233                     db.span_suggestion_with_applicability(
234                         sp,
235                         "remove the final `()`",
236                         String::new(),
237                         Applicability::MachineApplicable,
238                     );
239                 });
240             }
241         }
242     }
243
244     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
245         match e.node {
246             ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
247                 if is_unit_expr(expr) && !in_macro(expr.span) {
248                     span_lint_and_then(cx, UNUSED_UNIT, expr.span, "unneeded `()`", |db| {
249                         db.span_suggestion_with_applicability(
250                             expr.span,
251                             "remove the `()`",
252                             String::new(),
253                             Applicability::MachineApplicable,
254                         );
255                     });
256                 }
257             }
258             _ => ()
259         }
260     }
261 }
262
263 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
264     attr.meta_item_list().is_some() && attr.name() == "cfg"
265 }
266
267 // get the def site
268 fn get_def(span: Span) -> Option<Span> {
269     span.ctxt().outer().expn_info().and_then(|info| info.def_site)
270 }
271
272 // is this expr a `()` unit?
273 fn is_unit_expr(expr: &ast::Expr) -> bool {
274     if let ast::ExprKind::Tup(ref vals) = expr.node {
275         vals.is_empty()
276     } else {
277         false
278     }
279 }