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