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::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
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;
12 declare_clippy_lint! {
13 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
16 /// **Why is this bad?** Using `entry` is more efficient.
18 /// **Known problems:** Some false negatives, eg.:
20 /// # use std::collections::HashMap;
21 /// # let mut map = HashMap::new();
24 /// if !map.contains_key(&k) {
25 /// map.insert(k.clone(), v);
31 /// # use std::collections::HashMap;
32 /// # let mut map = HashMap::new();
35 /// if !map.contains_key(&k) {
39 /// can both be rewritten as:
41 /// # use std::collections::HashMap;
42 /// # let mut map = HashMap::new();
45 /// map.entry(k).or_insert(v);
49 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
52 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
54 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapPass {
55 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
56 if let Some((ref check, ref then_block, ref else_block)) = higher::if_block(&expr) {
57 if let ExprKind::Unary(UnOp::UnNot, ref check) = check.kind {
58 if let Some((ty, map, key)) = check_cond(cx, check) {
59 // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
60 // we can give a better error message
63 && if let ExprKind::Block(ref then_block, _) = then_block.kind {
64 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
68 // XXXManishearth we can also check for if/else blocks containing `None`.
71 let mut visitor = InsertVisitor {
80 walk_expr(&mut visitor, &**then_block);
82 } else if let Some(ref else_block) = *else_block {
83 if let Some((ty, map, key)) = check_cond(cx, check) {
84 let mut visitor = InsertVisitor {
93 walk_expr(&mut visitor, else_block);
100 fn check_cond<'a, 'tcx, 'b>(
101 cx: &'a LateContext<'a, 'tcx>,
103 ) -> Option<(&'static str, &'b Expr, &'b Expr)> {
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(_, ref key) = params[1].kind;
110 let map = ¶ms[0];
111 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
113 return if match_type(cx, obj_ty, &paths::BTREEMAP) {
114 Some(("BTreeMap", map, key))
116 else if match_type(cx, obj_ty, &paths::HASHMAP) {
117 Some(("HashMap", map, key))
128 struct InsertVisitor<'a, 'tcx, 'b> {
129 cx: &'a LateContext<'a, 'tcx>,
137 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
138 fn visit_expr(&mut self, expr: &'tcx Expr) {
140 if let ExprKind::MethodCall(ref path, _, ref params) = expr.kind;
141 if params.len() == 3;
142 if path.ident.name == sym!(insert);
143 if get_item_name(self.cx, self.map) == get_item_name(self.cx, ¶ms[0]);
144 if SpanlessEq::new(self.cx).eq_expr(self.key, ¶ms[1]);
145 if snippet_opt(self.cx, self.map.span) == snippet_opt(self.cx, params[0].span);
147 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
148 &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |db| {
150 let mut app = Applicability::MachineApplicable;
151 let help = format!("{}.entry({}).or_insert({});",
152 snippet_with_applicability(self.cx, self.map.span, "map", &mut app),
153 snippet_with_applicability(self.cx, params[1].span, "..", &mut app),
154 snippet_with_applicability(self.cx, params[2].span, "..", &mut app));
160 Applicability::MachineApplicable, // snippet
164 let help = format!("consider using `{}.entry({})`",
165 snippet(self.cx, self.map.span, "map"),
166 snippet(self.cx, params[1].span, ".."));
178 walk_expr(self, expr);
181 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
182 NestedVisitorMap::None