1 use clippy_utils::higher;
3 can_move_expr_to_closure_no_visit,
4 diagnostics::span_lint_and_sugg,
5 is_expr_final_block_expr, is_expr_used_or_unified, match_def_path, paths, peel_hir_expr_while,
6 source::{reindent_multiline, snippet_indent, snippet_with_applicability, snippet_with_context},
10 use rustc_errors::Applicability;
13 intravisit::{walk_expr, Visitor},
14 Block, Expr, ExprKind, Guard, HirId, Let, Pat, Stmt, StmtKind, UnOp,
16 use rustc_lint::{LateContext, LateLintPass};
17 use rustc_session::{declare_lint_pass, declare_tool_lint};
18 use rustc_span::{Span, SyntaxContext, DUMMY_SP};
20 declare_clippy_lint! {
22 /// Checks for uses of `contains_key` + `insert` on `HashMap`
25 /// ### Why is this bad?
26 /// Using `entry` is more efficient.
28 /// ### Known problems
29 /// The suggestion may have type inference errors in some cases. e.g.
31 /// let mut map = std::collections::HashMap::new();
32 /// let _ = if !map.contains_key(&0) {
41 /// # use std::collections::HashMap;
42 /// # let mut map = HashMap::new();
45 /// if !map.contains_key(&k) {
51 /// # use std::collections::HashMap;
52 /// # let mut map = HashMap::new();
55 /// map.entry(k).or_insert(v);
57 #[clippy::version = "pre 1.29.0"]
60 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
63 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
65 impl<'tcx> LateLintPass<'tcx> for HashMapPass {
66 #[expect(clippy::too_many_lines)]
67 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
68 let (cond_expr, then_expr, else_expr) = match higher::If::hir(expr) {
69 Some(higher::If { cond, then, r#else }) => (cond, then, r#else),
73 let (map_ty, contains_expr) = match try_parse_contains(cx, cond_expr) {
78 let then_search = match find_insert_calls(cx, &contains_expr, then_expr) {
83 let mut app = Applicability::MachineApplicable;
84 let map_str = snippet_with_context(cx, contains_expr.map.span, contains_expr.call_ctxt, "..", &mut app).0;
85 let key_str = snippet_with_context(cx, contains_expr.key.span, contains_expr.call_ctxt, "..", &mut app).0;
86 let sugg = if let Some(else_expr) = else_expr {
87 let else_search = match find_insert_calls(cx, &contains_expr, else_expr) {
88 Some(search) => search,
92 if then_search.edits.is_empty() && else_search.edits.is_empty() {
95 } else if then_search.edits.is_empty() || else_search.edits.is_empty() {
96 // if .. { insert } else { .. } or if .. { .. } else { insert }
97 let ((then_str, entry_kind), else_str) = match (else_search.edits.is_empty(), contains_expr.negated) {
99 then_search.snippet_vacant(cx, then_expr.span, &mut app),
100 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
103 then_search.snippet_occupied(cx, then_expr.span, &mut app),
104 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
107 else_search.snippet_occupied(cx, else_expr.span, &mut app),
108 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
111 else_search.snippet_vacant(cx, else_expr.span, &mut app),
112 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
116 "if let {}::{} = {}.entry({}) {} else {}",
125 // if .. { insert } else { insert }
126 let ((then_str, then_entry), (else_str, else_entry)) = if contains_expr.negated {
128 then_search.snippet_vacant(cx, then_expr.span, &mut app),
129 else_search.snippet_occupied(cx, else_expr.span, &mut app),
133 then_search.snippet_occupied(cx, then_expr.span, &mut app),
134 else_search.snippet_vacant(cx, else_expr.span, &mut app),
137 let indent_str = snippet_indent(cx, expr.span);
138 let indent_str = indent_str.as_deref().unwrap_or("");
140 "match {}.entry({}) {{\n{indent} {entry}::{} => {}\n\
141 {indent} {entry}::{} => {}\n{indent}}}",
145 reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
147 reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
148 entry = map_ty.entry_path(),
153 if then_search.edits.is_empty() {
159 if !then_search.allow_insert_closure {
160 let (body_str, entry_kind) = if contains_expr.negated {
161 then_search.snippet_vacant(cx, then_expr.span, &mut app)
163 then_search.snippet_occupied(cx, then_expr.span, &mut app)
166 "if let {}::{} = {}.entry({}) {}",
173 } else if let Some(insertion) = then_search.as_single_insertion() {
174 let value_str = snippet_with_context(cx, insertion.value.span, then_expr.span.ctxt(), "..", &mut app).0;
175 if contains_expr.negated {
176 if insertion.value.can_have_side_effects() {
177 format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, value_str)
179 format!("{}.entry({}).or_insert({});", map_str, key_str, value_str)
182 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
183 // This would need to be a different lint.
187 let block_str = then_search.snippet_closure(cx, then_expr.span, &mut app);
188 if contains_expr.negated {
189 format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, block_str)
191 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
192 // This would need to be a different lint.
202 &format!("usage of `contains_key` followed by `insert` on a `{}`", map_ty.name()),
210 #[derive(Clone, Copy)]
216 fn name(self) -> &'static str {
218 Self::Hash => "HashMap",
219 Self::BTree => "BTreeMap",
222 fn entry_path(self) -> &'static str {
224 Self::Hash => "std::collections::hash_map::Entry",
225 Self::BTree => "std::collections::btree_map::Entry",
230 struct ContainsExpr<'tcx> {
232 map: &'tcx Expr<'tcx>,
233 key: &'tcx Expr<'tcx>,
234 call_ctxt: SyntaxContext,
236 fn try_parse_contains<'tcx>(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> Option<(MapType, ContainsExpr<'tcx>)> {
237 let mut negated = false;
238 let expr = peel_hir_expr_while(expr, |e| match e.kind {
239 ExprKind::Unary(UnOp::Not, e) => {
246 ExprKind::MethodCall(
251 kind: ExprKind::AddrOf(_, _, key),
257 ) if key_span.ctxt() == expr.span.ctxt() => {
258 let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
259 let expr = ContainsExpr {
263 call_ctxt: expr.span.ctxt(),
265 if match_def_path(cx, id, &paths::BTREEMAP_CONTAINS_KEY) {
266 Some((MapType::BTree, expr))
267 } else if match_def_path(cx, id, &paths::HASHMAP_CONTAINS_KEY) {
268 Some((MapType::Hash, expr))
277 struct InsertExpr<'tcx> {
278 map: &'tcx Expr<'tcx>,
279 key: &'tcx Expr<'tcx>,
280 value: &'tcx Expr<'tcx>,
282 fn try_parse_insert<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<InsertExpr<'tcx>> {
283 if let ExprKind::MethodCall(_, [map, key, value], _) = expr.kind {
284 let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
285 if match_def_path(cx, id, &paths::BTREEMAP_INSERT) || match_def_path(cx, id, &paths::HASHMAP_INSERT) {
286 Some(InsertExpr { map, key, value })
295 /// An edit that will need to be made to move the expression to use the entry api
296 #[derive(Clone, Copy)]
298 /// A semicolon that needs to be removed. Used to create a closure for `insert_with`.
300 /// An insertion into the map.
301 Insertion(Insertion<'tcx>),
303 impl<'tcx> Edit<'tcx> {
304 fn as_insertion(self) -> Option<Insertion<'tcx>> {
305 if let Self::Insertion(i) = self { Some(i) } else { None }
308 #[derive(Clone, Copy)]
309 struct Insertion<'tcx> {
310 call: &'tcx Expr<'tcx>,
311 value: &'tcx Expr<'tcx>,
314 /// This visitor needs to do a multiple things:
315 /// * Find all usages of the map. An insertion can only be made before any other usages of the map.
316 /// * Determine if there's an insertion using the same key. There's no need for the entry api
318 /// * Determine if the final statement executed is an insertion. This is needed to use
319 /// `or_insert_with`.
320 /// * Determine if there's any sub-expression that can't be placed in a closure.
321 /// * Determine if there's only a single insert statement. `or_insert` can be used in this case.
322 #[expect(clippy::struct_excessive_bools)]
323 struct InsertSearcher<'cx, 'tcx> {
324 cx: &'cx LateContext<'tcx>,
325 /// The map expression used in the contains call.
326 map: &'tcx Expr<'tcx>,
327 /// The key expression used in the contains call.
328 key: &'tcx Expr<'tcx>,
329 /// The context of the top level block. All insert calls must be in the same context.
331 /// Whether this expression can be safely moved into a closure.
332 allow_insert_closure: bool,
333 /// Whether this expression can use the entry api.
335 /// Whether this expression is the final expression in this code path. This may be a statement.
337 // Is this expression a single insert. A slightly better suggestion can be made in this case.
338 is_single_insert: bool,
339 /// If the visitor has seen the map being used.
341 /// The locations where changes need to be made for the suggestion.
342 edits: Vec<Edit<'tcx>>,
343 /// A stack of loops the visitor is currently in.
345 /// Local variables created in the expression. These don't need to be captured.
348 impl<'tcx> InsertSearcher<'_, 'tcx> {
349 /// Visit the expression as a branch in control flow. Multiple insert calls can be used, but
350 /// only if they are on separate code paths. This will return whether the map was used in the
351 /// given expression.
352 fn visit_cond_arm(&mut self, e: &'tcx Expr<'_>) -> bool {
353 let is_map_used = self.is_map_used;
354 let in_tail_pos = self.in_tail_pos;
356 let res = self.is_map_used;
357 self.is_map_used = is_map_used;
358 self.in_tail_pos = in_tail_pos;
362 /// Visits an expression which is not itself in a tail position, but other sibling expressions
363 /// may be. e.g. if conditions
364 fn visit_non_tail_expr(&mut self, e: &'tcx Expr<'_>) {
365 let in_tail_pos = self.in_tail_pos;
366 self.in_tail_pos = false;
368 self.in_tail_pos = in_tail_pos;
371 impl<'tcx> Visitor<'tcx> for InsertSearcher<'_, 'tcx> {
372 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
374 StmtKind::Semi(e) => {
377 if self.in_tail_pos && self.allow_insert_closure {
378 // The spans are used to slice the top level expression into multiple parts. This requires that
379 // they all come from the same part of the source code.
380 if stmt.span.ctxt() == self.ctxt && e.span.ctxt() == self.ctxt {
382 .push(Edit::RemoveSemi(stmt.span.trim_start(e.span).unwrap_or(DUMMY_SP)));
384 self.allow_insert_closure = false;
388 StmtKind::Expr(e) => self.visit_expr(e),
389 StmtKind::Local(l) => {
390 self.visit_pat(l.pat);
391 if let Some(e) = l.init {
392 self.allow_insert_closure &= !self.in_tail_pos;
393 self.in_tail_pos = false;
394 self.is_single_insert = false;
398 StmtKind::Item(_) => {
399 self.allow_insert_closure &= !self.in_tail_pos;
400 self.is_single_insert = false;
405 fn visit_block(&mut self, block: &'tcx Block<'_>) {
406 // If the block is in a tail position, then the last expression (possibly a statement) is in the
407 // tail position. The rest, however, are not.
408 match (block.stmts, block.expr) {
410 self.allow_insert_closure &= !self.in_tail_pos;
412 ([], Some(expr)) => self.visit_expr(expr),
413 (stmts, Some(expr)) => {
414 let in_tail_pos = self.in_tail_pos;
415 self.in_tail_pos = false;
417 self.visit_stmt(stmt);
419 self.in_tail_pos = in_tail_pos;
420 self.visit_expr(expr);
422 ([stmts @ .., stmt], None) => {
423 let in_tail_pos = self.in_tail_pos;
424 self.in_tail_pos = false;
426 self.visit_stmt(stmt);
428 self.in_tail_pos = in_tail_pos;
429 self.visit_stmt(stmt);
434 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
435 if !self.can_use_entry {
439 match try_parse_insert(self.cx, expr) {
440 Some(insert_expr) if SpanlessEq::new(self.cx).eq_expr(self.map, insert_expr.map) => {
441 // Multiple inserts, inserts with a different key, and inserts from a macro can't use the entry api.
443 || !SpanlessEq::new(self.cx).eq_expr(self.key, insert_expr.key)
444 || expr.span.ctxt() != self.ctxt
446 self.can_use_entry = false;
450 self.edits.push(Edit::Insertion(Insertion {
452 value: insert_expr.value,
454 self.is_map_used = true;
455 self.allow_insert_closure &= self.in_tail_pos;
457 // The value doesn't affect whether there is only a single insert expression.
458 let is_single_insert = self.is_single_insert;
459 self.visit_non_tail_expr(insert_expr.value);
460 self.is_single_insert = is_single_insert;
462 _ if SpanlessEq::new(self.cx).eq_expr(self.map, expr) => {
463 self.is_map_used = true;
465 _ => match expr.kind {
466 ExprKind::If(cond_expr, then_expr, Some(else_expr)) => {
467 self.is_single_insert = false;
468 self.visit_non_tail_expr(cond_expr);
469 // Each branch may contain it's own insert expression.
470 let mut is_map_used = self.visit_cond_arm(then_expr);
471 is_map_used |= self.visit_cond_arm(else_expr);
472 self.is_map_used = is_map_used;
474 ExprKind::Match(scrutinee_expr, arms, _) => {
475 self.is_single_insert = false;
476 self.visit_non_tail_expr(scrutinee_expr);
477 // Each branch may contain it's own insert expression.
478 let mut is_map_used = self.is_map_used;
480 self.visit_pat(arm.pat);
481 if let Some(Guard::If(guard) | Guard::IfLet(&Let { init: guard, .. })) = arm.guard {
482 self.visit_non_tail_expr(guard);
484 is_map_used |= self.visit_cond_arm(arm.body);
486 self.is_map_used = is_map_used;
488 ExprKind::Loop(block, ..) => {
489 self.loops.push(expr.hir_id);
490 self.is_single_insert = false;
491 self.allow_insert_closure &= !self.in_tail_pos;
492 // Don't allow insertions inside of a loop.
493 let edit_len = self.edits.len();
494 self.visit_block(block);
495 if self.edits.len() != edit_len {
496 self.can_use_entry = false;
500 ExprKind::Block(block, _) => self.visit_block(block),
501 ExprKind::InlineAsm(_) => {
502 self.can_use_entry = false;
505 self.allow_insert_closure &= !self.in_tail_pos;
506 self.allow_insert_closure &=
507 can_move_expr_to_closure_no_visit(self.cx, expr, &self.loops, &self.locals);
508 // Sub expressions are no longer in the tail position.
509 self.is_single_insert = false;
510 self.in_tail_pos = false;
511 walk_expr(self, expr);
517 fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
518 p.each_binding_or_first(&mut |_, id, _, _| {
519 self.locals.insert(id);
524 struct InsertSearchResults<'tcx> {
525 edits: Vec<Edit<'tcx>>,
526 allow_insert_closure: bool,
527 is_single_insert: bool,
529 impl<'tcx> InsertSearchResults<'tcx> {
530 fn as_single_insertion(&self) -> Option<Insertion<'tcx>> {
531 self.is_single_insert.then(|| self.edits[0].as_insertion().unwrap())
536 cx: &LateContext<'_>,
538 app: &mut Applicability,
539 write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability),
541 let ctxt = span.ctxt();
542 let mut res = String::new();
543 for insertion in self.edits.iter().filter_map(|e| e.as_insertion()) {
544 res.push_str(&snippet_with_applicability(
546 span.until(insertion.call.span),
550 if is_expr_used_or_unified(cx.tcx, insertion.call) {
551 write_wrapped(&mut res, insertion, ctxt, app);
556 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
559 span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
561 res.push_str(&snippet_with_applicability(cx, span, "..", app));
565 fn snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
567 self.snippet(cx, span, app, |res, insertion, ctxt, app| {
568 // Insertion into a map would return `Some(&mut value)`, but the entry returns `&mut value`
571 "Some(e.insert({}))",
572 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
579 fn snippet_vacant(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
581 self.snippet(cx, span, app, |res, insertion, ctxt, app| {
582 // Insertion into a map would return `None`, but the entry returns a mutable reference.
583 let _ = if is_expr_final_block_expr(cx.tcx, insertion.call) {
586 "e.insert({});\n{}None",
587 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
588 snippet_indent(cx, insertion.call.span).as_deref().unwrap_or(""),
593 "{{ e.insert({}); None }}",
594 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
602 fn snippet_closure(&self, cx: &LateContext<'_>, mut span: Span, app: &mut Applicability) -> String {
603 let ctxt = span.ctxt();
604 let mut res = String::new();
605 for edit in &self.edits {
607 Edit::Insertion(insertion) => {
608 // Cut out the value from `map.insert(key, value)`
609 res.push_str(&snippet_with_applicability(
611 span.until(insertion.call.span),
615 res.push_str(&snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0);
616 span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
618 Edit::RemoveSemi(semi_span) => {
619 // Cut out the semicolon. This allows the value to be returned from the closure.
620 res.push_str(&snippet_with_applicability(cx, span.until(semi_span), "..", app));
621 span = span.trim_start(semi_span).unwrap_or(DUMMY_SP);
625 res.push_str(&snippet_with_applicability(cx, span, "..", app));
630 fn find_insert_calls<'tcx>(
631 cx: &LateContext<'tcx>,
632 contains_expr: &ContainsExpr<'tcx>,
633 expr: &'tcx Expr<'_>,
634 ) -> Option<InsertSearchResults<'tcx>> {
635 let mut s = InsertSearcher {
637 map: contains_expr.map,
638 key: contains_expr.key,
639 ctxt: expr.span.ctxt(),
642 allow_insert_closure: true,
645 is_single_insert: true,
647 locals: HirIdSet::default(),
650 let allow_insert_closure = s.allow_insert_closure;
651 let is_single_insert = s.is_single_insert;
653 s.can_use_entry.then(|| InsertSearchResults {
655 allow_insert_closure,