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