4 use utils::{snippet_opt, span_lint_and_then, is_adjusted, iter_input_pats};
6 #[allow(missing_copy_implementations)]
10 /// **What it does:** Checks for closures which just call another function where
11 /// the function can be called directly. `unsafe` functions or calls where types
12 /// get adjusted are ignored.
14 /// **Why is this bad?** Needlessly creating a closure adds code for no benefit
15 /// and gives the optimizer more work.
17 /// **Known problems:** None.
21 /// xs.map(|x| foo(x))
23 /// where `foo(_)` is a plain function that takes the exact argument type of `x`.
25 pub REDUNDANT_CLOSURE,
27 "redundant closures, i.e. `|a| foo(a)` (which can be written as just `foo`)"
30 impl LintPass for EtaPass {
31 fn get_lints(&self) -> LintArray {
32 lint_array!(REDUNDANT_CLOSURE)
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaPass {
37 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
39 ExprCall(_, ref args) |
40 ExprMethodCall(_, _, ref args) => {
42 check_closure(cx, arg)
50 fn check_closure(cx: &LateContext, expr: &Expr) {
51 if let ExprClosure(_, ref decl, eid, _) = expr.node {
52 let body = cx.tcx.hir.body(eid);
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.tables.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 || fn_ty.sig.skip_binder().output().sty == ty::TyNever {
75 for (a1, a2) in iter_input_pats(decl, body).zip(args) {
76 if let PatKind::Binding(_, _, ident, _) = a1.pat.node {
77 // XXXManishearth Should I be checking the binding mode here?
78 if let ExprPath(QPath::Resolved(None, ref p)) = a2.node {
79 if p.segments.len() != 1 {
80 // If it's a proper path, it can't be a local variable
83 if p.segments[0].name != ident.node {
84 // The two idents should be the same
94 span_lint_and_then(cx,
97 "redundant closure found",
98 |db| if let Some(snippet) = snippet_opt(cx, caller.span) {
99 db.span_suggestion(expr.span, "remove closure as shown:", snippet);