1 use clippy_utils::higher;
2 use clippy_utils::{
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},
7 SpanlessEq,
8 };
9 use core::fmt::Write;
10 use rustc_errors::Applicability;
11 use rustc_hir::{
12 hir_id::HirIdSet,
13 intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
14 Block, Expr, ExprKind, Guard, HirId, Pat, Stmt, StmtKind, UnOp,
15 };
16 use rustc_lint::{LateContext, LateLintPass};
17 use rustc_session::{declare_lint_pass, declare_tool_lint};
18 use rustc_span::{Span, SyntaxContext, DUMMY_SP};
19
20 declare_clippy_lint! {
21 /// ### What it does
22 /// Checks for uses of `contains_key` + `insert` on `HashMap`
23 /// or `BTreeMap`.
24 ///
25 /// ### Why is this bad?
26 /// Using `entry` is more efficient.
27 ///
28 /// ### Known problems
29 /// The suggestion may have type inference errors in some cases. e.g.
30 /// ```rust
31 /// let mut map = std::collections::HashMap::new();
32 /// let _ = if !map.contains_key(&0) {
33 /// map.insert(0, 0)
34 /// } else {
35 /// None
36 /// };
37 /// ```
38 ///
39 /// ### Example
40 /// ```rust
41 /// # use std::collections::HashMap;
42 /// # let mut map = HashMap::new();
43 /// # let k = 1;
44 /// # let v = 1;
45 /// if !map.contains_key(&k) {
46 /// map.insert(k, v);
47 /// }
48 /// ```
49 /// can both be rewritten as:
50 /// ```rust
51 /// # use std::collections::HashMap;
52 /// # let mut map = HashMap::new();
53 /// # let k = 1;
54 /// # let v = 1;
55 /// map.entry(k).or_insert(v);
56 /// ```
57 pub MAP_ENTRY,
58 perf,
59 "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
60 }
61
62 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
63
64 impl<'tcx> LateLintPass<'tcx> for HashMapPass {
65 #[allow(clippy::too_many_lines)]
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)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),
69 _ => return,
70 };
71
72 let (map_ty, contains_expr) = match try_parse_contains(cx, cond_expr) {
73 Some(x) => x,
74 None => return,
75 };
76
77 let then_search = match find_insert_calls(cx, &contains_expr, then_expr) {
78 Some(x) => x,
79 None => return,
80 };
81
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,
88 None => return,
89 };
90
91 if then_search.edits.is_empty() && else_search.edits.is_empty() {
92 // No insertions
93 return;
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) {
97 (true, true) => (
98 then_search.snippet_vacant(cx, then_expr.span, &mut app),
99 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
100 ),
101 (true, false) => (
102 then_search.snippet_occupied(cx, then_expr.span, &mut app),
103 snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
104 ),
105 (false, true) => (
106 else_search.snippet_occupied(cx, else_expr.span, &mut app),
107 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
108 ),
109 (false, false) => (
110 else_search.snippet_vacant(cx, else_expr.span, &mut app),
111 snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
112 ),
113 };
114 format!(
115 "if let {}::{} = {}.entry({}) {} else {}",
116 map_ty.entry_path(),
117 entry_kind,
118 map_str,
119 key_str,
120 then_str,
121 else_str,
122 )
123 } else {
124 // if .. { insert } else { insert }
125 let ((then_str, then_entry), (else_str, else_entry)) = if contains_expr.negated {
126 (
127 then_search.snippet_vacant(cx, then_expr.span, &mut app),
128 else_search.snippet_occupied(cx, else_expr.span, &mut app),
129 )
130 } else {
131 (
132 then_search.snippet_occupied(cx, then_expr.span, &mut app),
133 else_search.snippet_vacant(cx, else_expr.span, &mut app),
134 )
135 };
136 let indent_str = snippet_indent(cx, expr.span);
137 let indent_str = indent_str.as_deref().unwrap_or("");
138 format!(
139 "match {}.entry({}) {{\n{indent} {entry}::{} => {}\n\
140 {indent} {entry}::{} => {}\n{indent}}}",
141 map_str,
142 key_str,
143 then_entry,
144 reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
145 else_entry,
146 reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
147 entry = map_ty.entry_path(),
148 indent = indent_str,
149 )
150 }
151 } else {
152 if then_search.edits.is_empty() {
153 // no insertions
154 return;
155 }
156
157 // if .. { insert }
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)
161 } else {
162 then_search.snippet_occupied(cx, then_expr.span, &mut app)
163 };
164 format!(
165 "if let {}::{} = {}.entry({}) {}",
166 map_ty.entry_path(),
167 entry_kind,
168 map_str,
169 key_str,
170 body_str,
171 )
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)
177 } else {
178 format!("{}.entry({}).or_insert({});", map_str, key_str, value_str)
179 }
180 } else {
181 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
182 // This would need to be a different lint.
183 return;
184 }
185 } else {
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)
189 } else {
190 // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
191 // This would need to be a different lint.
192 return;
193 }
194 }
195 };
196
197 span_lint_and_sugg(
198 cx,
199 MAP_ENTRY,
200 expr.span,
201 &format!("usage of `contains_key` followed by `insert` on a `{}`", map_ty.name()),
202 "try this",
203 sugg,
204 app,
205 );
206 }
207 }
208
209 #[derive(Clone, Copy)]
210 enum MapType {
211 Hash,
212 BTree,
213 }
214 impl MapType {
name(self) -> &'static str215 fn name(self) -> &'static str {
216 match self {
217 Self::Hash => "HashMap",
218 Self::BTree => "BTreeMap",
219 }
220 }
entry_path(self) -> &'static str221 fn entry_path(self) -> &'static str {
222 match self {
223 Self::Hash => "std::collections::hash_map::Entry",
224 Self::BTree => "std::collections::btree_map::Entry",
225 }
226 }
227 }
228
229 struct ContainsExpr<'tcx> {
230 negated: bool,
231 map: &'tcx Expr<'tcx>,
232 key: &'tcx Expr<'tcx>,
233 call_ctxt: SyntaxContext,
234 }
try_parse_contains(cx: &LateContext<'_>, expr: &'tcx Expr<'_>) -> Option<(MapType, ContainsExpr<'tcx>)>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) => {
239 negated = !negated;
240 Some(e)
241 },
242 _ => None,
243 });
244 match expr.kind {
245 ExprKind::MethodCall(
246 _,
247 _,
248 [
249 map,
250 Expr {
251 kind: ExprKind::AddrOf(_, _, key),
252 span: key_span,
253 ..
254 },
255 ],
256 _,
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 {
260 negated,
261 map,
262 key,
263 call_ctxt: expr.span.ctxt(),
264 };
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))
269 } else {
270 None
271 }
272 },
273 _ => None,
274 }
275 }
276
277 struct InsertExpr<'tcx> {
278 map: &'tcx Expr<'tcx>,
279 key: &'tcx Expr<'tcx>,
280 value: &'tcx Expr<'tcx>,
281 }
try_parse_insert(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<InsertExpr<'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 })
287 } else {
288 None
289 }
290 } else {
291 None
292 }
293 }
294
295 /// An edit that will need to be made to move the expression to use the entry api
296 #[derive(Clone, Copy)]
297 enum Edit<'tcx> {
298 /// A semicolon that needs to be removed. Used to create a closure for `insert_with`.
299 RemoveSemi(Span),
300 /// An insertion into the map.
301 Insertion(Insertion<'tcx>),
302 }
303 impl Edit<'tcx> {
as_insertion(self) -> Option<Insertion<'tcx>>304 fn as_insertion(self) -> Option<Insertion<'tcx>> {
305 if let Self::Insertion(i) = self { Some(i) } else { None }
306 }
307 }
308 #[derive(Clone, Copy)]
309 struct Insertion<'tcx> {
310 call: &'tcx Expr<'tcx>,
311 value: &'tcx Expr<'tcx>,
312 }
313
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
317 /// otherwise.
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.
330 ctxt: SyntaxContext,
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.
334 can_use_entry: bool,
335 /// Whether this expression is the final expression in this code path. This may be a statement.
336 in_tail_pos: bool,
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.
340 is_map_used: bool,
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.
344 loops: Vec<HirId>,
345 /// Local variables created in the expression. These don't need to be captured.
346 locals: HirIdSet,
347 }
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.
visit_cond_arm(&mut self, e: &'tcx Expr<'_>) -> bool352 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;
355 self.visit_expr(e);
356 let res = self.is_map_used;
357 self.is_map_used = is_map_used;
358 self.in_tail_pos = in_tail_pos;
359 res
360 }
361
362 /// Visits an expression which is not itself in a tail position, but other sibling expressions
363 /// may be. e.g. if conditions
visit_non_tail_expr(&mut self, e: &'tcx Expr<'_>)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;
367 self.visit_expr(e);
368 self.in_tail_pos = in_tail_pos;
369 }
370 }
371 impl<'tcx> Visitor<'tcx> for InsertSearcher<'_, 'tcx> {
372 type Map = ErasedMap<'tcx>;
nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map>373 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
374 NestedVisitorMap::None
375 }
376
visit_stmt(&mut self, stmt: &'tcx Stmt<'_>)377 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
378 match stmt.kind {
379 StmtKind::Semi(e) => {
380 self.visit_expr(e);
381
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 {
386 self.edits
387 .push(Edit::RemoveSemi(stmt.span.trim_start(e.span).unwrap_or(DUMMY_SP)));
388 } else {
389 self.allow_insert_closure = false;
390 }
391 }
392 },
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;
400 self.visit_expr(e);
401 }
402 },
403 StmtKind::Item(_) => {
404 self.allow_insert_closure &= !self.in_tail_pos;
405 self.is_single_insert = false;
406 },
407 }
408 }
409
visit_block(&mut self, block: &'tcx Block<'_>)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) {
414 ([], None) => {
415 self.allow_insert_closure &= !self.in_tail_pos;
416 },
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;
421 for stmt in stmts {
422 self.visit_stmt(stmt);
423 }
424 self.in_tail_pos = in_tail_pos;
425 self.visit_expr(expr);
426 },
427 ([stmts @ .., stmt], None) => {
428 let in_tail_pos = self.in_tail_pos;
429 self.in_tail_pos = false;
430 for stmt in stmts {
431 self.visit_stmt(stmt);
432 }
433 self.in_tail_pos = in_tail_pos;
434 self.visit_stmt(stmt);
435 },
436 }
437 }
438
visit_expr(&mut self, expr: &'tcx Expr<'_>)439 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
440 if !self.can_use_entry {
441 return;
442 }
443
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.
447 if self.is_map_used
448 || !SpanlessEq::new(self.cx).eq_expr(self.key, insert_expr.key)
449 || expr.span.ctxt() != self.ctxt
450 {
451 self.can_use_entry = false;
452 return;
453 }
454
455 self.edits.push(Edit::Insertion(Insertion {
456 call: expr,
457 value: insert_expr.value,
458 }));
459 self.is_map_used = true;
460 self.allow_insert_closure &= self.in_tail_pos;
461
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;
466 },
467 _ if SpanlessEq::new(self.cx).eq_expr(self.map, expr) => {
468 self.is_map_used = true;
469 },
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;
478 },
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;
484 for arm in arms {
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);
488 }
489 is_map_used |= self.visit_cond_arm(arm.body);
490 }
491 self.is_map_used = is_map_used;
492 },
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;
502 }
503 self.loops.pop();
504 },
505 ExprKind::Block(block, _) => self.visit_block(block),
506 ExprKind::InlineAsm(_) | ExprKind::LlvmInlineAsm(_) => {
507 self.can_use_entry = false;
508 },
509 _ => {
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);
517 },
518 },
519 }
520 }
521
visit_pat(&mut self, p: &'tcx Pat<'tcx>)522 fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
523 p.each_binding_or_first(&mut |_, id, _, _| {
524 self.locals.insert(id);
525 });
526 }
527 }
528
529 struct InsertSearchResults<'tcx> {
530 edits: Vec<Edit<'tcx>>,
531 allow_insert_closure: bool,
532 is_single_insert: bool,
533 }
534 impl InsertSearchResults<'tcx> {
as_single_insertion(&self) -> Option<Insertion<'tcx>>535 fn as_single_insertion(&self) -> Option<Insertion<'tcx>> {
536 self.is_single_insert.then(|| self.edits[0].as_insertion().unwrap())
537 }
538
snippet( &self, cx: &LateContext<'_>, mut span: Span, app: &mut Applicability, write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability), ) -> String539 fn snippet(
540 &self,
541 cx: &LateContext<'_>,
542 mut span: Span,
543 app: &mut Applicability,
544 write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability),
545 ) -> String {
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(
550 cx,
551 span.until(insertion.call.span),
552 "..",
553 app,
554 ));
555 if is_expr_used_or_unified(cx.tcx, insertion.call) {
556 write_wrapped(&mut res, insertion, ctxt, app);
557 } else {
558 let _ = write!(
559 res,
560 "e.insert({})",
561 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
562 );
563 }
564 span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
565 }
566 res.push_str(&snippet_with_applicability(cx, span, "..", app));
567 res
568 }
569
snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str)570 fn snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
571 (
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`
574 let _ = write!(
575 res,
576 "Some(e.insert({}))",
577 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
578 );
579 }),
580 "Occupied(mut e)",
581 )
582 }
583
snippet_vacant(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str)584 fn snippet_vacant(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
585 (
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) {
589 write!(
590 res,
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(""),
594 )
595 } else {
596 write!(
597 res,
598 "{{ e.insert({}); None }}",
599 snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
600 )
601 };
602 }),
603 "Vacant(e)",
604 )
605 }
606
snippet_closure(&self, cx: &LateContext<'_>, mut span: Span, app: &mut Applicability) -> String607 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 {
611 match *edit {
612 Edit::Insertion(insertion) => {
613 // Cut out the value from `map.insert(key, value)`
614 res.push_str(&snippet_with_applicability(
615 cx,
616 span.until(insertion.call.span),
617 "..",
618 app,
619 ));
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);
622 },
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);
627 },
628 }
629 }
630 res.push_str(&snippet_with_applicability(cx, span, "..", app));
631 res
632 }
633 }
634
find_insert_calls( cx: &LateContext<'tcx>, contains_expr: &ContainsExpr<'tcx>, expr: &'tcx Expr<'_>, ) -> Option<InsertSearchResults<'tcx>>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 {
641 cx,
642 map: contains_expr.map,
643 key: contains_expr.key,
644 ctxt: expr.span.ctxt(),
645 edits: Vec::new(),
646 is_map_used: false,
647 allow_insert_closure: true,
648 can_use_entry: true,
649 in_tail_pos: true,
650 is_single_insert: true,
651 loops: Vec::new(),
652 locals: HirIdSet::default(),
653 };
654 s.visit_expr(expr);
655 let allow_insert_closure = s.allow_insert_closure;
656 let is_single_insert = s.is_single_insert;
657 let edits = s.edits;
658 s.can_use_entry.then(|| InsertSearchResults {
659 edits,
660 allow_insert_closure,
661 is_single_insert,
662 })
663 }
664