1 use if_chain::if_chain;
3 use rustc_ast::visit::FnKind;
4 use rustc_errors::Applicability;
5 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
6 use rustc_middle::lint::in_external_macro;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::source_map::Span;
9 use rustc_span::BytePos;
11 use crate::utils::{in_macro, match_path_ast, snippet_opt, span_lint_and_sugg, span_lint_and_then};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for return statements at the end of a block.
16 /// **Why is this bad?** Removing the `return` and semicolon will make the code
19 /// **Known problems:** If the computation returning the value borrows a local
20 /// variable, removing the `return` may run afoul of the borrow checker.
24 /// fn foo(x: usize) -> usize {
30 /// fn foo(x: usize) -> usize {
36 "using a return statement like `return expr;` where an expression would suffice"
39 declare_clippy_lint! {
40 /// **What it does:** Checks for `let`-bindings, which are subsequently
43 /// **Why is this bad?** It is just extraneous code. Remove it to make your code
46 /// **Known problems:** None.
50 /// fn foo() -> String {
51 /// let x = String::new();
57 /// fn foo() -> String {
63 "creating a let-binding and then immediately returning it like `let x = expr; x` at the end of a block"
66 declare_clippy_lint! {
67 /// **What it does:** Checks for unit (`()`) expressions that can be removed.
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.
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) { .. }`.
78 /// fn return_unit() -> () {
84 "needless unit expression"
87 #[derive(PartialEq, Eq, Copy, Clone)]
93 declare_lint_pass!(Return => [NEEDLESS_RETURN, LET_AND_RETURN, UNUSED_UNIT]);
96 // Check the final stmt or expr in a block for unnecessary return.
97 fn check_block_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
98 if let Some(stmt) = block.stmts.last() {
100 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
101 self.check_final_expr(cx, expr, Some(stmt.span), RetReplacement::Empty);
108 // Check a the final expression in a block if it's a return.
111 cx: &EarlyContext<'_>,
114 replacement: RetReplacement,
117 // simple return is always "bad"
118 ast::ExprKind::Ret(ref inner) => {
119 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
120 if !expr.attrs.iter().any(attr_is_cfg) {
121 Self::emit_return_lint(
123 span.expect("`else return` is not possible"),
124 inner.as_ref().map(|i| i.span),
129 // a whole block? check it!
130 ast::ExprKind::Block(ref block, _) => {
131 self.check_block_return(cx, block);
133 // an if/if let expr, check both exprs
134 // note, if without else is going to be a type checking error anyways
135 // (except for unit type functions) so we don't match it
136 ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
137 self.check_block_return(cx, ifblock);
138 self.check_final_expr(cx, elsexpr, None, RetReplacement::Empty);
140 // a match expr, check all arms
141 ast::ExprKind::Match(_, ref arms) => {
143 self.check_final_expr(cx, &arm.body, Some(arm.body.span), RetReplacement::Block);
150 fn emit_return_lint(cx: &EarlyContext<'_>, ret_span: Span, inner_span: Option<Span>, replacement: RetReplacement) {
152 Some(inner_span) => {
153 if in_external_macro(cx.sess(), inner_span) || inner_span.from_expansion() {
157 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded `return` statement", |diag| {
158 if let Some(snippet) = snippet_opt(cx, inner_span) {
159 diag.span_suggestion(ret_span, "remove `return`", snippet, Applicability::MachineApplicable);
163 None => match replacement {
164 RetReplacement::Empty => {
169 "unneeded `return` statement",
172 Applicability::MachineApplicable,
175 RetReplacement::Block => {
180 "unneeded `return` statement",
181 "replace `return` with an empty block",
183 Applicability::MachineApplicable,
190 // Check for "let x = EXPR; x"
191 fn check_let_return(cx: &EarlyContext<'_>, block: &ast::Block) {
192 let mut it = block.stmts.iter();
194 // we need both a let-binding stmt and an expr
196 if let Some(retexpr) = it.next_back();
197 if let ast::StmtKind::Expr(ref retexpr) = retexpr.kind;
198 if let Some(stmt) = it.next_back();
199 if let ast::StmtKind::Local(ref local) = stmt.kind;
200 // don't lint in the presence of type inference
201 if local.ty.is_none();
202 if local.attrs.is_empty();
203 if let Some(ref initexpr) = local.init;
204 if let ast::PatKind::Ident(_, ident, _) = local.pat.kind;
205 if let ast::ExprKind::Path(_, ref path) = retexpr.kind;
206 if match_path_ast(path, &[&*ident.name.as_str()]);
207 if !in_external_macro(cx.sess(), initexpr.span);
208 if !in_external_macro(cx.sess(), retexpr.span);
209 if !in_external_macro(cx.sess(), local.span);
210 if !in_macro(local.span);
216 "returning the result of a `let` binding from a block",
218 err.span_label(local.span, "unnecessary `let` binding");
220 if let Some(snippet) = snippet_opt(cx, initexpr.span) {
221 err.multipart_suggestion(
222 "return the expression directly",
224 (local.span, String::new()),
225 (retexpr.span, snippet),
227 Applicability::MachineApplicable,
230 err.span_help(initexpr.span, "this expression can be directly returned");
239 impl EarlyLintPass for Return {
240 fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, span: Span, _: ast::NodeId) {
242 FnKind::Fn(.., Some(block)) => self.check_block_return(cx, block),
243 FnKind::Closure(_, body) => self.check_final_expr(cx, body, Some(body.span), RetReplacement::Empty),
244 FnKind::Fn(.., None) => {},
247 if let ast::FnRetTy::Ty(ref ty) = kind.decl().output;
248 if let ast::TyKind::Tup(ref vals) = ty.kind;
249 if vals.is_empty() && !ty.span.from_expansion() && get_def(span) == get_def(ty.span);
251 let (rspan, appl) = if let Ok(fn_source) =
252 cx.sess().source_map()
253 .span_to_snippet(span.with_hi(ty.span.hi())) {
254 if let Some(rpos) = fn_source.rfind("->") {
255 #[allow(clippy::cast_possible_truncation)]
256 (ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
257 Applicability::MachineApplicable)
259 (ty.span, Applicability::MaybeIncorrect)
262 (ty.span, Applicability::MaybeIncorrect)
268 "unneeded unit return type",
269 "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();
289 "unneeded unit expression",
290 "remove the final `()`",
292 Applicability::MachineApplicable,
298 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
300 ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
301 if is_unit_expr(expr) && !expr.span.from_expansion() {
309 Applicability::MachineApplicable,
318 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
319 attr.meta_item_list().is_some() && attr.check_name(sym!(cfg))
324 fn get_def(span: Span) -> Option<Span> {
325 if span.from_expansion() {
326 Some(span.ctxt().outer_expn_data().def_site)
332 // is this expr a `()` unit?
333 fn is_unit_expr(expr: &ast::Expr) -> bool {
334 if let ast::ExprKind::Tup(ref vals) = expr.kind {