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, ErasedMap, NestedVisitorMap, Visitor},
14 Block, Expr, ExprKind, Guard, HirId, 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) {
49 /// can both be rewritten as:
51 /// # use std::collections::HashMap;
52 /// # let mut map = HashMap::new();
55 /// map.entry(k).or_insert(v);
59 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
62 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
64 impl<'tcx> LateLintPass<'tcx> for HashMapPass {
65 #[allow(clippy::too_many_lines)]
66 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
67 let (cond_expr, then_expr, else_expr) = match higher::If::hir(expr) {
68 Some(higher::If { cond, then, r#else }) => (cond, then, r#else),
72 let (map_ty, contains_expr) = match try_parse_contains(cx, cond_expr) {
77 let then_search = match find_insert_calls(cx, &contains_expr, then_expr) {
82 let mut app = Applicability::MachineApplicable;
83 let map_str = snippet_with_context(cx, contains_expr.map.span, contains_expr.call_ctxt, "..", &mut app).0;
84 let key_str = snippet_with_context(cx, contains_expr.key.span, contains_expr.call_ctxt, "..", &mut app).0;
85 let sugg = if let Some(else_expr) = else_expr {
86 let else_search = match find_insert_calls(cx, &contains_expr, else_expr) {
87 Some(search) => search,
91 if then_search.edits.is_empty() && else_search.edits.is_empty() {
94 } else if then_search.edits.is_empty() || else_search.edits.is_empty() {
95 // if .. { insert } else { .. } or if .. { .. } else { insert }
96 let ((then_str, entry_kind), else_str) = match (else_search.edits.is_empty(), contains_expr.negated) {
98 then_search.snippet_vacant(cx, then_expr.span, &mut app),
99 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
102 then_search.snippet_occupied(cx, then_expr.span, &mut app),
103 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
106 else_search.snippet_occupied(cx, else_expr.span, &mut app),
107 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
110 else_search.snippet_vacant(cx, else_expr.span, &mut app),
111 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
115 "if let {}::{} = {}.entry({}) {} else {}",
124 // if .. { insert } else { insert }
125 let ((then_str, then_entry), (else_str, else_entry)) = if contains_expr.negated {
127 then_search.snippet_vacant(cx, then_expr.span, &mut app),
128 else_search.snippet_occupied(cx, else_expr.span, &mut app),
132 then_search.snippet_occupied(cx, then_expr.span, &mut app),
133 else_search.snippet_vacant(cx, else_expr.span, &mut app),
136 let indent_str = snippet_indent(cx, expr.span);
137 let indent_str = indent_str.as_deref().unwrap_or("");
139 "match {}.entry({}) {{\n{indent} {entry}::{} => {}\n\
140 {indent} {entry}::{} => {}\n{indent}}}",
144 reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
146 reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
147 entry = map_ty.entry_path(),
152 if then_search.edits.is_empty() {
158 if !then_search.allow_insert_closure {
159 let (body_str, entry_kind) = if contains_expr.negated {
160 then_search.snippet_vacant(cx, then_expr.span, &mut app)
162 then_search.snippet_occupied(cx, then_expr.span, &mut app)
165 "if let {}::{} = {}.entry({}) {}",
172 } else if let Some(insertion) = then_search.as_single_insertion() {
173 let value_str = snippet_with_context(cx, insertion.value.span, then_expr.span.ctxt(), "..", &mut app).0;
174 if contains_expr.negated {
175 if insertion.value.can_have_side_effects() {
176 format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, value_str)
178 format!("{}.entry({}).or_insert({});", map_str, key_str, value_str)
181 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
182 // This would need to be a different lint.
186 let block_str = then_search.snippet_closure(cx, then_expr.span, &mut app);
187 if contains_expr.negated {
188 format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, block_str)
190 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
191 // This would need to be a different lint.
201 &format!("usage of `contains_key` followed by `insert` on a `{}`", map_ty.name()),
209 #[derive(Clone, Copy)]
215 fn name(self) -> &'static str {
217 Self::Hash => "HashMap",
218 Self::BTree => "BTreeMap",
221 fn entry_path(self) -> &'static str {
223 Self::Hash => "std::collections::hash_map::Entry",
224 Self::BTree => "std::collections::btree_map::Entry",
229 struct ContainsExpr<'tcx> {
231 map: &'tcx Expr<'tcx>,
232 key: &'tcx Expr<'tcx>,
233 call_ctxt: SyntaxContext,
235 fn try_parse_contains(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> Option<(MapType, ContainsExpr<'tcx>)> {
236 let mut negated = false;
237 let expr = peel_hir_expr_while(expr, |e| match e.kind {
238 ExprKind::Unary(UnOp::Not, e) => {
245 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(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>),
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 #[allow(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 type Map = ErasedMap<'tcx>;
373 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
374 NestedVisitorMap::None
377 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
379 StmtKind::Semi(e) => {
382 if self.in_tail_pos && self.allow_insert_closure {
383 // The spans are used to slice the top level expression into multiple parts. This requires that
384 // they all come from the same part of the source code.
385 if stmt.span.ctxt() == self.ctxt && e.span.ctxt() == self.ctxt {
387 .push(Edit::RemoveSemi(stmt.span.trim_start(e.span).unwrap_or(DUMMY_SP)));
389 self.allow_insert_closure = false;
393 StmtKind::Expr(e) => self.visit_expr(e),
394 StmtKind::Local(l) => {
395 self.visit_pat(l.pat);
396 if let Some(e) = l.init {
397 self.allow_insert_closure &= !self.in_tail_pos;
398 self.in_tail_pos = false;
399 self.is_single_insert = false;
403 StmtKind::Item(_) => {
404 self.allow_insert_closure &= !self.in_tail_pos;
405 self.is_single_insert = false;
410 fn visit_block(&mut self, block: &'tcx Block<'_>) {
411 // If the block is in a tail position, then the last expression (possibly a statement) is in the
412 // tail position. The rest, however, are not.
413 match (block.stmts, block.expr) {
415 self.allow_insert_closure &= !self.in_tail_pos;
417 ([], Some(expr)) => self.visit_expr(expr),
418 (stmts, Some(expr)) => {
419 let in_tail_pos = self.in_tail_pos;
420 self.in_tail_pos = false;
422 self.visit_stmt(stmt);
424 self.in_tail_pos = in_tail_pos;
425 self.visit_expr(expr);
427 ([stmts @ .., stmt], None) => {
428 let in_tail_pos = self.in_tail_pos;
429 self.in_tail_pos = false;
431 self.visit_stmt(stmt);
433 self.in_tail_pos = in_tail_pos;
434 self.visit_stmt(stmt);
439 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
440 if !self.can_use_entry {
444 match try_parse_insert(self.cx, expr) {
445 Some(insert_expr) if SpanlessEq::new(self.cx).eq_expr(self.map, insert_expr.map) => {
446 // Multiple inserts, inserts with a different key, and inserts from a macro can't use the entry api.
448 || !SpanlessEq::new(self.cx).eq_expr(self.key, insert_expr.key)
449 || expr.span.ctxt() != self.ctxt
451 self.can_use_entry = false;
455 self.edits.push(Edit::Insertion(Insertion {
457 value: insert_expr.value,
459 self.is_map_used = true;
460 self.allow_insert_closure &= self.in_tail_pos;
462 // The value doesn't affect whether there is only a single insert expression.
463 let is_single_insert = self.is_single_insert;
464 self.visit_non_tail_expr(insert_expr.value);
465 self.is_single_insert = is_single_insert;
467 _ if SpanlessEq::new(self.cx).eq_expr(self.map, expr) => {
468 self.is_map_used = true;
470 _ => match expr.kind {
471 ExprKind::If(cond_expr, then_expr, Some(else_expr)) => {
472 self.is_single_insert = false;
473 self.visit_non_tail_expr(cond_expr);
474 // Each branch may contain it's own insert expression.
475 let mut is_map_used = self.visit_cond_arm(then_expr);
476 is_map_used |= self.visit_cond_arm(else_expr);
477 self.is_map_used = is_map_used;
479 ExprKind::Match(scrutinee_expr, arms, _) => {
480 self.is_single_insert = false;
481 self.visit_non_tail_expr(scrutinee_expr);
482 // Each branch may contain it's own insert expression.
483 let mut is_map_used = self.is_map_used;
485 self.visit_pat(arm.pat);
486 if let Some(Guard::If(guard) | Guard::IfLet(_, guard)) = arm.guard {
487 self.visit_non_tail_expr(guard);
489 is_map_used |= self.visit_cond_arm(arm.body);
491 self.is_map_used = is_map_used;
493 ExprKind::Loop(block, ..) => {
494 self.loops.push(expr.hir_id);
495 self.is_single_insert = false;
496 self.allow_insert_closure &= !self.in_tail_pos;
497 // Don't allow insertions inside of a loop.
498 let edit_len = self.edits.len();
499 self.visit_block(block);
500 if self.edits.len() != edit_len {
501 self.can_use_entry = false;
505 ExprKind::Block(block, _) => self.visit_block(block),
506 ExprKind::InlineAsm(_) | ExprKind::LlvmInlineAsm(_) => {
507 self.can_use_entry = false;
510 self.allow_insert_closure &= !self.in_tail_pos;
511 self.allow_insert_closure &=
512 can_move_expr_to_closure_no_visit(self.cx, expr, &self.loops, &self.locals);
513 // Sub expressions are no longer in the tail position.
514 self.is_single_insert = false;
515 self.in_tail_pos = false;
516 walk_expr(self, expr);
522 fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
523 p.each_binding_or_first(&mut |_, id, _, _| {
524 self.locals.insert(id);
529 struct InsertSearchResults<'tcx> {
530 edits: Vec<Edit<'tcx>>,
531 allow_insert_closure: bool,
532 is_single_insert: bool,
534 impl InsertSearchResults<'tcx> {
535 fn as_single_insertion(&self) -> Option<Insertion<'tcx>> {
536 self.is_single_insert.then(|| self.edits[0].as_insertion().unwrap())
541 cx: &LateContext<'_>,
543 app: &mut Applicability,
544 write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability),
546 let ctxt = span.ctxt();
547 let mut res = String::new();
548 for insertion in self.edits.iter().filter_map(|e| e.as_insertion()) {
549 res.push_str(&snippet_with_applicability(
551 span.until(insertion.call.span),
555 if is_expr_used_or_unified(cx.tcx, insertion.call) {
556 write_wrapped(&mut res, insertion, ctxt, app);
561 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
564 span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
566 res.push_str(&snippet_with_applicability(cx, span, "..", app));
570 fn snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
572 self.snippet(cx, span, app, |res, insertion, ctxt, app| {
573 // Insertion into a map would return `Some(&mut value)`, but the entry returns `&mut value`
576 "Some(e.insert({}))",
577 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
584 fn snippet_vacant(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
586 self.snippet(cx, span, app, |res, insertion, ctxt, app| {
587 // Insertion into a map would return `None`, but the entry returns a mutable reference.
588 let _ = if is_expr_final_block_expr(cx.tcx, insertion.call) {
591 "e.insert({});\n{}None",
592 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
593 snippet_indent(cx, insertion.call.span).as_deref().unwrap_or(""),
598 "{{ e.insert({}); None }}",
599 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
607 fn snippet_closure(&self, cx: &LateContext<'_>, mut span: Span, app: &mut Applicability) -> String {
608 let ctxt = span.ctxt();
609 let mut res = String::new();
610 for edit in &self.edits {
612 Edit::Insertion(insertion) => {
613 // Cut out the value from `map.insert(key, value)`
614 res.push_str(&snippet_with_applicability(
616 span.until(insertion.call.span),
620 res.push_str(&snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0);
621 span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
623 Edit::RemoveSemi(semi_span) => {
624 // Cut out the semicolon. This allows the value to be returned from the closure.
625 res.push_str(&snippet_with_applicability(cx, span.until(semi_span), "..", app));
626 span = span.trim_start(semi_span).unwrap_or(DUMMY_SP);
630 res.push_str(&snippet_with_applicability(cx, span, "..", app));
635 fn find_insert_calls(
636 cx: &LateContext<'tcx>,
637 contains_expr: &ContainsExpr<'tcx>,
638 expr: &'tcx Expr<'_>,
639 ) -> Option<InsertSearchResults<'tcx>> {
640 let mut s = InsertSearcher {
642 map: contains_expr.map,
643 key: contains_expr.key,
644 ctxt: expr.span.ctxt(),
647 allow_insert_closure: true,
650 is_single_insert: true,
652 locals: HirIdSet::default(),
655 let allow_insert_closure = s.allow_insert_closure;
656 let is_single_insert = s.is_single_insert;
658 s.can_use_entry.then(|| InsertSearchResults {
660 allow_insert_closure,