1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
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;
21 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
24 /// **Why is this bad?** Using `entry` is more efficient.
26 /// **Known problems:** Some false negatives, eg.:
29 /// if !m.contains_key(k) { m.insert(k.clone(), v); }
34 /// if !m.contains_key(&k) { m.insert(k, v) }
36 /// can be rewritten as:
38 /// m.entry(k).or_insert(v);
40 declare_clippy_lint! {
43 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
46 #[derive(Copy, Clone)]
47 pub struct HashMapLint;
49 impl LintPass for HashMapLint {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(MAP_ENTRY)
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
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
70 let mut visitor = InsertVisitor {
79 walk_expr(&mut visitor, &**then_block);
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 {
92 walk_expr(&mut visitor, else_block);
99 fn check_cond<'a, 'tcx, 'b>(
100 cx: &'a LateContext<'a, 'tcx>,
102 ) -> Option<(&'static str, &'b Expr, &'b Expr)> {
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;
109 let map = ¶ms[0];
110 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
112 return if match_type(cx, obj_ty, &paths::BTREEMAP) {
113 Some(("BTreeMap", map, key))
115 else if match_type(cx, obj_ty, &paths::HASHMAP) {
116 Some(("HashMap", map, key))
127 struct InsertVisitor<'a, 'tcx: 'a, 'b> {
128 cx: &'a LateContext<'a, 'tcx>,
136 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
137 fn visit_expr(&mut self, expr: &'tcx Expr) {
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, ¶ms[0]);
143 if SpanlessEq::new(self.cx).eq_expr(self.key, ¶ms[1]);
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| {
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, ".."));
153 db.span_suggestion_with_applicability(
157 Applicability::MachineApplicable, // snippet
161 let help = format!("{}.entry({})",
162 snippet(self.cx, self.map.span, "map"),
163 snippet(self.cx, params[1].span, ".."));
165 db.span_suggestion_with_applicability(
169 Applicability::MachineApplicable, // snippet
177 walk_expr(self, expr);
180 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
181 NestedVisitorMap::None