]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/returns.rs
Add a new lint for unused self
[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::{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     Block,
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.kind {
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(
109         &mut self,
110         cx: &EarlyContext<'_>,
111         expr: &ast::Expr,
112         span: Option<Span>,
113         replacement: RetReplacement,
114     ) {
115         match expr.kind {
116             // simple return is always "bad"
117             ast::ExprKind::Ret(ref inner) => {
118                 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
119                 if !expr.attrs.iter().any(attr_is_cfg) {
120                     Self::emit_return_lint(
121                         cx,
122                         span.expect("`else return` is not possible"),
123                         inner.as_ref().map(|i| i.span),
124                         replacement,
125                     );
126                 }
127             },
128             // a whole block? check it!
129             ast::ExprKind::Block(ref block, _) => {
130                 self.check_block_return(cx, block);
131             },
132             // an if/if let expr, check both exprs
133             // note, if without else is going to be a type checking error anyways
134             // (except for unit type functions) so we don't match it
135             ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
136                 self.check_block_return(cx, ifblock);
137                 self.check_final_expr(cx, elsexpr, None, RetReplacement::Empty);
138             },
139             // a match expr, check all arms
140             ast::ExprKind::Match(_, ref arms) => {
141                 for arm in arms {
142                     self.check_final_expr(cx, &arm.body, Some(arm.body.span), RetReplacement::Block);
143                 }
144             },
145             _ => (),
146         }
147     }
148
149     fn emit_return_lint(cx: &EarlyContext<'_>, ret_span: Span, inner_span: Option<Span>, replacement: RetReplacement) {
150         match inner_span {
151             Some(inner_span) => {
152                 if in_external_macro(cx.sess(), inner_span) || inner_span.from_expansion() {
153                     return;
154                 }
155
156                 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
157                     if let Some(snippet) = snippet_opt(cx, inner_span) {
158                         db.span_suggestion(ret_span, "remove `return`", snippet, Applicability::MachineApplicable);
159                     }
160                 })
161             },
162             None => match replacement {
163                 RetReplacement::Empty => {
164                     span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
165                         db.span_suggestion(
166                             ret_span,
167                             "remove `return`",
168                             String::new(),
169                             Applicability::MachineApplicable,
170                         );
171                     });
172                 },
173                 RetReplacement::Block => {
174                     span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
175                         db.span_suggestion(
176                             ret_span,
177                             "replace `return` with an empty block",
178                             "{}".to_string(),
179                             Applicability::MachineApplicable,
180                         );
181                     });
182                 },
183             },
184         }
185     }
186
187     // Check for "let x = EXPR; x"
188     fn check_let_return(cx: &EarlyContext<'_>, block: &ast::Block) {
189         let mut it = block.stmts.iter();
190
191         // we need both a let-binding stmt and an expr
192         if_chain! {
193             if let Some(retexpr) = it.next_back();
194             if let ast::StmtKind::Expr(ref retexpr) = retexpr.kind;
195             if let Some(stmt) = it.next_back();
196             if let ast::StmtKind::Local(ref local) = stmt.kind;
197             // don't lint in the presence of type inference
198             if local.ty.is_none();
199             if local.attrs.is_empty();
200             if let Some(ref initexpr) = local.init;
201             if let ast::PatKind::Ident(_, ident, _) = local.pat.kind;
202             if let ast::ExprKind::Path(_, ref path) = retexpr.kind;
203             if match_path_ast(path, &[&*ident.name.as_str()]);
204             if !in_external_macro(cx.sess(), initexpr.span);
205             if !in_external_macro(cx.sess(), retexpr.span);
206             if !in_external_macro(cx.sess(), local.span);
207             then {
208                 span_lint_and_then(
209                     cx,
210                     LET_AND_RETURN,
211                     retexpr.span,
212                     "returning the result of a let binding from a block",
213                     |err| {
214                         err.span_label(local.span, "unnecessary let binding");
215
216                         if let Some(snippet) = snippet_opt(cx, initexpr.span) {
217                             err.multipart_suggestion(
218                                 "return the expression directly",
219                                 vec![
220                                     (local.span, String::new()),
221                                     (retexpr.span, snippet),
222                                 ],
223                                 Applicability::MachineApplicable,
224                             );
225                         } else {
226                             err.span_help(initexpr.span, "this expression can be directly returned");
227                         }
228                     },
229                 );
230             }
231         }
232     }
233 }
234
235 impl EarlyLintPass for Return {
236     fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, decl: &ast::FnDecl, span: Span, _: ast::NodeId) {
237         match kind {
238             FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
239             FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span), RetReplacement::Empty),
240         }
241         if_chain! {
242             if let ast::FunctionRetTy::Ty(ref ty) = decl.output;
243             if let ast::TyKind::Tup(ref vals) = ty.kind;
244             if vals.is_empty() && !ty.span.from_expansion() && get_def(span) == get_def(ty.span);
245             then {
246                 let (rspan, appl) = if let Ok(fn_source) =
247                         cx.sess().source_map()
248                                  .span_to_snippet(span.with_hi(ty.span.hi())) {
249                     if let Some(rpos) = fn_source.rfind("->") {
250                         #[allow(clippy::cast_possible_truncation)]
251                         (ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
252                             Applicability::MachineApplicable)
253                     } else {
254                         (ty.span, Applicability::MaybeIncorrect)
255                     }
256                 } else {
257                     (ty.span, Applicability::MaybeIncorrect)
258                 };
259                 span_lint_and_then(cx, UNUSED_UNIT, rspan, "unneeded unit return type", |db| {
260                     db.span_suggestion(
261                         rspan,
262                         "remove the `-> ()`",
263                         String::new(),
264                         appl,
265                     );
266                 });
267             }
268         }
269     }
270
271     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
272         Self::check_let_return(cx, block);
273         if_chain! {
274             if let Some(ref stmt) = block.stmts.last();
275             if let ast::StmtKind::Expr(ref expr) = stmt.kind;
276             if is_unit_expr(expr) && !stmt.span.from_expansion();
277             then {
278                 let sp = expr.span;
279                 span_lint_and_then(cx, UNUSED_UNIT, sp, "unneeded unit expression", |db| {
280                     db.span_suggestion(
281                         sp,
282                         "remove the final `()`",
283                         String::new(),
284                         Applicability::MachineApplicable,
285                     );
286                 });
287             }
288         }
289     }
290
291     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
292         match e.kind {
293             ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
294                 if is_unit_expr(expr) && !expr.span.from_expansion() {
295                     span_lint_and_then(cx, UNUSED_UNIT, expr.span, "unneeded `()`", |db| {
296                         db.span_suggestion(
297                             expr.span,
298                             "remove the `()`",
299                             String::new(),
300                             Applicability::MachineApplicable,
301                         );
302                     });
303                 }
304             },
305             _ => (),
306         }
307     }
308 }
309
310 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
311     attr.meta_item_list().is_some() && attr.check_name(sym!(cfg))
312 }
313
314 // get the def site
315 #[must_use]
316 fn get_def(span: Span) -> Option<Span> {
317     if span.from_expansion() {
318         Some(span.ctxt().outer_expn_data().def_site)
319     } else {
320         None
321     }
322 }
323
324 // is this expr a `()` unit?
325 fn is_unit_expr(expr: &ast::Expr) -> bool {
326     if let ast::ExprKind::Tup(ref vals) = expr.kind {
327         vals.is_empty()
328     } else {
329         false
330     }
331 }