]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bytecount.rs
4f7ffdcdfb499ac972c9dbd9eeced0153b492ddc
[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::LocalUsedVisitor;
5 use clippy_utils::{path_to_local_id, paths, peel_ref_operators, remove_blocks, 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:** 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     pedantic,
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<'tcx> LateLintPass<'tcx> for ByteCount {
39     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
40         if_chain! {
41             if let ExprKind::MethodCall(count, _, [count_recv], _) = expr.kind;
42             if count.ident.name == sym!(count);
43             if let ExprKind::MethodCall(filter, _, [filter_recv, filter_arg], _) = count_recv.kind;
44             if filter.ident.name == sym!(filter);
45             if let ExprKind::Closure(_, _, body_id, _, _) = filter_arg.kind;
46             let body = cx.tcx.hir().body(body_id);
47             if let [param] = body.params;
48             if let PatKind::Binding(_, arg_id, _, _) = strip_pat_refs(param.pat).kind;
49             if let ExprKind::Binary(ref op, l, r) = body.value.kind;
50             if op.node == BinOpKind::Eq;
51             if match_type(cx,
52                        cx.typeck_results().expr_ty(filter_recv).peel_refs(),
53                        &paths::SLICE_ITER);
54             let operand_is_arg = |expr| {
55                 let expr = peel_ref_operators(cx, remove_blocks(expr));
56                 path_to_local_id(expr, arg_id)
57             };
58             let needle = if operand_is_arg(l) {
59                 r
60             } else if operand_is_arg(r) {
61                 l
62             } else {
63                 return;
64             };
65             if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(needle).peel_refs().kind();
66             if !LocalUsedVisitor::new(cx, arg_id).check_expr(needle);
67             then {
68                 let haystack = if let ExprKind::MethodCall(path, _, args, _) =
69                         filter_recv.kind {
70                     let p = path.ident.name;
71                     if (p == sym::iter || p == sym!(iter_mut)) && args.len() == 1 {
72                         &args[0]
73                     } else {
74                         &filter_recv
75                     }
76                 } else {
77                     &filter_recv
78                 };
79                 let mut applicability = Applicability::MaybeIncorrect;
80                 span_lint_and_sugg(
81                     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_with_applicability(cx, haystack.span, "..", &mut applicability),
88                             snippet_with_applicability(cx, needle.span, "..", &mut applicability)),
89                     applicability,
90                 );
91             }
92         };
93     }
94 }