1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
11 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, in_external_macro, LintContext};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use if_chain::if_chain;
14 use crate::syntax::ast;
15 use crate::syntax::source_map::Span;
16 use crate::syntax::visit::FnKind;
17 use crate::syntax_pos::BytePos;
18 use crate::rustc_errors::Applicability;
19 use crate::utils::{in_macro, match_path_ast, snippet_opt, span_lint_and_then, span_note_and_lint};
21 /// **What it does:** Checks for return statements at the end of a block.
23 /// **Why is this bad?** Removing the `return` and semicolon will make the code
26 /// **Known problems:** If the computation returning the value borrows a local
27 /// variable, removing the `return` may run afoul of the borrow checker.
31 /// fn foo(x: usize) { return x; }
35 /// fn foo(x: usize) { x }
37 declare_clippy_lint! {
40 "using a return statement like `return expr;` where an expression would suffice"
43 /// **What it does:** Checks for `let`-bindings, which are subsequently
46 /// **Why is this bad?** It is just extraneous code. Remove it to make your code
49 /// **Known problems:** None.
53 /// fn foo() -> String {
54 /// let x = String::new();
60 /// fn foo() -> String {
64 declare_clippy_lint! {
67 "creating a let-binding and then immediately returning it like `let x = expr; x` at \
71 /// **What it does:** Checks for unit (`()`) expressions that can be removed.
73 /// **Why is this bad?** Such expressions add no value, but can make the code
74 /// less readable. Depending on formatting they can make a `break` or `return`
75 /// statement look like a function call.
77 /// **Known problems:** The lint currently misses unit return types in types,
78 /// e.g. the `F` in `fn generic_unit<F: Fn() -> ()>(f: F) { .. }`.
82 /// fn return_unit() -> () { () }
84 declare_clippy_lint! {
87 "needless unit expression"
90 #[derive(Copy, Clone)]
91 pub struct ReturnPass;
94 // Check the final stmt or expr in a block for unnecessary return.
95 fn check_block_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
96 if let Some(stmt) = block.stmts.last() {
98 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
99 self.check_final_expr(cx, expr, Some(stmt.span));
106 // Check a the final expression in a block if it's a return.
107 fn check_final_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr, span: Option<Span>) {
109 // simple return is always "bad"
110 ast::ExprKind::Ret(Some(ref inner)) => {
111 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
112 if !expr.attrs.iter().any(attr_is_cfg) {
113 self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
116 // a whole block? check it!
117 ast::ExprKind::Block(ref block, _) => {
118 self.check_block_return(cx, block);
120 // an if/if let expr, check both exprs
121 // note, if without else is going to be a type checking error anyways
122 // (except for unit type functions) so we don't match it
123 ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
124 self.check_block_return(cx, ifblock);
125 self.check_final_expr(cx, elsexpr, None);
127 // a match expr, check all arms
128 ast::ExprKind::Match(_, ref arms) => for arm in arms {
129 self.check_final_expr(cx, &arm.body, Some(arm.body.span));
135 fn emit_return_lint(&mut self, cx: &EarlyContext<'_>, ret_span: Span, inner_span: Span) {
136 if in_external_macro(cx.sess(), inner_span) || in_macro(inner_span) {
139 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
140 if let Some(snippet) = snippet_opt(cx, inner_span) {
141 db.span_suggestion_with_applicability(
143 "remove `return` as shown",
145 Applicability::MachineApplicable,
151 // Check for "let x = EXPR; x"
152 fn check_let_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
153 let mut it = block.stmts.iter();
155 // we need both a let-binding stmt and an expr
157 if let Some(retexpr) = it.next_back();
158 if let ast::StmtKind::Expr(ref retexpr) = retexpr.node;
159 if let Some(stmt) = it.next_back();
160 if let ast::StmtKind::Local(ref local) = stmt.node;
161 // don't lint in the presence of type inference
162 if local.ty.is_none();
163 if !local.attrs.iter().any(attr_is_cfg);
164 if let Some(ref initexpr) = local.init;
165 if let ast::PatKind::Ident(_, ident, _) = local.pat.node;
166 if let ast::ExprKind::Path(_, ref path) = retexpr.node;
167 if match_path_ast(path, &[&ident.as_str()]);
168 if !in_external_macro(cx.sess(), initexpr.span);
170 span_note_and_lint(cx,
173 "returning the result of a let binding from a block. \
174 Consider returning the expression directly.",
176 "this expression can be directly returned");
182 impl LintPass for ReturnPass {
183 fn get_lints(&self) -> LintArray {
184 lint_array!(NEEDLESS_RETURN, LET_AND_RETURN, UNUSED_UNIT)
188 impl EarlyLintPass for ReturnPass {
189 fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, decl: &ast::FnDecl, span: Span, _: ast::NodeId) {
191 FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
192 FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
195 if let ast::FunctionRetTy::Ty(ref ty) = decl.output;
196 if let ast::TyKind::Tup(ref vals) = ty.node;
197 if vals.is_empty() && !in_macro(ty.span) && get_def(span) == get_def(ty.span);
199 let (rspan, appl) = if let Ok(fn_source) =
200 cx.sess().source_map()
201 .span_to_snippet(span.with_hi(ty.span.hi())) {
202 if let Some(rpos) = fn_source.rfind("->") {
203 #[allow(clippy::cast_possible_truncation)]
204 (ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
205 Applicability::MachineApplicable)
207 (ty.span, Applicability::MaybeIncorrect)
210 (ty.span, Applicability::MaybeIncorrect)
212 span_lint_and_then(cx, UNUSED_UNIT, rspan, "unneeded unit return type", |db| {
213 db.span_suggestion_with_applicability(
215 "remove the `-> ()`",
224 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
225 self.check_let_return(cx, block);
227 if let Some(ref stmt) = block.stmts.last();
228 if let ast::StmtKind::Expr(ref expr) = stmt.node;
229 if is_unit_expr(expr) && !in_macro(expr.span);
232 span_lint_and_then(cx, UNUSED_UNIT, sp, "unneeded unit expression", |db| {
233 db.span_suggestion_with_applicability(
235 "remove the final `()`",
237 Applicability::MachineApplicable,
244 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
246 ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
247 if is_unit_expr(expr) && !in_macro(expr.span) {
248 span_lint_and_then(cx, UNUSED_UNIT, expr.span, "unneeded `()`", |db| {
249 db.span_suggestion_with_applicability(
253 Applicability::MachineApplicable,
263 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
264 attr.meta_item_list().is_some() && attr.name() == "cfg"
268 fn get_def(span: Span) -> Option<Span> {
269 span.ctxt().outer().expn_info().and_then(|info| info.def_site)
272 // is this expr a `()` unit?
273 fn is_unit_expr(expr: &ast::Expr) -> bool {
274 if let ast::ExprKind::Tup(ref vals) = expr.node {