1 use if_chain::if_chain;
2 use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
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::{in_macro, match_path_ast, snippet_opt, span_lint_and_then, span_note_and_lint};
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(Copy, Clone)]
87 pub struct ReturnPass;
90 // Check the final stmt or expr in a block for unnecessary return.
91 fn check_block_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
92 if let Some(stmt) = block.stmts.last() {
94 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
95 self.check_final_expr(cx, expr, Some(stmt.span));
102 // Check a the final expression in a block if it's a return.
103 fn check_final_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr, span: Option<Span>) {
105 // simple return is always "bad"
106 ast::ExprKind::Ret(Some(ref inner)) => {
107 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
108 if !expr.attrs.iter().any(attr_is_cfg) {
109 self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
112 // a whole block? check it!
113 ast::ExprKind::Block(ref block, _) => {
114 self.check_block_return(cx, block);
116 // an if/if let expr, check both exprs
117 // note, if without else is going to be a type checking error anyways
118 // (except for unit type functions) so we don't match it
119 ast::ExprKind::If(_, ref ifblock, Some(ref elsexpr)) => {
120 self.check_block_return(cx, ifblock);
121 self.check_final_expr(cx, elsexpr, None);
123 // a match expr, check all arms
124 ast::ExprKind::Match(_, ref arms) => {
126 self.check_final_expr(cx, &arm.body, Some(arm.body.span));
133 fn emit_return_lint(&mut self, cx: &EarlyContext<'_>, ret_span: Span, inner_span: Span) {
134 if in_external_macro(cx.sess(), inner_span) || in_macro(inner_span) {
137 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded return statement", |db| {
138 if let Some(snippet) = snippet_opt(cx, inner_span) {
141 "remove `return` as shown",
143 Applicability::MachineApplicable,
149 // Check for "let x = EXPR; x"
150 fn check_let_return(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
151 let mut it = block.stmts.iter();
153 // we need both a let-binding stmt and an expr
155 if let Some(retexpr) = it.next_back();
156 if let ast::StmtKind::Expr(ref retexpr) = retexpr.node;
157 if let Some(stmt) = it.next_back();
158 if let ast::StmtKind::Local(ref local) = stmt.node;
159 // don't lint in the presence of type inference
160 if local.ty.is_none();
161 if !local.attrs.iter().any(attr_is_cfg);
162 if let Some(ref initexpr) = local.init;
163 if let ast::PatKind::Ident(_, ident, _) = local.pat.node;
164 if let ast::ExprKind::Path(_, ref path) = retexpr.node;
165 if match_path_ast(path, &[&ident.as_str()]);
166 if !in_external_macro(cx.sess(), initexpr.span);
168 span_note_and_lint(cx,
171 "returning the result of a let binding from a block. \
172 Consider returning the expression directly.",
174 "this expression can be directly returned");
180 impl LintPass for ReturnPass {
181 fn get_lints(&self) -> LintArray {
182 lint_array!(NEEDLESS_RETURN, LET_AND_RETURN, UNUSED_UNIT)
185 fn name(&self) -> &'static str {
190 impl EarlyLintPass for ReturnPass {
191 fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, decl: &ast::FnDecl, span: Span, _: ast::NodeId) {
193 FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
194 FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
197 if let ast::FunctionRetTy::Ty(ref ty) = decl.output;
198 if let ast::TyKind::Tup(ref vals) = ty.node;
199 if vals.is_empty() && !in_macro(ty.span) && get_def(span) == get_def(ty.span);
201 let (rspan, appl) = if let Ok(fn_source) =
202 cx.sess().source_map()
203 .span_to_snippet(span.with_hi(ty.span.hi())) {
204 if let Some(rpos) = fn_source.rfind("->") {
205 #[allow(clippy::cast_possible_truncation)]
206 (ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
207 Applicability::MachineApplicable)
209 (ty.span, Applicability::MaybeIncorrect)
212 (ty.span, Applicability::MaybeIncorrect)
214 span_lint_and_then(cx, UNUSED_UNIT, rspan, "unneeded unit return type", |db| {
217 "remove the `-> ()`",
226 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
227 self.check_let_return(cx, block);
229 if let Some(ref stmt) = block.stmts.last();
230 if let ast::StmtKind::Expr(ref expr) = stmt.node;
231 if is_unit_expr(expr) && !in_macro(expr.span);
234 span_lint_and_then(cx, UNUSED_UNIT, sp, "unneeded unit expression", |db| {
237 "remove the final `()`",
239 Applicability::MachineApplicable,
246 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
248 ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
249 if is_unit_expr(expr) && !in_macro(expr.span) {
250 span_lint_and_then(cx, UNUSED_UNIT, expr.span, "unneeded `()`", |db| {
255 Applicability::MachineApplicable,
265 fn attr_is_cfg(attr: &ast::Attribute) -> bool {
266 attr.meta_item_list().is_some() && attr.name() == "cfg"
270 fn get_def(span: Span) -> Option<Span> {
271 span.ctxt().outer().expn_info().and_then(|info| info.def_site)
274 // is this expr a `()` unit?
275 fn is_unit_expr(expr: &ast::Expr) -> bool {
276 if let ast::ExprKind::Tup(ref vals) = expr.node {