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