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;
6 use syntax::source_map::Span;
7 use syntax::visit::FnKind;
8 use syntax_pos::BytePos;
10 use crate::utils::{match_path_ast, snippet_opt, span_lint_and_then};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for return statements at the end of a block.
15 /// **Why is this bad?** Removing the `return` and semicolon will make the code
18 /// **Known problems:** If the computation returning the value borrows a local
19 /// variable, removing the `return` may run afoul of the borrow checker.
23 /// fn foo(x: usize) -> usize {
29 /// fn foo(x: usize) -> usize {
35 "using a return statement like `return expr;` where an expression would suffice"
38 declare_clippy_lint! {
39 /// **What it does:** Checks for `let`-bindings, which are subsequently
42 /// **Why is this bad?** It is just extraneous code. Remove it to make your code
45 /// **Known problems:** None.
49 /// fn foo() -> String {
50 /// let x = String::new();
56 /// fn foo() -> String {
62 "creating a let-binding and then immediately returning it like `let x = expr; x` at the end of a block"
65 declare_clippy_lint! {
66 /// **What it does:** Checks for unit (`()`) expressions that can be removed.
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.
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) { .. }`.
77 /// fn return_unit() -> () {
83 "needless unit expression"
86 #[derive(PartialEq, Eq, Copy, Clone)]
92 declare_lint_pass!(Return => [NEEDLESS_RETURN, LET_AND_RETURN, UNUSED_UNIT]);
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() {
99 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
100 self.check_final_expr(cx, expr, Some(stmt.span), RetReplacement::Empty);
107 // Check a the final expression in a block if it's a return.
110 cx: &EarlyContext<'_>,
113 replacement: RetReplacement,
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(
122 span.expect("`else return` is not possible"),
123 inner.as_ref().map(|i| i.span),
128 // a whole block? check it!
129 ast::ExprKind::Block(ref block, _) => {
130 self.check_block_return(cx, block);
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);
139 // a match expr, check all arms
140 ast::ExprKind::Match(_, ref arms) => {
142 self.check_final_expr(cx, &arm.body, Some(arm.body.span), RetReplacement::Block);
151 cx: &EarlyContext<'_>,
153 inner_span: Option<Span>,
154 replacement: RetReplacement,
157 Some(inner_span) => {
158 if in_external_macro(cx.sess(), inner_span) || inner_span.from_expansion() {
162 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
163 if let Some(snippet) = snippet_opt(cx, inner_span) {
164 db.span_suggestion(ret_span, "remove `return`", snippet, Applicability::MachineApplicable);
168 None => match replacement {
169 RetReplacement::Empty => {
170 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
175 Applicability::MachineApplicable,
179 RetReplacement::Block => {
180 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
183 "replace `return` with an empty block",
185 Applicability::MachineApplicable,
193 // Check for "let x = EXPR; x"
194 fn check_let_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
195 let mut it = block.stmts.iter();
197 // we need both a let-binding stmt and an expr
199 if let Some(retexpr) = it.next_back();
200 if let ast::StmtKind::Expr(ref retexpr) = retexpr.kind;
201 if let Some(stmt) = it.next_back();
202 if let ast::StmtKind::Local(ref local) = stmt.kind;
203 // don't lint in the presence of type inference
204 if local.ty.is_none();
205 if local.attrs.is_empty();
206 if let Some(ref initexpr) = local.init;
207 if let ast::PatKind::Ident(_, ident, _) = local.pat.kind;
208 if let ast::ExprKind::Path(_, ref path) = retexpr.kind;
209 if match_path_ast(path, &[&*ident.name.as_str()]);
210 if !in_external_macro(cx.sess(), initexpr.span);
211 if !in_external_macro(cx.sess(), retexpr.span);
212 if !in_external_macro(cx.sess(), local.span);
218 "returning the result of a let binding from a block",
220 err.span_label(local.span, "unnecessary let binding");
222 if let Some(snippet) = snippet_opt(cx, initexpr.span) {
223 err.multipart_suggestion(
224 "return the expression directly",
226 (local.span, String::new()),
227 (retexpr.span, snippet),
229 Applicability::MachineApplicable,
232 err.span_help(initexpr.span, "this expression can be directly returned");
241 impl EarlyLintPass for Return {
242 fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, decl: &ast::FnDecl, span: Span, _: ast::NodeId) {
244 FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
245 FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span), RetReplacement::Empty),
248 if let ast::FunctionRetTy::Ty(ref ty) = decl.output;
249 if let ast::TyKind::Tup(ref vals) = ty.kind;
250 if vals.is_empty() && !ty.span.from_expansion() && get_def(span) == get_def(ty.span);
252 let (rspan, appl) = if let Ok(fn_source) =
253 cx.sess().source_map()
254 .span_to_snippet(span.with_hi(ty.span.hi())) {
255 if let Some(rpos) = fn_source.rfind("->") {
256 #[allow(clippy::cast_possible_truncation)]
257 (ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
258 Applicability::MachineApplicable)
260 (ty.span, Applicability::MaybeIncorrect)
263 (ty.span, Applicability::MaybeIncorrect)
265 span_lint_and_then(cx, UNUSED_UNIT, rspan, "unneeded unit return type", |db| {
268 "remove the `-> ()`",
277 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
278 self.check_let_return(cx, block);
280 if let Some(ref stmt) = block.stmts.last();
281 if let ast::StmtKind::Expr(ref expr) = stmt.kind;
282 if is_unit_expr(expr) && !stmt.span.from_expansion();
285 span_lint_and_then(cx, UNUSED_UNIT, sp, "unneeded unit expression", |db| {
288 "remove the final `()`",
290 Applicability::MachineApplicable,
297 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
299 ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
300 if is_unit_expr(expr) && !expr.span.from_expansion() {
301 span_lint_and_then(cx, UNUSED_UNIT, expr.span, "unneeded `()`", |db| {
306 Applicability::MachineApplicable,
316 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
317 attr.meta_item_list().is_some() && attr.check_name(sym!(cfg))
321 fn get_def(span: Span) -> Option<Span> {
322 if span.from_expansion() {
323 Some(span.ctxt().outer_expn_data().def_site)
329 // is this expr a `()` unit?
330 fn is_unit_expr(expr: &ast::Expr) -> bool {
331 if let ast::ExprKind::Tup(ref vals) = expr.kind {