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.
10 use crate::rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::rustc_errors::Applicability;
13 use crate::syntax::ast;
14 use crate::syntax::source_map::Span;
15 use crate::syntax::visit::FnKind;
16 use crate::syntax_pos::BytePos;
17 use crate::utils::{in_macro, match_path_ast, snippet_opt, span_lint_and_then, span_note_and_lint};
18 use if_chain::if_chain;
20 /// **What it does:** Checks for return statements at the end of a block.
22 /// **Why is this bad?** Removing the `return` and semicolon will make the code
25 /// **Known problems:** If the computation returning the value borrows a local
26 /// variable, removing the `return` may run afoul of the borrow checker.
30 /// fn foo(x: usize) {
36 /// fn foo(x: usize) {
40 declare_clippy_lint! {
43 "using a return statement like `return expr;` where an expression would suffice"
46 /// **What it does:** Checks for `let`-bindings, which are subsequently
49 /// **Why is this bad?** It is just extraneous code. Remove it to make your code
52 /// **Known problems:** None.
56 /// fn foo() -> String {
57 /// let x = String::new();
63 /// fn foo() -> String {
67 declare_clippy_lint! {
70 "creating a let-binding and then immediately returning it like `let x = expr; x` at the end of a block"
73 /// **What it does:** Checks for unit (`()`) expressions that can be removed.
75 /// **Why is this bad?** Such expressions add no value, but can make the code
76 /// less readable. Depending on formatting they can make a `break` or `return`
77 /// statement look like a function call.
79 /// **Known problems:** The lint currently misses unit return types in types,
80 /// e.g. the `F` in `fn generic_unit<F: Fn() -> ()>(f: F) { .. }`.
84 /// fn return_unit() -> () {
88 declare_clippy_lint! {
91 "needless unit expression"
94 #[derive(Copy, Clone)]
95 pub struct ReturnPass;
98 // Check the final stmt or expr in a block for unnecessary return.
99 fn check_block_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
100 if let Some(stmt) = block.stmts.last() {
102 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
103 self.check_final_expr(cx, expr, Some(stmt.span));
110 // Check a the final expression in a block if it's a return.
111 fn check_final_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr, span: Option<Span>) {
113 // simple return is always "bad"
114 ast::ExprKind::Ret(Some(ref inner)) => {
115 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
116 if !expr.attrs.iter().any(attr_is_cfg) {
117 self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
120 // a whole block? check it!
121 ast::ExprKind::Block(ref block, _) => {
122 self.check_block_return(cx, block);
124 // an if/if let expr, check both exprs
125 // note, if without else is going to be a type checking error anyways
126 // (except for unit type functions) so we don't match it
127 ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
128 self.check_block_return(cx, ifblock);
129 self.check_final_expr(cx, elsexpr, None);
131 // a match expr, check all arms
132 ast::ExprKind::Match(_, ref arms) => {
134 self.check_final_expr(cx, &arm.body, Some(arm.body.span));
141 fn emit_return_lint(&mut self, cx: &EarlyContext<'_>, ret_span: Span, inner_span: Span) {
142 if in_external_macro(cx.sess(), inner_span) || in_macro(inner_span) {
145 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
146 if let Some(snippet) = snippet_opt(cx, inner_span) {
147 db.span_suggestion_with_applicability(
149 "remove `return` as shown",
151 Applicability::MachineApplicable,
157 // Check for "let x = EXPR; x"
158 fn check_let_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
159 let mut it = block.stmts.iter();
161 // we need both a let-binding stmt and an expr
163 if let Some(retexpr) = it.next_back();
164 if let ast::StmtKind::Expr(ref retexpr) = retexpr.node;
165 if let Some(stmt) = it.next_back();
166 if let ast::StmtKind::Local(ref local) = stmt.node;
167 // don't lint in the presence of type inference
168 if local.ty.is_none();
169 if !local.attrs.iter().any(attr_is_cfg);
170 if let Some(ref initexpr) = local.init;
171 if let ast::PatKind::Ident(_, ident, _) = local.pat.node;
172 if let ast::ExprKind::Path(_, ref path) = retexpr.node;
173 if match_path_ast(path, &[&ident.as_str()]);
174 if !in_external_macro(cx.sess(), initexpr.span);
176 span_note_and_lint(cx,
179 "returning the result of a let binding from a block. \
180 Consider returning the expression directly.",
182 "this expression can be directly returned");
188 impl LintPass for ReturnPass {
189 fn get_lints(&self) -> LintArray {
190 lint_array!(NEEDLESS_RETURN, LET_AND_RETURN, UNUSED_UNIT)
194 impl EarlyLintPass for ReturnPass {
195 fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, decl: &ast::FnDecl, span: Span, _: ast::NodeId) {
197 FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
198 FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
201 if let ast::FunctionRetTy::Ty(ref ty) = decl.output;
202 if let ast::TyKind::Tup(ref vals) = ty.node;
203 if vals.is_empty() && !in_macro(ty.span) && get_def(span) == get_def(ty.span);
205 let (rspan, appl) = if let Ok(fn_source) =
206 cx.sess().source_map()
207 .span_to_snippet(span.with_hi(ty.span.hi())) {
208 if let Some(rpos) = fn_source.rfind("->") {
209 #[allow(clippy::cast_possible_truncation)]
210 (ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
211 Applicability::MachineApplicable)
213 (ty.span, Applicability::MaybeIncorrect)
216 (ty.span, Applicability::MaybeIncorrect)
218 span_lint_and_then(cx, UNUSED_UNIT, rspan, "unneeded unit return type", |db| {
219 db.span_suggestion_with_applicability(
221 "remove the `-> ()`",
230 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
231 self.check_let_return(cx, block);
233 if let Some(ref stmt) = block.stmts.last();
234 if let ast::StmtKind::Expr(ref expr) = stmt.node;
235 if is_unit_expr(expr) && !in_macro(expr.span);
238 span_lint_and_then(cx, UNUSED_UNIT, sp, "unneeded unit expression", |db| {
239 db.span_suggestion_with_applicability(
241 "remove the final `()`",
243 Applicability::MachineApplicable,
250 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
252 ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
253 if is_unit_expr(expr) && !in_macro(expr.span) {
254 span_lint_and_then(cx, UNUSED_UNIT, expr.span, "unneeded `()`", |db| {
255 db.span_suggestion_with_applicability(
259 Applicability::MachineApplicable,
269 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
270 attr.meta_item_list().is_some() && attr.name() == "cfg"
274 fn get_def(span: Span) -> Option<Span> {
275 span.ctxt().outer().expn_info().and_then(|info| info.def_site)
278 // is this expr a `()` unit?
279 fn is_unit_expr(expr: &ast::Expr) -> bool {
280 if let ast::ExprKind::Tup(ref vals) = expr.node {