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