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