4 use utils::{snippet_opt, span_lint_and_then, is_adjusted};
6 #[allow(missing_copy_implementations)]
10 /// **What it does:** This lint checks for closures which just call another function where the function can be called directly. `unsafe` functions or calls where types get adjusted are ignored.
12 /// **Why is this bad?** Needlessly creating a closure just costs heap space and adds code for no benefit.
14 /// **Known problems:** None
16 /// **Example:** `xs.map(|x| foo(x))` where `foo(_)` is a plain function that takes the exact argument type of `x`.
18 pub REDUNDANT_CLOSURE, Warn,
19 "using redundant closures, i.e. `|a| foo(a)` (which can be written as just `foo`)"
22 impl LintPass for EtaPass {
23 fn get_lints(&self) -> LintArray {
24 lint_array!(REDUNDANT_CLOSURE)
28 impl LateLintPass for EtaPass {
29 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
31 ExprCall(_, ref args) |
32 ExprMethodCall(_, _, ref args) => {
34 check_closure(cx, arg)
42 fn check_closure(cx: &LateContext, expr: &Expr) {
43 if let ExprClosure(_, ref decl, ref blk, _) = expr.node {
44 if !blk.stmts.is_empty() {
45 // || {foo(); bar()}; can't be reduced here
49 if let Some(ref ex) = blk.expr {
50 if let ExprCall(ref caller, ref args) = ex.node {
51 if args.len() != decl.inputs.len() {
52 // Not the same number of arguments, there
53 // is no way the closure is the same as the function
56 if is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)) {
57 // Are the expression or the arguments type-adjusted? Then we need the closure
60 let fn_ty = cx.tcx.expr_ty(caller);
62 // Is it an unsafe function? They don't implement the closure traits
63 ty::TyFnDef(_, _, fn_ty) |
64 ty::TyFnPtr(fn_ty) => {
65 if fn_ty.unsafety == Unsafety::Unsafe ||
66 fn_ty.sig.skip_binder().output == ty::FnOutput::FnDiverging {
72 for (ref a1, ref a2) in decl.inputs.iter().zip(args) {
73 if let PatKind::Ident(_, ident, _) = a1.pat.node {
74 // XXXManishearth Should I be checking the binding mode here?
75 if let ExprPath(None, ref p) = a2.node {
76 if p.segments.len() != 1 {
77 // If it's a proper path, it can't be a local variable
80 if p.segments[0].identifier != ident.node {
81 // The two idents should be the same
91 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
92 if let Some(snippet) = snippet_opt(cx, caller.span) {
93 db.span_suggestion(expr.span, "remove closure as shown:", snippet);