4 use utils::{is_adjusted, iter_input_pats, snippet_opt, span_lint_and_then};
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
26 pub REDUNDANT_CLOSURE,
28 "redundant closures, i.e. `|a| foo(a)` (which can be written as just `foo`)"
31 impl LintPass for EtaPass {
32 fn get_lints(&self) -> LintArray {
33 lint_array!(REDUNDANT_CLOSURE)
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaPass {
38 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
40 ExprCall(_, ref args) | ExprMethodCall(_, _, ref args) => for arg in args {
41 check_closure(cx, arg)
48 fn check_closure(cx: &LateContext, expr: &Expr) {
49 if let ExprClosure(_, ref decl, eid, _, _) = expr.node {
50 let body = cx.tcx.hir.body(eid);
52 if let ExprCall(ref caller, ref args) = ex.node {
53 if args.len() != decl.inputs.len() {
54 // Not the same number of arguments, there
55 // is no way the closure is the same as the function
58 if is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg)) {
59 // Are the expression or the arguments type-adjusted? Then we need the closure
62 let fn_ty = cx.tables.expr_ty(caller);
64 // Is it an unsafe function? They don't implement the closure traits
65 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
66 let sig = fn_ty.fn_sig(cx.tcx);
67 if sig.skip_binder().unsafety == Unsafety::Unsafe || sig.skip_binder().output().sty == ty::TyNever {
73 for (a1, a2) in iter_input_pats(decl, body).zip(args) {
74 if let PatKind::Binding(_, _, ident, _) = a1.pat.node {
75 // XXXManishearth Should I be checking the binding mode here?
76 if let ExprPath(QPath::Resolved(None, ref p)) = a2.node {
77 if p.segments.len() != 1 {
78 // If it's a proper path, it can't be a local variable
81 if p.segments[0].name != ident.node {
82 // The two idents should be the same
92 span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure found", |db| {
93 if let Some(snippet) = snippet_opt(cx, caller.span) {
94 db.span_suggestion(expr.span, "remove closure as shown", snippet);