1 use crate::utils::SpanlessEq;
2 use crate::utils::{get_item_name, paths, snippet, snippet_opt};
3 use crate::utils::{snippet_with_applicability, span_lint_and_then};
4 use clippy_utils::ty::{is_type_diagnostic_item, match_type};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
8 use rustc_hir::{BorrowKind, Expr, ExprKind, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::hir::map::Map;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Span;
15 declare_clippy_lint! {
16 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
19 /// **Why is this bad?** Using `entry` is more efficient.
21 /// **Known problems:** Some false negatives, eg.:
23 /// # use std::collections::HashMap;
24 /// # let mut map = HashMap::new();
27 /// if !map.contains_key(&k) {
28 /// map.insert(k.clone(), v);
34 /// # use std::collections::HashMap;
35 /// # let mut map = HashMap::new();
38 /// if !map.contains_key(&k) {
42 /// can both be rewritten as:
44 /// # use std::collections::HashMap;
45 /// # let mut map = HashMap::new();
48 /// map.entry(k).or_insert(v);
52 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
55 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
57 impl<'tcx> LateLintPass<'tcx> for HashMapPass {
58 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
59 if let ExprKind::If(ref check, ref then_block, ref else_block) = expr.kind {
60 if let ExprKind::Unary(UnOp::Not, ref check) = check.kind {
61 if let Some((ty, map, key)) = check_cond(cx, check) {
62 // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
63 // we can give a better error message
66 && if let ExprKind::Block(ref then_block, _) = then_block.kind {
67 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
71 // XXXManishearth we can also check for if/else blocks containing `None`.
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>(cx: &LateContext<'_>, check: &'a Expr<'a>) -> Option<(&'static str, &'a Expr<'a>, &'a Expr<'a>)> {
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(BorrowKind::Ref, _, ref key) = params[1].kind;
110 let map = ¶ms[0];
111 let obj_ty = cx.typeck_results().expr_ty(map).peel_refs();
113 return if match_type(cx, obj_ty, &paths::BTREEMAP) {
114 Some(("BTreeMap", map, key))
116 else if is_type_diagnostic_item(cx, obj_ty, sym::hashmap_type) {
117 Some(("HashMap", map, key))
128 struct InsertVisitor<'a, 'tcx, 'b> {
129 cx: &'a LateContext<'tcx>,
137 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
138 type Map = Map<'tcx>;
140 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
142 if let ExprKind::MethodCall(ref path, _, ref params, _) = expr.kind;
143 if params.len() == 3;
144 if path.ident.name == sym!(insert);
145 if get_item_name(self.cx, self.map) == get_item_name(self.cx, ¶ms[0]);
146 if SpanlessEq::new(self.cx).eq_expr(self.key, ¶ms[1]);
147 if snippet_opt(self.cx, self.map.span) == snippet_opt(self.cx, params[0].span);
149 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
150 &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |diag| {
152 let mut app = Applicability::MachineApplicable;
153 let help = format!("{}.entry({}).or_insert({});",
154 snippet_with_applicability(self.cx, self.map.span, "map", &mut app),
155 snippet_with_applicability(self.cx, params[1].span, "..", &mut app),
156 snippet_with_applicability(self.cx, params[2].span, "..", &mut app));
158 diag.span_suggestion(
162 Applicability::MachineApplicable, // snippet
166 let help = format!("consider using `{}.entry({})`",
167 snippet(self.cx, self.map.span, "map"),
168 snippet(self.cx, params[1].span, ".."));
180 walk_expr(self, expr);
183 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
184 NestedVisitorMap::None