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
11 /// function can be called directly. `unsafe` functions or calls where types get adjusted are
14 /// **Why is this bad?** Needlessly creating a closure adds code for no
15 /// benefit and gives the optimizer more work.
17 /// **Known problems:** None
19 /// **Example:** `xs.map(|x| foo(x))` where `foo(_)` is a plain function that takes the exact
20 /// argument type of `x`.
22 pub REDUNDANT_CLOSURE, Warn,
23 "using redundant closures, i.e. `|a| foo(a)` (which can be written as just `foo`)"
26 impl LintPass for EtaPass {
27 fn get_lints(&self) -> LintArray {
28 lint_array!(REDUNDANT_CLOSURE)
32 impl LateLintPass for EtaPass {
33 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
35 ExprCall(_, ref args) |
36 ExprMethodCall(_, _, ref args) => {
38 check_closure(cx, arg)
46 fn check_closure(cx: &LateContext, expr: &Expr) {
47 if let ExprClosure(_, ref decl, ref blk, _) = expr.node {
48 if !blk.stmts.is_empty() {
49 // || {foo(); bar()}; can't be reduced here
53 if let Some(ref ex) = blk.expr {
54 if let ExprCall(ref caller, ref args) = ex.node {
55 if args.len() != decl.inputs.len() {
56 // Not the same number of arguments, there
57 // is no way the closure is the same as the function
60 if is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)) {
61 // Are the expression or the arguments type-adjusted? Then we need the closure
64 let fn_ty = cx.tcx.expr_ty(caller);
66 // Is it an unsafe function? They don't implement the closure traits
67 ty::TyFnDef(_, _, fn_ty) |
68 ty::TyFnPtr(fn_ty) => {
69 if fn_ty.unsafety == Unsafety::Unsafe ||
70 fn_ty.sig.skip_binder().output == ty::FnOutput::FnDiverging {
76 for (ref a1, ref a2) in decl.inputs.iter().zip(args) {
77 if let PatKind::Binding(_, ident, _) = a1.pat.node {
78 // XXXManishearth Should I be checking the binding mode here?
79 if let ExprPath(None, ref p) = a2.node {
80 if p.segments.len() != 1 {
81 // If it's a proper path, it can't be a local variable
84 if p.segments[0].name != ident.node {
85 // The two idents should be the same
95 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
96 if let Some(snippet) = snippet_opt(cx, caller.span) {
97 db.span_suggestion(expr.span, "remove closure as shown:", snippet);