]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/entry.rs
Remove crate:: prefixes from crate paths
[rust.git] / clippy_lints / src / entry.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::SpanlessEq;
11 use crate::utils::{get_item_name, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty};
12 use if_chain::if_chain;
13 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
14 use rustc::hir::*;
15 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use rustc::{declare_tool_lint, lint_array};
17 use rustc_errors::Applicability;
18 use syntax::source_map::Span;
19
20 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
21 /// or `BTreeMap`.
22 ///
23 /// **Why is this bad?** Using `entry` is more efficient.
24 ///
25 /// **Known problems:** Some false negatives, eg.:
26 /// ```rust
27 /// let k = &key;
28 /// if !m.contains_key(k) {
29 ///     m.insert(k.clone(), v);
30 /// }
31 /// ```
32 ///
33 /// **Example:**
34 /// ```rust
35 /// if !m.contains_key(&k) {
36 ///     m.insert(k, v)
37 /// }
38 /// ```
39 /// can be rewritten as:
40 /// ```rust
41 /// m.entry(k).or_insert(v);
42 /// ```
43 declare_clippy_lint! {
44     pub MAP_ENTRY,
45     perf,
46     "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
47 }
48
49 #[derive(Copy, Clone)]
50 pub struct HashMapLint;
51
52 impl LintPass for HashMapLint {
53     fn get_lints(&self) -> LintArray {
54         lint_array!(MAP_ENTRY)
55     }
56 }
57
58 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapLint {
59     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
60         if let ExprKind::If(ref check, ref then_block, ref else_block) = expr.node {
61             if let ExprKind::Unary(UnOp::UnNot, ref check) = check.node {
62                 if let Some((ty, map, key)) = check_cond(cx, check) {
63                     // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
64                     // we can give a better error message
65                     let sole_expr = {
66                         else_block.is_none()
67                             && if let ExprKind::Block(ref then_block, _) = then_block.node {
68                                 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
69                             } else {
70                                 true
71                             }
72                     };
73
74                     let mut visitor = InsertVisitor {
75                         cx,
76                         span: expr.span,
77                         ty,
78                         map,
79                         key,
80                         sole_expr,
81                     };
82
83                     walk_expr(&mut visitor, &**then_block);
84                 }
85             } else if let Some(ref else_block) = *else_block {
86                 if let Some((ty, map, key)) = check_cond(cx, check) {
87                     let mut visitor = InsertVisitor {
88                         cx,
89                         span: expr.span,
90                         ty,
91                         map,
92                         key,
93                         sole_expr: false,
94                     };
95
96                     walk_expr(&mut visitor, else_block);
97                 }
98             }
99         }
100     }
101 }
102
103 fn check_cond<'a, 'tcx, 'b>(
104     cx: &'a LateContext<'a, 'tcx>,
105     check: &'b Expr,
106 ) -> Option<(&'static str, &'b Expr, &'b Expr)> {
107     if_chain! {
108         if let ExprKind::MethodCall(ref path, _, ref params) = check.node;
109         if params.len() >= 2;
110         if path.ident.name == "contains_key";
111         if let ExprKind::AddrOf(_, ref key) = params[1].node;
112         then {
113             let map = &params[0];
114             let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
115
116             return if match_type(cx, obj_ty, &paths::BTREEMAP) {
117                 Some(("BTreeMap", map, key))
118             }
119             else if match_type(cx, obj_ty, &paths::HASHMAP) {
120                 Some(("HashMap", map, key))
121             }
122             else {
123                 None
124             };
125         }
126     }
127
128     None
129 }
130
131 struct InsertVisitor<'a, 'tcx: 'a, 'b> {
132     cx: &'a LateContext<'a, 'tcx>,
133     span: Span,
134     ty: &'static str,
135     map: &'b Expr,
136     key: &'b Expr,
137     sole_expr: bool,
138 }
139
140 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
141     fn visit_expr(&mut self, expr: &'tcx Expr) {
142         if_chain! {
143             if let ExprKind::MethodCall(ref path, _, ref params) = expr.node;
144             if params.len() == 3;
145             if path.ident.name == "insert";
146             if get_item_name(self.cx, self.map) == get_item_name(self.cx, &params[0]);
147             if SpanlessEq::new(self.cx).eq_expr(self.key, &params[1]);
148             then {
149                 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
150                                    &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |db| {
151                     if self.sole_expr {
152                         let help = format!("{}.entry({}).or_insert({})",
153                                            snippet(self.cx, self.map.span, "map"),
154                                            snippet(self.cx, params[1].span, ".."),
155                                            snippet(self.cx, params[2].span, ".."));
156
157                         db.span_suggestion_with_applicability(
158                             self.span,
159                             "consider using",
160                             help,
161                             Applicability::MachineApplicable, // snippet
162                         );
163                     }
164                     else {
165                         let help = format!("{}.entry({})",
166                                            snippet(self.cx, self.map.span, "map"),
167                                            snippet(self.cx, params[1].span, ".."));
168
169                         db.span_suggestion_with_applicability(
170                             self.span,
171                             "consider using",
172                             help,
173                             Applicability::MachineApplicable, // snippet
174                         );
175                     }
176                 });
177             }
178         }
179
180         if !self.sole_expr {
181             walk_expr(self, expr);
182         }
183     }
184     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
185         NestedVisitorMap::None
186     }
187 }