]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bytecount.rs
rustup https://github.com/rust-lang/rust/pull/61758/files
[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_lint_pass, declare_tool_lint};
10 use rustc_errors::Applicability;
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     /// &my_data.filter(|&x| x == 0u8).count() // use bytecount::count instead
28     /// ```
29     pub NAIVE_BYTECOUNT,
30     perf,
31     "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
32 }
33
34 declare_lint_pass!(ByteCount => [NAIVE_BYTECOUNT]);
35
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ByteCount {
37     fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr) {
38         if_chain! {
39             if let ExprKind::MethodCall(ref count, _, ref count_args) = expr.node;
40             if count.ident.name == sym!(count);
41             if count_args.len() == 1;
42             if let ExprKind::MethodCall(ref filter, _, ref filter_args) = count_args[0].node;
43             if filter.ident.name == sym!(filter);
44             if filter_args.len() == 2;
45             if let ExprKind::Closure(_, _, body_id, _, _) = filter_args[1].node;
46             then {
47                 let body = cx.tcx.hir().body(body_id);
48                 if_chain! {
49                     if body.arguments.len() == 1;
50                     if let Some(argname) = get_pat_name(&body.arguments[0].pat);
51                     if let ExprKind::Binary(ref op, ref l, ref r) = body.value.node;
52                     if op.node == BinOpKind::Eq;
53                     if match_type(cx,
54                                walk_ptrs_ty(cx.tables.expr_ty(&filter_args[0])),
55                                &paths::SLICE_ITER);
56                     then {
57                         let needle = match get_path_name(l) {
58                             Some(name) if check_arg(name, argname, r) => r,
59                             _ => match get_path_name(r) {
60                                 Some(name) if check_arg(name, argname, l) => l,
61                                 _ => { return; }
62                             }
63                         };
64                         if ty::Uint(UintTy::U8) != walk_ptrs_ty(cx.tables.expr_ty(needle)).sty {
65                             return;
66                         }
67                         let haystack = if let ExprKind::MethodCall(ref path, _, ref args) =
68                                 filter_args[0].node {
69                             let p = path.ident.name;
70                             if (p == sym!(iter) || p == sym!(iter_mut)) && args.len() == 1 {
71                                 &args[0]
72                             } else {
73                                 &filter_args[0]
74                             }
75                         } else {
76                             &filter_args[0]
77                         };
78                         let mut applicability = Applicability::MaybeIncorrect;
79                         span_lint_and_sugg(
80                             cx,
81                             NAIVE_BYTECOUNT,
82                             expr.span,
83                             "You appear to be counting bytes the naive way",
84                             "Consider using the bytecount crate",
85                             format!("bytecount::count({}, {})",
86                                     snippet_with_applicability(cx, haystack.span, "..", &mut applicability),
87                                     snippet_with_applicability(cx, needle.span, "..", &mut applicability)),
88                             applicability,
89                         );
90                     }
91                 };
92             }
93         };
94     }
95 }
96
97 fn check_arg(name: Name, arg: Name, needle: &Expr) -> bool {
98     name == arg && !contains_name(name, needle)
99 }
100
101 fn get_path_name(expr: &Expr) -> Option<Name> {
102     match expr.node {
103         ExprKind::Box(ref e) | ExprKind::AddrOf(_, ref e) | ExprKind::Unary(UnOp::UnDeref, ref e) => get_path_name(e),
104         ExprKind::Block(ref b, _) => {
105             if b.stmts.is_empty() {
106                 b.expr.as_ref().and_then(|p| get_path_name(p))
107             } else {
108                 None
109             }
110         },
111         ExprKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
112         _ => None,
113     }
114 }