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