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