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