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