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