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