]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/entry.rs
Auto merge of #4327 - phansch:doctests_perf, r=flip1995
[rust.git] / clippy_lints / src / entry.rs
1 use crate::utils::SpanlessEq;
2 use crate::utils::{get_item_name, higher, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty};
3 use if_chain::if_chain;
4 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc::hir::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use rustc_errors::Applicability;
9 use syntax::source_map::Span;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
13     /// or `BTreeMap`.
14     ///
15     /// **Why is this bad?** Using `entry` is more efficient.
16     ///
17     /// **Known problems:** Some false negatives, eg.:
18     /// ```rust
19     /// # use std::collections::HashMap;
20     /// # let mut map = HashMap::new();
21     /// # let v = 1;
22     /// # let k = 1;
23     /// if !map.contains_key(&k) {
24     ///     map.insert(k.clone(), v);
25     /// }
26     /// ```
27     ///
28     /// **Example:**
29     /// ```rust
30     /// # use std::collections::HashMap;
31     /// # let mut map = HashMap::new();
32     /// # let k = 1;
33     /// # let v = 1;
34     /// if !map.contains_key(&k) {
35     ///     map.insert(k, v);
36     /// }
37     /// ```
38     /// can both be rewritten as:
39     /// ```rust
40     /// # use std::collections::HashMap;
41     /// # let mut map = HashMap::new();
42     /// # let k = 1;
43     /// # let v = 1;
44     /// map.entry(k).or_insert(v);
45     /// ```
46     pub MAP_ENTRY,
47     perf,
48     "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
49 }
50
51 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
52
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapPass {
54     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
55         if let Some((ref check, ref then_block, ref else_block)) = higher::if_block(&expr) {
56             if let ExprKind::Unary(UnOp::UnNot, ref check) = check.node {
57                 if let Some((ty, map, key)) = check_cond(cx, check) {
58                     // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
59                     // we can give a better error message
60                     let sole_expr = {
61                         else_block.is_none()
62                             && if let ExprKind::Block(ref then_block, _) = then_block.node {
63                                 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
64                             } else {
65                                 true
66                             }
67                     };
68
69                     let mut visitor = InsertVisitor {
70                         cx,
71                         span: expr.span,
72                         ty,
73                         map,
74                         key,
75                         sole_expr,
76                     };
77
78                     walk_expr(&mut visitor, &**then_block);
79                 }
80             } else if let Some(ref else_block) = *else_block {
81                 if let Some((ty, map, key)) = check_cond(cx, check) {
82                     let mut visitor = InsertVisitor {
83                         cx,
84                         span: expr.span,
85                         ty,
86                         map,
87                         key,
88                         sole_expr: false,
89                     };
90
91                     walk_expr(&mut visitor, else_block);
92                 }
93             }
94         }
95     }
96 }
97
98 fn check_cond<'a, 'tcx, 'b>(
99     cx: &'a LateContext<'a, 'tcx>,
100     check: &'b Expr,
101 ) -> Option<(&'static str, &'b Expr, &'b Expr)> {
102     if_chain! {
103         if let ExprKind::MethodCall(ref path, _, ref params) = check.node;
104         if params.len() >= 2;
105         if path.ident.name == sym!(contains_key);
106         if let ExprKind::AddrOf(_, ref key) = params[1].node;
107         then {
108             let map = &params[0];
109             let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
110
111             return if match_type(cx, obj_ty, &paths::BTREEMAP) {
112                 Some(("BTreeMap", map, key))
113             }
114             else if match_type(cx, obj_ty, &paths::HASHMAP) {
115                 Some(("HashMap", map, key))
116             }
117             else {
118                 None
119             };
120         }
121     }
122
123     None
124 }
125
126 struct InsertVisitor<'a, 'tcx, 'b> {
127     cx: &'a LateContext<'a, 'tcx>,
128     span: Span,
129     ty: &'static str,
130     map: &'b Expr,
131     key: &'b Expr,
132     sole_expr: bool,
133 }
134
135 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
136     fn visit_expr(&mut self, expr: &'tcx Expr) {
137         if_chain! {
138             if let ExprKind::MethodCall(ref path, _, ref params) = expr.node;
139             if params.len() == 3;
140             if path.ident.name == sym!(insert);
141             if get_item_name(self.cx, self.map) == get_item_name(self.cx, &params[0]);
142             if SpanlessEq::new(self.cx).eq_expr(self.key, &params[1]);
143             then {
144                 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
145                                    &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |db| {
146                     if self.sole_expr {
147                         let help = format!("{}.entry({}).or_insert({})",
148                                            snippet(self.cx, self.map.span, "map"),
149                                            snippet(self.cx, params[1].span, ".."),
150                                            snippet(self.cx, params[2].span, ".."));
151
152                         db.span_suggestion(
153                             self.span,
154                             "consider using",
155                             help,
156                             Applicability::MachineApplicable, // snippet
157                         );
158                     }
159                     else {
160                         let help = format!("{}.entry({})",
161                                            snippet(self.cx, self.map.span, "map"),
162                                            snippet(self.cx, params[1].span, ".."));
163
164                         db.span_suggestion(
165                             self.span,
166                             "consider using",
167                             help,
168                             Applicability::MachineApplicable, // snippet
169                         );
170                     }
171                 });
172             }
173         }
174
175         if !self.sole_expr {
176             walk_expr(self, expr);
177         }
178     }
179     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
180         NestedVisitorMap::None
181     }
182 }