]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bytecount.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / bytecount.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
5 use rustc::ty;
6 use syntax::ast::{Name, UintTy};
7 use crate::utils::{contains_name, get_pat_name, match_type, paths, single_segment_path, snippet, span_lint_and_sugg,
8             walk_ptrs_ty};
9
10 /// **What it does:** Checks for naive byte counts
11 ///
12 /// **Why is this bad?** The [`bytecount`](https://crates.io/crates/bytecount)
13 /// crate has methods to count your bytes faster, especially for large slices.
14 ///
15 /// **Known problems:** If you have predominantly small slices, the
16 /// `bytecount::count(..)` method may actually be slower. However, if you can
17 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
18 /// faster in those cases.
19 ///
20 /// **Example:**
21 ///
22 /// ```rust
23 /// &my_data.filter(|&x| x == 0u8).count() // use bytecount::count instead
24 /// ```
25 declare_clippy_lint! {
26     pub NAIVE_BYTECOUNT,
27     perf,
28     "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
29 }
30
31 #[derive(Copy, Clone)]
32 pub struct ByteCount;
33
34 impl LintPass for ByteCount {
35     fn get_lints(&self) -> LintArray {
36         lint_array!(NAIVE_BYTECOUNT)
37     }
38 }
39
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ByteCount {
41     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
42         if_chain! {
43             if let ExprKind::MethodCall(ref count, _, ref count_args) = expr.node;
44             if count.ident.name == "count";
45             if count_args.len() == 1;
46             if let ExprKind::MethodCall(ref filter, _, ref filter_args) = count_args[0].node;
47             if filter.ident.name == "filter";
48             if filter_args.len() == 2;
49             if let ExprKind::Closure(_, _, body_id, _, _) = filter_args[1].node;
50             then {
51                 let body = cx.tcx.hir.body(body_id);
52                 if_chain! {
53                     if body.arguments.len() == 1;
54                     if let Some(argname) = get_pat_name(&body.arguments[0].pat);
55                     if let ExprKind::Binary(ref op, ref l, ref r) = body.value.node;
56                     if op.node == BinOpKind::Eq;
57                     if match_type(cx,
58                                walk_ptrs_ty(cx.tables.expr_ty(&filter_args[0])),
59                                &paths::SLICE_ITER);
60                     then {
61                         let needle = match get_path_name(l) {
62                             Some(name) if check_arg(name, argname, r) => r,
63                             _ => match get_path_name(r) {
64                                 Some(name) if check_arg(name, argname, l) => l,
65                                 _ => { return; }
66                             }
67                         };
68                         if ty::TyUint(UintTy::U8) != walk_ptrs_ty(cx.tables.expr_ty(needle)).sty {
69                             return;
70                         }
71                         let haystack = if let ExprKind::MethodCall(ref path, _, ref args) =
72                                 filter_args[0].node {
73                             let p = path.ident.name;
74                             if (p == "iter" || p == "iter_mut") && args.len() == 1 {
75                                 &args[0]
76                             } else {
77                                 &filter_args[0]
78                             }
79                         } else {
80                             &filter_args[0]
81                         };
82                         span_lint_and_sugg(cx,
83                                            NAIVE_BYTECOUNT,
84                                            expr.span,
85                                            "You appear to be counting bytes the naive way",
86                                            "Consider using the bytecount crate",
87                                            format!("bytecount::count({}, {})",
88                                                     snippet(cx, haystack.span, ".."),
89                                                     snippet(cx, needle.span, "..")));
90                     }
91                 };
92             }
93         };
94     }
95 }
96
97 fn check_arg(name: Name, arg: Name, needle: &Expr) -> bool {
98     name == arg && !contains_name(name, needle)
99 }
100
101 fn get_path_name(expr: &Expr) -> Option<Name> {
102     match expr.node {
103         ExprKind::Box(ref e) | ExprKind::AddrOf(_, ref e) | ExprKind::Unary(UnOp::UnDeref, ref e) => get_path_name(e),
104         ExprKind::Block(ref b, _) => if b.stmts.is_empty() {
105             b.expr.as_ref().and_then(|p| get_path_name(p))
106         } else {
107             None
108         },
109         ExprKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
110         _ => None,
111     }
112 }