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;
12 intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
13 Block, Expr, ExprKind, Guard, HirId, Local, Stmt, StmtKind, UnOp,
15 use rustc_lint::{LateContext, LateLintPass};
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_span::{Span, SyntaxContext, DUMMY_SP};
19 declare_clippy_lint! {
21 /// Checks for uses of `contains_key` + `insert` on `HashMap`
24 /// ### Why is this bad?
25 /// Using `entry` is more efficient.
27 /// ### Known problems
28 /// The suggestion may have type inference errors in some cases. e.g.
30 /// let mut map = std::collections::HashMap::new();
31 /// let _ = if !map.contains_key(&0) {
40 /// # use std::collections::HashMap;
41 /// # let mut map = HashMap::new();
44 /// if !map.contains_key(&k) {
48 /// can both be rewritten as:
50 /// # use std::collections::HashMap;
51 /// # let mut map = HashMap::new();
54 /// map.entry(k).or_insert(v);
58 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
61 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
63 impl<'tcx> LateLintPass<'tcx> for HashMapPass {
64 #[allow(clippy::too_many_lines)]
65 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
66 let (cond_expr, then_expr, else_expr) = match higher::If::hir(expr) {
67 Some(higher::If { cond, then, r#else }) => (cond, then, r#else),
71 let (map_ty, contains_expr) = match try_parse_contains(cx, cond_expr) {
76 let then_search = match find_insert_calls(cx, &contains_expr, then_expr) {
81 let mut app = Applicability::MachineApplicable;
82 let map_str = snippet_with_context(cx, contains_expr.map.span, contains_expr.call_ctxt, "..", &mut app).0;
83 let key_str = snippet_with_context(cx, contains_expr.key.span, contains_expr.call_ctxt, "..", &mut app).0;
84 let sugg = if let Some(else_expr) = else_expr {
85 let else_search = match find_insert_calls(cx, &contains_expr, else_expr) {
86 Some(search) => search,
90 if then_search.edits.is_empty() && else_search.edits.is_empty() {
93 } else if then_search.edits.is_empty() || else_search.edits.is_empty() {
94 // if .. { insert } else { .. } or if .. { .. } else { insert }
95 let ((then_str, entry_kind), else_str) = match (else_search.edits.is_empty(), contains_expr.negated) {
97 then_search.snippet_vacant(cx, then_expr.span, &mut app),
98 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
101 then_search.snippet_occupied(cx, then_expr.span, &mut app),
102 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
105 else_search.snippet_occupied(cx, else_expr.span, &mut app),
106 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
109 else_search.snippet_vacant(cx, else_expr.span, &mut app),
110 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
114 "if let {}::{} = {}.entry({}) {} else {}",
123 // if .. { insert } else { insert }
124 let ((then_str, then_entry), (else_str, else_entry)) = if contains_expr.negated {
126 then_search.snippet_vacant(cx, then_expr.span, &mut app),
127 else_search.snippet_occupied(cx, else_expr.span, &mut app),
131 then_search.snippet_occupied(cx, then_expr.span, &mut app),
132 else_search.snippet_vacant(cx, else_expr.span, &mut app),
135 let indent_str = snippet_indent(cx, expr.span);
136 let indent_str = indent_str.as_deref().unwrap_or("");
138 "match {}.entry({}) {{\n{indent} {entry}::{} => {}\n\
139 {indent} {entry}::{} => {}\n{indent}}}",
143 reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
145 reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
146 entry = map_ty.entry_path(),
151 if then_search.edits.is_empty() {
157 if !then_search.allow_insert_closure {
158 let (body_str, entry_kind) = if contains_expr.negated {
159 then_search.snippet_vacant(cx, then_expr.span, &mut app)
161 then_search.snippet_occupied(cx, then_expr.span, &mut app)
164 "if let {}::{} = {}.entry({}) {}",
171 } else if let Some(insertion) = then_search.as_single_insertion() {
172 let value_str = snippet_with_context(cx, insertion.value.span, then_expr.span.ctxt(), "..", &mut app).0;
173 if contains_expr.negated {
174 if insertion.value.can_have_side_effects() {
175 format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, value_str)
177 format!("{}.entry({}).or_insert({});", map_str, key_str, value_str)
180 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
181 // This would need to be a different lint.
185 let block_str = then_search.snippet_closure(cx, then_expr.span, &mut app);
186 if contains_expr.negated {
187 format!("{}.entry({}).or_insert_with(|| {});", map_str, key_str, block_str)
189 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
190 // This would need to be a different lint.
200 &format!("usage of `contains_key` followed by `insert` on a `{}`", map_ty.name()),
208 #[derive(Clone, Copy)]
214 fn name(self) -> &'static str {
216 Self::Hash => "HashMap",
217 Self::BTree => "BTreeMap",
220 fn entry_path(self) -> &'static str {
222 Self::Hash => "std::collections::hash_map::Entry",
223 Self::BTree => "std::collections::btree_map::Entry",
228 struct ContainsExpr<'tcx> {
230 map: &'tcx Expr<'tcx>,
231 key: &'tcx Expr<'tcx>,
232 call_ctxt: SyntaxContext,
234 fn try_parse_contains(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> Option<(MapType, ContainsExpr<'tcx>)> {
235 let mut negated = false;
236 let expr = peel_hir_expr_while(expr, |e| match e.kind {
237 ExprKind::Unary(UnOp::Not, e) => {
244 ExprKind::MethodCall(
248 kind: ExprKind::AddrOf(_, _, key),
253 ) if key_span.ctxt() == expr.span.ctxt() => {
254 let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
255 let expr = ContainsExpr {
259 call_ctxt: expr.span.ctxt(),
261 if match_def_path(cx, id, &paths::BTREEMAP_CONTAINS_KEY) {
262 Some((MapType::BTree, expr))
263 } else if match_def_path(cx, id, &paths::HASHMAP_CONTAINS_KEY) {
264 Some((MapType::Hash, expr))
273 struct InsertExpr<'tcx> {
274 map: &'tcx Expr<'tcx>,
275 key: &'tcx Expr<'tcx>,
276 value: &'tcx Expr<'tcx>,
278 fn try_parse_insert(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<InsertExpr<'tcx>> {
279 if let ExprKind::MethodCall(_, _, [map, key, value], _) = expr.kind {
280 let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
281 if match_def_path(cx, id, &paths::BTREEMAP_INSERT) || match_def_path(cx, id, &paths::HASHMAP_INSERT) {
282 Some(InsertExpr { map, key, value })
291 /// An edit that will need to be made to move the expression to use the entry api
292 #[derive(Clone, Copy)]
294 /// A semicolon that needs to be removed. Used to create a closure for `insert_with`.
296 /// An insertion into the map.
297 Insertion(Insertion<'tcx>),
300 fn as_insertion(self) -> Option<Insertion<'tcx>> {
301 if let Self::Insertion(i) = self { Some(i) } else { None }
304 #[derive(Clone, Copy)]
305 struct Insertion<'tcx> {
306 call: &'tcx Expr<'tcx>,
307 value: &'tcx Expr<'tcx>,
310 /// This visitor needs to do a multiple things:
311 /// * Find all usages of the map. An insertion can only be made before any other usages of the map.
312 /// * Determine if there's an insertion using the same key. There's no need for the entry api
314 /// * Determine if the final statement executed is an insertion. This is needed to use
315 /// `or_insert_with`.
316 /// * Determine if there's any sub-expression that can't be placed in a closure.
317 /// * Determine if there's only a single insert statement. `or_insert` can be used in this case.
318 #[allow(clippy::struct_excessive_bools)]
319 struct InsertSearcher<'cx, 'tcx> {
320 cx: &'cx LateContext<'tcx>,
321 /// The map expression used in the contains call.
322 map: &'tcx Expr<'tcx>,
323 /// The key expression used in the contains call.
324 key: &'tcx Expr<'tcx>,
325 /// The context of the top level block. All insert calls must be in the same context.
327 /// Whether this expression can be safely moved into a closure.
328 allow_insert_closure: bool,
329 /// Whether this expression can use the entry api.
331 /// Whether this expression is the final expression in this code path. This may be a statement.
333 // Is this expression a single insert. A slightly better suggestion can be made in this case.
334 is_single_insert: bool,
335 /// If the visitor has seen the map being used.
337 /// The locations where changes need to be made for the suggestion.
338 edits: Vec<Edit<'tcx>>,
339 /// A stack of loops the visitor is currently in.
342 impl<'tcx> InsertSearcher<'_, 'tcx> {
343 /// Visit the expression as a branch in control flow. Multiple insert calls can be used, but
344 /// only if they are on separate code paths. This will return whether the map was used in the
345 /// given expression.
346 fn visit_cond_arm(&mut self, e: &'tcx Expr<'_>) -> bool {
347 let is_map_used = self.is_map_used;
348 let in_tail_pos = self.in_tail_pos;
350 let res = self.is_map_used;
351 self.is_map_used = is_map_used;
352 self.in_tail_pos = in_tail_pos;
356 /// Visits an expression which is not itself in a tail position, but other sibling expressions
357 /// may be. e.g. if conditions
358 fn visit_non_tail_expr(&mut self, e: &'tcx Expr<'_>) {
359 let in_tail_pos = self.in_tail_pos;
360 self.in_tail_pos = false;
362 self.in_tail_pos = in_tail_pos;
365 impl<'tcx> Visitor<'tcx> for InsertSearcher<'_, 'tcx> {
366 type Map = ErasedMap<'tcx>;
367 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
368 NestedVisitorMap::None
371 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
373 StmtKind::Semi(e) => {
376 if self.in_tail_pos && self.allow_insert_closure {
377 // The spans are used to slice the top level expression into multiple parts. This requires that
378 // they all come from the same part of the source code.
379 if stmt.span.ctxt() == self.ctxt && e.span.ctxt() == self.ctxt {
381 .push(Edit::RemoveSemi(stmt.span.trim_start(e.span).unwrap_or(DUMMY_SP)));
383 self.allow_insert_closure = false;
387 StmtKind::Expr(e) => self.visit_expr(e),
388 StmtKind::Local(Local { init: Some(e), .. }) => {
389 self.allow_insert_closure &= !self.in_tail_pos;
390 self.in_tail_pos = false;
391 self.is_single_insert = false;
395 self.allow_insert_closure &= !self.in_tail_pos;
396 self.is_single_insert = false;
401 fn visit_block(&mut self, block: &'tcx Block<'_>) {
402 // If the block is in a tail position, then the last expression (possibly a statement) is in the
403 // tail position. The rest, however, are not.
404 match (block.stmts, block.expr) {
406 self.allow_insert_closure &= !self.in_tail_pos;
408 ([], Some(expr)) => self.visit_expr(expr),
409 (stmts, Some(expr)) => {
410 let in_tail_pos = self.in_tail_pos;
411 self.in_tail_pos = false;
413 self.visit_stmt(stmt);
415 self.in_tail_pos = in_tail_pos;
416 self.visit_expr(expr);
418 ([stmts @ .., stmt], None) => {
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_stmt(stmt);
430 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
431 if !self.can_use_entry {
435 match try_parse_insert(self.cx, expr) {
436 Some(insert_expr) if SpanlessEq::new(self.cx).eq_expr(self.map, insert_expr.map) => {
437 // Multiple inserts, inserts with a different key, and inserts from a macro can't use the entry api.
439 || !SpanlessEq::new(self.cx).eq_expr(self.key, insert_expr.key)
440 || expr.span.ctxt() != self.ctxt
442 self.can_use_entry = false;
446 self.edits.push(Edit::Insertion(Insertion {
448 value: insert_expr.value,
450 self.is_map_used = true;
451 self.allow_insert_closure &= self.in_tail_pos;
453 // The value doesn't affect whether there is only a single insert expression.
454 let is_single_insert = self.is_single_insert;
455 self.visit_non_tail_expr(insert_expr.value);
456 self.is_single_insert = is_single_insert;
458 _ if SpanlessEq::new(self.cx).eq_expr(self.map, expr) => {
459 self.is_map_used = true;
461 _ => match expr.kind {
462 ExprKind::If(cond_expr, then_expr, Some(else_expr)) => {
463 self.is_single_insert = false;
464 self.visit_non_tail_expr(cond_expr);
465 // Each branch may contain it's own insert expression.
466 let mut is_map_used = self.visit_cond_arm(then_expr);
467 is_map_used |= self.visit_cond_arm(else_expr);
468 self.is_map_used = is_map_used;
470 ExprKind::Match(scrutinee_expr, arms, _) => {
471 self.is_single_insert = false;
472 self.visit_non_tail_expr(scrutinee_expr);
473 // Each branch may contain it's own insert expression.
474 let mut is_map_used = self.is_map_used;
476 if let Some(Guard::If(guard) | Guard::IfLet(_, guard)) = arm.guard {
477 self.visit_non_tail_expr(guard);
479 is_map_used |= self.visit_cond_arm(arm.body);
481 self.is_map_used = is_map_used;
483 ExprKind::Loop(block, ..) => {
484 self.loops.push(expr.hir_id);
485 self.is_single_insert = false;
486 self.allow_insert_closure &= !self.in_tail_pos;
487 // Don't allow insertions inside of a loop.
488 let edit_len = self.edits.len();
489 self.visit_block(block);
490 if self.edits.len() != edit_len {
491 self.can_use_entry = false;
495 ExprKind::Block(block, _) => self.visit_block(block),
496 ExprKind::InlineAsm(_) | ExprKind::LlvmInlineAsm(_) => {
497 self.can_use_entry = false;
500 self.allow_insert_closure &= !self.in_tail_pos;
501 self.allow_insert_closure &= can_move_expr_to_closure_no_visit(self.cx, expr, &self.loops);
502 // Sub expressions are no longer in the tail position.
503 self.is_single_insert = false;
504 self.in_tail_pos = false;
505 walk_expr(self, expr);
512 struct InsertSearchResults<'tcx> {
513 edits: Vec<Edit<'tcx>>,
514 allow_insert_closure: bool,
515 is_single_insert: bool,
517 impl InsertSearchResults<'tcx> {
518 fn as_single_insertion(&self) -> Option<Insertion<'tcx>> {
519 self.is_single_insert.then(|| self.edits[0].as_insertion().unwrap())
524 cx: &LateContext<'_>,
526 app: &mut Applicability,
527 write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability),
529 let ctxt = span.ctxt();
530 let mut res = String::new();
531 for insertion in self.edits.iter().filter_map(|e| e.as_insertion()) {
532 res.push_str(&snippet_with_applicability(
534 span.until(insertion.call.span),
538 if is_expr_used_or_unified(cx.tcx, insertion.call) {
539 write_wrapped(&mut res, insertion, ctxt, app);
544 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
547 span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
549 res.push_str(&snippet_with_applicability(cx, span, "..", app));
553 fn snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
555 self.snippet(cx, span, app, |res, insertion, ctxt, app| {
556 // Insertion into a map would return `Some(&mut value)`, but the entry returns `&mut value`
559 "Some(e.insert({}))",
560 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
567 fn snippet_vacant(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
569 self.snippet(cx, span, app, |res, insertion, ctxt, app| {
570 // Insertion into a map would return `None`, but the entry returns a mutable reference.
571 let _ = if is_expr_final_block_expr(cx.tcx, insertion.call) {
574 "e.insert({});\n{}None",
575 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
576 snippet_indent(cx, insertion.call.span).as_deref().unwrap_or(""),
581 "{{ e.insert({}); None }}",
582 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
590 fn snippet_closure(&self, cx: &LateContext<'_>, mut span: Span, app: &mut Applicability) -> String {
591 let ctxt = span.ctxt();
592 let mut res = String::new();
593 for edit in &self.edits {
595 Edit::Insertion(insertion) => {
596 // Cut out the value from `map.insert(key, value)`
597 res.push_str(&snippet_with_applicability(
599 span.until(insertion.call.span),
603 res.push_str(&snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0);
604 span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
606 Edit::RemoveSemi(semi_span) => {
607 // Cut out the semicolon. This allows the value to be returned from the closure.
608 res.push_str(&snippet_with_applicability(cx, span.until(semi_span), "..", app));
609 span = span.trim_start(semi_span).unwrap_or(DUMMY_SP);
613 res.push_str(&snippet_with_applicability(cx, span, "..", app));
618 fn find_insert_calls(
619 cx: &LateContext<'tcx>,
620 contains_expr: &ContainsExpr<'tcx>,
621 expr: &'tcx Expr<'_>,
622 ) -> Option<InsertSearchResults<'tcx>> {
623 let mut s = InsertSearcher {
625 map: contains_expr.map,
626 key: contains_expr.key,
627 ctxt: expr.span.ctxt(),
630 allow_insert_closure: true,
633 is_single_insert: true,
637 let allow_insert_closure = s.allow_insert_closure;
638 let is_single_insert = s.is_single_insert;
640 s.can_use_entry.then(|| InsertSearchResults {
642 allow_insert_closure,