]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bytecount.rs
Auto merge of #5040 - JohnTitor:rustup-0111, r=flip1995
[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::lint::{LateContext, LateLintPass};
7 use rustc::ty;
8 use rustc_errors::Applicability;
9 use rustc_hir::*;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use syntax::ast::{Name, UintTy};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for naive byte counts
15     ///
16     /// **Why is this bad?** The [`bytecount`](https://crates.io/crates/bytecount)
17     /// crate has methods to count your bytes faster, especially for large slices.
18     ///
19     /// **Known problems:** If you have predominantly small slices, the
20     /// `bytecount::count(..)` method may actually be slower. However, if you can
21     /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
22     /// faster in those cases.
23     ///
24     /// **Example:**
25     ///
26     /// ```rust
27     /// # let vec = vec![1_u8];
28     /// &vec.iter().filter(|x| **x == 0u8).count(); // use bytecount::count instead
29     /// ```
30     pub NAIVE_BYTECOUNT,
31     perf,
32     "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
33 }
34
35 declare_lint_pass!(ByteCount => [NAIVE_BYTECOUNT]);
36
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ByteCount {
38     fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
39         if_chain! {
40             if let ExprKind::MethodCall(ref count, _, ref count_args) = expr.kind;
41             if count.ident.name == sym!(count);
42             if count_args.len() == 1;
43             if let ExprKind::MethodCall(ref filter, _, ref filter_args) = count_args[0].kind;
44             if filter.ident.name == sym!(filter);
45             if filter_args.len() == 2;
46             if let ExprKind::Closure(_, _, body_id, _, _) = filter_args[1].kind;
47             then {
48                 let body = cx.tcx.hir().body(body_id);
49                 if_chain! {
50                     if body.params.len() == 1;
51                     if let Some(argname) = get_pat_name(&body.params[0].pat);
52                     if let ExprKind::Binary(ref op, ref l, ref r) = body.value.kind;
53                     if op.node == BinOpKind::Eq;
54                     if match_type(cx,
55                                walk_ptrs_ty(cx.tables.expr_ty(&filter_args[0])),
56                                &paths::SLICE_ITER);
57                     then {
58                         let needle = match get_path_name(l) {
59                             Some(name) if check_arg(name, argname, r) => r,
60                             _ => match get_path_name(r) {
61                                 Some(name) if check_arg(name, argname, l) => l,
62                                 _ => { return; }
63                             }
64                         };
65                         if ty::Uint(UintTy::U8) != walk_ptrs_ty(cx.tables.expr_ty(needle)).kind {
66                             return;
67                         }
68                         let haystack = if let ExprKind::MethodCall(ref path, _, ref args) =
69                                 filter_args[0].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_args[0]
75                             }
76                         } else {
77                             &filter_args[0]
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         };
95     }
96 }
97
98 fn check_arg(name: Name, arg: Name, needle: &Expr<'_>) -> bool {
99     name == arg && !contains_name(name, needle)
100 }
101
102 fn get_path_name(expr: &Expr<'_>) -> Option<Name> {
103     match expr.kind {
104         ExprKind::Box(ref e) | ExprKind::AddrOf(BorrowKind::Ref, _, ref e) | ExprKind::Unary(UnOp::UnDeref, ref e) => {
105             get_path_name(e)
106         },
107         ExprKind::Block(ref b, _) => {
108             if b.stmts.is_empty() {
109                 b.expr.as_ref().and_then(|p| get_path_name(p))
110             } else {
111                 None
112             }
113         },
114         ExprKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
115         _ => None,
116     }
117 }