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