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.
10 use crate::rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use crate::syntax::source_map::Span;
16 use crate::utils::SpanlessEq;
17 use crate::utils::{get_item_name, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty};
18 use if_chain::if_chain;
20 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
23 /// **Why is this bad?** Using `entry` is more efficient.
25 /// **Known problems:** Some false negatives, eg.:
28 /// if !m.contains_key(k) {
29 /// m.insert(k.clone(), v);
35 /// if !m.contains_key(&k) {
39 /// can be rewritten as:
41 /// m.entry(k).or_insert(v);
43 declare_clippy_lint! {
46 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
49 #[derive(Copy, Clone)]
50 pub struct HashMapLint;
52 impl LintPass for HashMapLint {
53 fn get_lints(&self) -> LintArray {
54 lint_array!(MAP_ENTRY)
58 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapLint {
59 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
60 if let ExprKind::If(ref check, ref then_block, ref else_block) = expr.node {
61 if let ExprKind::Unary(UnOp::UnNot, ref check) = check.node {
62 if let Some((ty, map, key)) = check_cond(cx, check) {
63 // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
64 // we can give a better error message
67 && if let ExprKind::Block(ref then_block, _) = then_block.node {
68 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
74 let mut visitor = InsertVisitor {
83 walk_expr(&mut visitor, &**then_block);
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 {
96 walk_expr(&mut visitor, else_block);
103 fn check_cond<'a, 'tcx, 'b>(
104 cx: &'a LateContext<'a, 'tcx>,
106 ) -> Option<(&'static str, &'b Expr, &'b Expr)> {
108 if let ExprKind::MethodCall(ref path, _, ref params) = check.node;
109 if params.len() >= 2;
110 if path.ident.name == "contains_key";
111 if let ExprKind::AddrOf(_, ref key) = params[1].node;
113 let map = ¶ms[0];
114 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
116 return if match_type(cx, obj_ty, &paths::BTREEMAP) {
117 Some(("BTreeMap", map, key))
119 else if match_type(cx, obj_ty, &paths::HASHMAP) {
120 Some(("HashMap", map, key))
131 struct InsertVisitor<'a, 'tcx: 'a, 'b> {
132 cx: &'a LateContext<'a, 'tcx>,
140 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
141 fn visit_expr(&mut self, expr: &'tcx Expr) {
143 if let ExprKind::MethodCall(ref path, _, ref params) = expr.node;
144 if params.len() == 3;
145 if path.ident.name == "insert";
146 if get_item_name(self.cx, self.map) == get_item_name(self.cx, ¶ms[0]);
147 if SpanlessEq::new(self.cx).eq_expr(self.key, ¶ms[1]);
149 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
150 &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |db| {
152 let help = format!("{}.entry({}).or_insert({})",
153 snippet(self.cx, self.map.span, "map"),
154 snippet(self.cx, params[1].span, ".."),
155 snippet(self.cx, params[2].span, ".."));
157 db.span_suggestion_with_applicability(
161 Applicability::MachineApplicable, // snippet
165 let help = format!("{}.entry({})",
166 snippet(self.cx, self.map.span, "map"),
167 snippet(self.cx, params[1].span, ".."));
169 db.span_suggestion_with_applicability(
173 Applicability::MachineApplicable, // snippet
181 walk_expr(self, expr);
184 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
185 NestedVisitorMap::None