]> git.lizzy.rs Git - rust.git/blob - src/entry.rs
Merge pull request #957 from oli-obk/needs_borrow
[rust.git] / src / entry.rs
1 use rustc::hir::*;
2 use rustc::hir::intravisit::{Visitor, walk_expr, walk_block};
3 use rustc::lint::*;
4 use syntax::codemap::Span;
5 use utils::SpanlessEq;
6 use utils::{get_item_name, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty};
7
8 /// **What it does:** This lint checks for uses of `contains_key` + `insert` on `HashMap` or
9 /// `BTreeMap`.
10 ///
11 /// **Why is this bad?** Using `entry` is more efficient.
12 ///
13 /// **Known problems:** Some false negatives, eg.:
14 /// ```
15 /// let k = &key;
16 /// if !m.contains_key(k) { m.insert(k.clone(), v); }
17 /// ```
18 ///
19 /// **Example:**
20 /// ```rust
21 /// if !m.contains_key(&k) { m.insert(k, v) }
22 /// ```
23 /// can be rewritten as:
24 /// ```rust
25 /// m.entry(k).or_insert(v);
26 /// ```
27 declare_lint! {
28     pub MAP_ENTRY,
29     Warn,
30     "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
31 }
32
33 #[derive(Copy,Clone)]
34 pub struct HashMapLint;
35
36 impl LintPass for HashMapLint {
37     fn get_lints(&self) -> LintArray {
38         lint_array!(MAP_ENTRY)
39     }
40 }
41
42 impl LateLintPass for HashMapLint {
43     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
44         if let ExprIf(ref check, ref then_block, ref else_block) = expr.node {
45             if let ExprUnary(UnOp::UnNot, ref check) = check.node {
46                 if let Some((ty, map, key)) = check_cond(cx, check) {
47                     // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
48                     // we can give a better error message
49                     let sole_expr = else_block.is_none() &&
50                                     ((then_block.expr.is_some() as usize) + then_block.stmts.len() == 1);
51
52                     let mut visitor = InsertVisitor {
53                         cx: cx,
54                         span: expr.span,
55                         ty: ty,
56                         map: map,
57                         key: key,
58                         sole_expr: sole_expr,
59                     };
60
61                     walk_block(&mut visitor, then_block);
62                 }
63             } else if let Some(ref else_block) = *else_block {
64                 if let Some((ty, map, key)) = check_cond(cx, check) {
65                     let mut visitor = InsertVisitor {
66                         cx: cx,
67                         span: expr.span,
68                         ty: ty,
69                         map: map,
70                         key: key,
71                         sole_expr: false,
72                     };
73
74                     walk_expr(&mut visitor, else_block);
75                 }
76             }
77         }
78     }
79 }
80
81 fn check_cond<'a, 'tcx, 'b>(cx: &'a LateContext<'a, 'tcx>, check: &'b Expr) -> Option<(&'static str, &'b Expr, &'b Expr)> {
82     if_let_chain! {[
83         let ExprMethodCall(ref name, _, ref params) = check.node,
84         params.len() >= 2,
85         name.node.as_str() == "contains_key",
86         let ExprAddrOf(_, ref key) = params[1].node
87     ], {
88         let map = &params[0];
89         let obj_ty = walk_ptrs_ty(cx.tcx.expr_ty(map));
90
91         return if match_type(cx, obj_ty, &paths::BTREEMAP) {
92             Some(("BTreeMap", map, key))
93         }
94         else if match_type(cx, obj_ty, &paths::HASHMAP) {
95             Some(("HashMap", map, key))
96         }
97         else {
98             None
99         };
100     }}
101
102     None
103 }
104
105 struct InsertVisitor<'a, 'tcx: 'a, 'b> {
106     cx: &'a LateContext<'a, 'tcx>,
107     span: Span,
108     ty: &'static str,
109     map: &'b Expr,
110     key: &'b Expr,
111     sole_expr: bool,
112 }
113
114 impl<'a, 'tcx, 'v, 'b> Visitor<'v> for InsertVisitor<'a, 'tcx, 'b> {
115     fn visit_expr(&mut self, expr: &'v Expr) {
116         if_let_chain! {[
117             let ExprMethodCall(ref name, _, ref params) = expr.node,
118             params.len() == 3,
119             name.node.as_str() == "insert",
120             get_item_name(self.cx, self.map) == get_item_name(self.cx, &*params[0]),
121             SpanlessEq::new(self.cx).eq_expr(self.key, &params[1])
122         ], {
123
124             span_lint_and_then(self.cx, MAP_ENTRY, self.span,
125                                &format!("usage of `contains_key` followed by `insert` on `{}`", self.ty), |db| {
126                 if self.sole_expr {
127                     let help = format!("{}.entry({}).or_insert({})",
128                                        snippet(self.cx, self.map.span, "map"),
129                                        snippet(self.cx, params[1].span, ".."),
130                                        snippet(self.cx, params[2].span, ".."));
131
132                     db.span_suggestion(self.span, "Consider using", help);
133                 }
134                 else {
135                     let help = format!("Consider using `{}.entry({})`",
136                                        snippet(self.cx, self.map.span, "map"),
137                                        snippet(self.cx, params[1].span, ".."));
138
139                     db.span_note(self.span, &help);
140                 }
141             });
142         }}
143
144         if !self.sole_expr {
145             walk_expr(self, expr);
146         }
147     }
148 }