1 use crate::utils::SpanlessEq;
2 use crate::utils::{get_item_name, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty};
3 use if_chain::if_chain;
4 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_errors::Applicability;
9 use syntax::source_map::Span;
11 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
14 /// **Why is this bad?** Using `entry` is more efficient.
16 /// **Known problems:** Some false negatives, eg.:
19 /// if !m.contains_key(k) {
20 /// m.insert(k.clone(), v);
26 /// if !m.contains_key(&k) {
30 /// can be rewritten as:
32 /// m.entry(k).or_insert(v);
34 declare_clippy_lint! {
37 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
40 #[derive(Copy, Clone)]
41 pub struct HashMapLint;
43 impl LintPass for HashMapLint {
44 fn get_lints(&self) -> LintArray {
45 lint_array!(MAP_ENTRY)
48 fn name(&self) -> &'static str {
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapLint {
54 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
55 if let ExprKind::If(ref check, ref then_block, ref else_block) = expr.node {
56 if let ExprKind::Unary(UnOp::UnNot, ref check) = check.node {
57 if let Some((ty, map, key)) = check_cond(cx, check) {
58 // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
59 // we can give a better error message
62 && if let ExprKind::Block(ref then_block, _) = then_block.node {
63 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
69 let mut visitor = InsertVisitor {
78 walk_expr(&mut visitor, &**then_block);
80 } else if let Some(ref else_block) = *else_block {
81 if let Some((ty, map, key)) = check_cond(cx, check) {
82 let mut visitor = InsertVisitor {
91 walk_expr(&mut visitor, else_block);
98 fn check_cond<'a, 'tcx, 'b>(
99 cx: &'a LateContext<'a, 'tcx>,
101 ) -> Option<(&'static str, &'b Expr, &'b Expr)> {
103 if let ExprKind::MethodCall(ref path, _, ref params) = check.node;
104 if params.len() >= 2;
105 if path.ident.name == "contains_key";
106 if let ExprKind::AddrOf(_, ref key) = params[1].node;
108 let map = ¶ms[0];
109 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
111 return if match_type(cx, obj_ty, &paths::BTREEMAP) {
112 Some(("BTreeMap", map, key))
114 else if match_type(cx, obj_ty, &paths::HASHMAP) {
115 Some(("HashMap", map, key))
126 struct InsertVisitor<'a, 'tcx: 'a, 'b> {
127 cx: &'a LateContext<'a, 'tcx>,
135 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
136 fn visit_expr(&mut self, expr: &'tcx Expr) {
138 if let ExprKind::MethodCall(ref path, _, ref params) = expr.node;
139 if params.len() == 3;
140 if path.ident.name == "insert";
141 if get_item_name(self.cx, self.map) == get_item_name(self.cx, ¶ms[0]);
142 if SpanlessEq::new(self.cx).eq_expr(self.key, ¶ms[1]);
144 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
145 &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |db| {
147 let help = format!("{}.entry({}).or_insert({})",
148 snippet(self.cx, self.map.span, "map"),
149 snippet(self.cx, params[1].span, ".."),
150 snippet(self.cx, params[2].span, ".."));
156 Applicability::MachineApplicable, // snippet
160 let help = format!("{}.entry({})",
161 snippet(self.cx, self.map.span, "map"),
162 snippet(self.cx, params[1].span, ".."));
168 Applicability::MachineApplicable, // snippet
176 walk_expr(self, expr);
179 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
180 NestedVisitorMap::None