]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/bytecount.rs
Rollup merge of #91313 - petrochenkov:cratexp, r=Aaron1011
[rust.git] / src / tools / clippy / 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_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
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     /// &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead
32     /// ```
33     pub NAIVE_BYTECOUNT,
34     pedantic,
35     "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
36 }
37
38 declare_lint_pass!(ByteCount => [NAIVE_BYTECOUNT]);
39
40 impl<'tcx> LateLintPass<'tcx> for ByteCount {
41     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
42         if_chain! {
43             if let ExprKind::MethodCall(count, _, [count_recv], _) = expr.kind;
44             if count.ident.name == sym!(count);
45             if let ExprKind::MethodCall(filter, _, [filter_recv, filter_arg], _) = count_recv.kind;
46             if filter.ident.name == sym!(filter);
47             if let ExprKind::Closure(_, _, body_id, _, _) = filter_arg.kind;
48             let body = cx.tcx.hir().body(body_id);
49             if let [param] = body.params;
50             if let PatKind::Binding(_, arg_id, _, _) = strip_pat_refs(param.pat).kind;
51             if let ExprKind::Binary(ref op, l, r) = body.value.kind;
52             if op.node == BinOpKind::Eq;
53             if match_type(cx,
54                        cx.typeck_results().expr_ty(filter_recv).peel_refs(),
55                        &paths::SLICE_ITER);
56             let operand_is_arg = |expr| {
57                 let expr = peel_ref_operators(cx, remove_blocks(expr));
58                 path_to_local_id(expr, arg_id)
59             };
60             let needle = if operand_is_arg(l) {
61                 r
62             } else if operand_is_arg(r) {
63                 l
64             } else {
65                 return;
66             };
67             if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(needle).peel_refs().kind();
68             if !is_local_used(cx, needle, arg_id);
69             then {
70                 let haystack = if let ExprKind::MethodCall(path, _, args, _) =
71                         filter_recv.kind {
72                     let p = path.ident.name;
73                     if (p == sym::iter || p == sym!(iter_mut)) && args.len() == 1 {
74                         &args[0]
75                     } else {
76                         &filter_recv
77                     }
78                 } else {
79                     &filter_recv
80                 };
81                 let mut applicability = Applicability::MaybeIncorrect;
82                 span_lint_and_sugg(
83                     cx,
84                     NAIVE_BYTECOUNT,
85                     expr.span,
86                     "you appear to be counting bytes the naive way",
87                     "consider using the bytecount crate",
88                     format!("bytecount::count({}, {})",
89                             snippet_with_applicability(cx, haystack.span, "..", &mut applicability),
90                             snippet_with_applicability(cx, needle.span, "..", &mut applicability)),
91                     applicability,
92                 );
93             }
94         };
95     }
96 }