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