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