2 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
4 use rustc::{declare_lint, lint_array};
5 use if_chain::if_chain;
6 use syntax::source_map::Span;
7 use crate::utils::SpanlessEq;
8 use crate::utils::{get_item_name, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty};
10 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
13 /// **Why is this bad?** Using `entry` is more efficient.
15 /// **Known problems:** Some false negatives, eg.:
18 /// if !m.contains_key(k) { m.insert(k.clone(), v); }
23 /// if !m.contains_key(&k) { m.insert(k, v) }
25 /// can be rewritten as:
27 /// m.entry(k).or_insert(v);
29 declare_clippy_lint! {
32 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
35 #[derive(Copy, Clone)]
36 pub struct HashMapLint;
38 impl LintPass for HashMapLint {
39 fn get_lints(&self) -> LintArray {
40 lint_array!(MAP_ENTRY)
44 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapLint {
45 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
46 if let ExprKind::If(ref check, ref then_block, ref else_block) = expr.node {
47 if let ExprKind::Unary(UnOp::UnNot, ref check) = check.node {
48 if let Some((ty, map, key)) = check_cond(cx, check) {
49 // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
50 // we can give a better error message
52 else_block.is_none() && if let ExprKind::Block(ref then_block, _) = then_block.node {
53 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
59 let mut visitor = InsertVisitor {
68 walk_expr(&mut visitor, &**then_block);
70 } else if let Some(ref else_block) = *else_block {
71 if let Some((ty, map, key)) = check_cond(cx, check) {
72 let mut visitor = InsertVisitor {
81 walk_expr(&mut visitor, else_block);
88 fn check_cond<'a, 'tcx, 'b>(
89 cx: &'a LateContext<'a, 'tcx>,
91 ) -> Option<(&'static str, &'b Expr, &'b Expr)> {
93 if let ExprKind::MethodCall(ref path, _, ref params) = check.node;
95 if path.ident.name == "contains_key";
96 if let ExprKind::AddrOf(_, ref key) = params[1].node;
99 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
101 return if match_type(cx, obj_ty, &paths::BTREEMAP) {
102 Some(("BTreeMap", map, key))
104 else if match_type(cx, obj_ty, &paths::HASHMAP) {
105 Some(("HashMap", map, key))
116 struct InsertVisitor<'a, 'tcx: 'a, 'b> {
117 cx: &'a LateContext<'a, 'tcx>,
125 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
126 fn visit_expr(&mut self, expr: &'tcx Expr) {
128 if let ExprKind::MethodCall(ref path, _, ref params) = expr.node;
129 if params.len() == 3;
130 if path.ident.name == "insert";
131 if get_item_name(self.cx, self.map) == get_item_name(self.cx, ¶ms[0]);
132 if SpanlessEq::new(self.cx).eq_expr(self.key, ¶ms[1]);
134 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
135 &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |db| {
137 let help = format!("{}.entry({}).or_insert({})",
138 snippet(self.cx, self.map.span, "map"),
139 snippet(self.cx, params[1].span, ".."),
140 snippet(self.cx, params[2].span, ".."));
142 db.span_suggestion(self.span, "consider using", help);
145 let help = format!("{}.entry({})",
146 snippet(self.cx, self.map.span, "map"),
147 snippet(self.cx, params[1].span, ".."));
149 db.span_suggestion(self.span, "consider using", help);
156 walk_expr(self, expr);
159 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
160 NestedVisitorMap::None