]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bytecount.rs
Auto merge of #8901 - Jarcho:sharing_code, r=dswij
[rust.git] / clippy_lints / src / bytecount.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::ty::match_type;
4 use clippy_utils::visitors::is_local_used;
5 use clippy_utils::{path_to_local_id, paths, peel_blocks, peel_ref_operators, strip_pat_refs};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind, PatKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::{self, UintTy};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::sym;
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Checks for naive byte counts
17     ///
18     /// ### Why is this bad?
19     /// The [`bytecount`](https://crates.io/crates/bytecount)
20     /// crate has methods to count your bytes faster, especially for large slices.
21     ///
22     /// ### Known problems
23     /// If you have predominantly small slices, the
24     /// `bytecount::count(..)` method may actually be slower. However, if you can
25     /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
26     /// faster in those cases.
27     ///
28     /// ### Example
29     /// ```rust
30     /// # let vec = vec![1_u8];
31     /// let count = vec.iter().filter(|x| **x == 0u8).count();
32     /// ```
33     ///
34     /// Use instead:
35     /// ```rust,ignore
36     /// # let vec = vec![1_u8];
37     /// let count = bytecount::count(&vec, 0u8);
38     /// ```
39     #[clippy::version = "pre 1.29.0"]
40     pub NAIVE_BYTECOUNT,
41     pedantic,
42     "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
43 }
44
45 declare_lint_pass!(ByteCount => [NAIVE_BYTECOUNT]);
46
47 impl<'tcx> LateLintPass<'tcx> for ByteCount {
48     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
49         if_chain! {
50             if let ExprKind::MethodCall(count, [count_recv], _) = expr.kind;
51             if count.ident.name == sym::count;
52             if let ExprKind::MethodCall(filter, [filter_recv, filter_arg], _) = count_recv.kind;
53             if filter.ident.name == sym!(filter);
54             if let ExprKind::Closure(_, _, body_id, _, _) = filter_arg.kind;
55             let body = cx.tcx.hir().body(body_id);
56             if let [param] = body.params;
57             if let PatKind::Binding(_, arg_id, _, _) = strip_pat_refs(param.pat).kind;
58             if let ExprKind::Binary(ref op, l, r) = body.value.kind;
59             if op.node == BinOpKind::Eq;
60             if match_type(cx,
61                        cx.typeck_results().expr_ty(filter_recv).peel_refs(),
62                        &paths::SLICE_ITER);
63             let operand_is_arg = |expr| {
64                 let expr = peel_ref_operators(cx, peel_blocks(expr));
65                 path_to_local_id(expr, arg_id)
66             };
67             let needle = if operand_is_arg(l) {
68                 r
69             } else if operand_is_arg(r) {
70                 l
71             } else {
72                 return;
73             };
74             if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(needle).peel_refs().kind();
75             if !is_local_used(cx, needle, arg_id);
76             then {
77                 let haystack = if let ExprKind::MethodCall(path, args, _) =
78                         filter_recv.kind {
79                     let p = path.ident.name;
80                     if (p == sym::iter || p == sym!(iter_mut)) && args.len() == 1 {
81                         &args[0]
82                     } else {
83                         filter_recv
84                     }
85                 } else {
86                     filter_recv
87                 };
88                 let mut applicability = Applicability::MaybeIncorrect;
89                 span_lint_and_sugg(
90                     cx,
91                     NAIVE_BYTECOUNT,
92                     expr.span,
93                     "you appear to be counting bytes the naive way",
94                     "consider using the bytecount crate",
95                     format!("bytecount::count({}, {})",
96                             snippet_with_applicability(cx, haystack.span, "..", &mut applicability),
97                             snippet_with_applicability(cx, needle.span, "..", &mut applicability)),
98                     applicability,
99                 );
100             }
101         };
102     }
103 }