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