]> git.lizzy.rs Git - rust.git/blob - src/eta_reduction.rs
6948c1b22abb948b44e197c28281bb40e98dd9a2
[rust.git] / src / eta_reduction.rs
1 use syntax::ast::*;
2 use rustc::lint::{Context, LintPass, LintArray, Lint, Level};
3 use syntax::codemap::{Span, Spanned};
4 use syntax::print::pprust::expr_to_string;
5
6 use utils::span_lint;
7
8
9 #[allow(missing_copy_implementations)]
10 pub struct EtaPass;
11
12
13 declare_lint!(pub REDUNDANT_CLOSURE, Warn,
14               "Warn on usage of redundant closures, i.e. `|a| foo(a)`");
15
16 impl LintPass for EtaPass {
17     fn get_lints(&self) -> LintArray {
18         lint_array!(REDUNDANT_CLOSURE)
19     }
20
21     fn check_expr(&mut self, cx: &Context, expr: &Expr) {
22         if let ExprClosure(_, ref decl, ref blk) = expr.node {
23             if !blk.stmts.is_empty() {
24                 // || {foo(); bar()}; can't be reduced here
25                 return;
26             }
27             if let Some(ref ex) = blk.expr {
28                 if let ExprCall(ref caller, ref args) = ex.node {
29                     if args.len() != decl.inputs.len() {
30                         // Not the same number of arguments, there
31                         // is no way the closure is the same as the function
32                         return;
33                     }
34                     for (ref a1, ref a2) in decl.inputs.iter().zip(args) {
35                         if let PatIdent(_, ident, _) = a1.pat.node {
36                             // XXXManishearth Should I be checking the binding mode here?
37                             if let ExprPath(None, ref p) = a2.node {
38                                 if p.segments.len() != 1 {
39                                     // If it's a proper path, it can't be a local variable
40                                     return;
41                                 }
42                                 if p.segments[0].identifier != ident.node {
43                                     // The two idents should be the same
44                                     return
45                                 }
46                             } else {
47                                 return
48                             }
49                         } else {
50                             return
51                         }
52                     }
53                     span_lint(cx, REDUNDANT_CLOSURE, expr.span,
54                                  &format!("Redundant closure found, consider using `{}` in its place",
55                                           expr_to_string(caller))[..])
56                 }
57             }
58         }
59     }
60 }