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