1 use crate::utils::SpanlessEq;
2 use crate::utils::{get_item_name, higher, is_type_diagnostic_item, match_type, paths, snippet, snippet_opt};
3 use crate::utils::{snippet_with_applicability, span_lint_and_then, walk_ptrs_ty};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
7 use rustc_hir::{BorrowKind, Expr, ExprKind, UnOp};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::hir::map::Map;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Span;
13 declare_clippy_lint! {
14 /// **What it does:** Checks for uses of `contains_key` + `insert` on `HashMap`
17 /// **Why is this bad?** Using `entry` is more efficient.
19 /// **Known problems:** Some false negatives, eg.:
21 /// # use std::collections::HashMap;
22 /// # let mut map = HashMap::new();
25 /// if !map.contains_key(&k) {
26 /// map.insert(k.clone(), v);
32 /// # use std::collections::HashMap;
33 /// # let mut map = HashMap::new();
36 /// if !map.contains_key(&k) {
40 /// can both be rewritten as:
42 /// # use std::collections::HashMap;
43 /// # let mut map = HashMap::new();
46 /// map.entry(k).or_insert(v);
50 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
53 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
55 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapPass {
56 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
57 if let Some((ref check, ref then_block, ref else_block)) = higher::if_block(&expr) {
58 if let ExprKind::Unary(UnOp::UnNot, ref check) = check.kind {
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
64 && if let ExprKind::Block(ref then_block, _) = then_block.kind {
65 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
69 // XXXManishearth we can also check for if/else blocks containing `None`.
72 let mut visitor = InsertVisitor {
81 walk_expr(&mut visitor, &**then_block);
83 } else if let Some(ref else_block) = *else_block {
84 if let Some((ty, map, key)) = check_cond(cx, check) {
85 let mut visitor = InsertVisitor {
94 walk_expr(&mut visitor, else_block);
101 fn check_cond<'a, 'tcx, 'b>(
102 cx: &'a LateContext<'a, 'tcx>,
104 ) -> Option<(&'static str, &'b Expr<'b>, &'b Expr<'b>)> {
106 if let ExprKind::MethodCall(ref path, _, ref params) = check.kind;
107 if params.len() >= 2;
108 if path.ident.name == sym!(contains_key);
109 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref key) = params[1].kind;
111 let map = ¶ms[0];
112 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(map));
114 return if match_type(cx, obj_ty, &paths::BTREEMAP) {
115 Some(("BTreeMap", map, key))
117 else if is_type_diagnostic_item(cx, obj_ty, sym!(hashmap_type)) {
118 Some(("HashMap", map, key))
129 struct InsertVisitor<'a, 'tcx, 'b> {
130 cx: &'a LateContext<'a, 'tcx>,
138 impl<'a, 'tcx, 'b> Visitor<'tcx> for InsertVisitor<'a, 'tcx, 'b> {
139 type Map = Map<'tcx>;
141 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
143 if let ExprKind::MethodCall(ref path, _, ref params) = expr.kind;
144 if params.len() == 3;
145 if path.ident.name == sym!(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]);
148 if snippet_opt(self.cx, self.map.span) == snippet_opt(self.cx, params[0].span);
150 span_lint_and_then(self.cx, MAP_ENTRY, self.span,
151 &format!("usage of `contains_key` followed by `insert` on a `{}`", self.ty), |diag| {
153 let mut app = Applicability::MachineApplicable;
154 let help = format!("{}.entry({}).or_insert({});",
155 snippet_with_applicability(self.cx, self.map.span, "map", &mut app),
156 snippet_with_applicability(self.cx, params[1].span, "..", &mut app),
157 snippet_with_applicability(self.cx, params[2].span, "..", &mut app));
159 diag.span_suggestion(
163 Applicability::MachineApplicable, // snippet
167 let help = format!("consider using `{}.entry({})`",
168 snippet(self.cx, self.map.span, "map"),
169 snippet(self.cx, params[1].span, ".."));
181 walk_expr(self, expr);
184 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
185 NestedVisitorMap::None