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