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::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 #[derive(Copy, Clone)]
72 pub struct ReturnPass;
75 // Check the final stmt or expr in a block for unnecessary return.
76 fn check_block_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
77 if let Some(stmt) = block.stmts.last() {
79 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
80 self.check_final_expr(cx, expr, Some(stmt.span));
87 // Check a the final expression in a block if it's a return.
88 fn check_final_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr, span: Option<Span>) {
90 // simple return is always "bad"
91 ast::ExprKind::Ret(Some(ref inner)) => {
92 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
93 if !expr.attrs.iter().any(attr_is_cfg) {
94 self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
97 // a whole block? check it!
98 ast::ExprKind::Block(ref block, _) => {
99 self.check_block_return(cx, block);
101 // an if/if let expr, check both exprs
102 // note, if without else is going to be a type checking error anyways
103 // (except for unit type functions) so we don't match it
104 ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
105 self.check_block_return(cx, ifblock);
106 self.check_final_expr(cx, elsexpr, None);
108 // a match expr, check all arms
109 ast::ExprKind::Match(_, ref arms) => for arm in arms {
110 self.check_final_expr(cx, &arm.body, Some(arm.body.span));
116 fn emit_return_lint(&mut self, cx: &EarlyContext<'_>, ret_span: Span, inner_span: Span) {
117 if in_external_macro(cx.sess(), inner_span) || in_macro(inner_span) {
120 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
121 if let Some(snippet) = snippet_opt(cx, inner_span) {
122 db.span_suggestion_with_applicability(
124 "remove `return` as shown",
126 Applicability::MachineApplicable,
132 // Check for "let x = EXPR; x"
133 fn check_let_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
134 let mut it = block.stmts.iter();
136 // we need both a let-binding stmt and an expr
138 if let Some(retexpr) = it.next_back();
139 if let ast::StmtKind::Expr(ref retexpr) = retexpr.node;
140 if let Some(stmt) = it.next_back();
141 if let ast::StmtKind::Local(ref local) = stmt.node;
142 // don't lint in the presence of type inference
143 if local.ty.is_none();
144 if !local.attrs.iter().any(attr_is_cfg);
145 if let Some(ref initexpr) = local.init;
146 if let ast::PatKind::Ident(_, ident, _) = local.pat.node;
147 if let ast::ExprKind::Path(_, ref path) = retexpr.node;
148 if match_path_ast(path, &[&ident.as_str()]);
149 if !in_external_macro(cx.sess(), initexpr.span);
151 span_note_and_lint(cx,
154 "returning the result of a let binding from a block. \
155 Consider returning the expression directly.",
157 "this expression can be directly returned");
163 impl LintPass for ReturnPass {
164 fn get_lints(&self) -> LintArray {
165 lint_array!(NEEDLESS_RETURN, LET_AND_RETURN)
169 impl EarlyLintPass for ReturnPass {
170 fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
172 FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
173 FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
177 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
178 self.check_let_return(cx, block);
182 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
183 attr.meta_item_list().is_some() && attr.name() == "cfg"