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