]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/entry.rs
Rollup merge of #91630 - GuillaumeGomez:missing-whitespace, r=notriddle
[rust.git] / src / tools / clippy / clippy_lints / src / entry.rs
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     #[clippy::version = "pre 1.29.0"]
58     pub MAP_ENTRY,
59     perf,
60     "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
61 }
62
63 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
64
65 impl<'tcx> LateLintPass<'tcx> for HashMapPass {
66     #[allow(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),
70             _ => return,
71         };
72
73         let (map_ty, contains_expr) = match try_parse_contains(cx, cond_expr) {
74             Some(x) => x,
75             None => return,
76         };
77
78         let then_search = match find_insert_calls(cx, &contains_expr, then_expr) {
79             Some(x) => x,
80             None => return,
81         };
82
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,
89                 None => return,
90             };
91
92             if then_search.edits.is_empty() && else_search.edits.is_empty() {
93                 // No insertions
94                 return;
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) {
98                     (true, true) => (
99                         then_search.snippet_vacant(cx, then_expr.span, &mut app),
100                         snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
101                     ),
102                     (true, false) => (
103                         then_search.snippet_occupied(cx, then_expr.span, &mut app),
104                         snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
105                     ),
106                     (false, true) => (
107                         else_search.snippet_occupied(cx, else_expr.span, &mut app),
108                         snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
109                     ),
110                     (false, false) => (
111                         else_search.snippet_vacant(cx, else_expr.span, &mut app),
112                         snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
113                     ),
114                 };
115                 format!(
116                     "if let {}::{} = {}.entry({}) {} else {}",
117                     map_ty.entry_path(),
118                     entry_kind,
119                     map_str,
120                     key_str,
121                     then_str,
122                     else_str,
123                 )
124             } else {
125                 // if .. { insert } else { insert }
126                 let ((then_str, then_entry), (else_str, else_entry)) = if contains_expr.negated {
127                     (
128                         then_search.snippet_vacant(cx, then_expr.span, &mut app),
129                         else_search.snippet_occupied(cx, else_expr.span, &mut app),
130                     )
131                 } else {
132                     (
133                         then_search.snippet_occupied(cx, then_expr.span, &mut app),
134                         else_search.snippet_vacant(cx, else_expr.span, &mut app),
135                     )
136                 };
137                 let indent_str = snippet_indent(cx, expr.span);
138                 let indent_str = indent_str.as_deref().unwrap_or("");
139                 format!(
140                     "match {}.entry({}) {{\n{indent}    {entry}::{} => {}\n\
141                         {indent}    {entry}::{} => {}\n{indent}}}",
142                     map_str,
143                     key_str,
144                     then_entry,
145                     reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
146                     else_entry,
147                     reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
148                     entry = map_ty.entry_path(),
149                     indent = indent_str,
150                 )
151             }
152         } else {
153             if then_search.edits.is_empty() {
154                 // no insertions
155                 return;
156             }
157
158             // if .. { insert }
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)
162                 } else {
163                     then_search.snippet_occupied(cx, then_expr.span, &mut app)
164                 };
165                 format!(
166                     "if let {}::{} = {}.entry({}) {}",
167                     map_ty.entry_path(),
168                     entry_kind,
169                     map_str,
170                     key_str,
171                     body_str,
172                 )
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)
178                     } else {
179                         format!("{}.entry({}).or_insert({});", map_str, key_str, value_str)
180                     }
181                 } else {
182                     // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
183                     // This would need to be a different lint.
184                     return;
185                 }
186             } else {
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)
190                 } else {
191                     // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
192                     // This would need to be a different lint.
193                     return;
194                 }
195             }
196         };
197
198         span_lint_and_sugg(
199             cx,
200             MAP_ENTRY,
201             expr.span,
202             &format!("usage of `contains_key` followed by `insert` on a `{}`", map_ty.name()),
203             "try this",
204             sugg,
205             app,
206         );
207     }
208 }
209
210 #[derive(Clone, Copy)]
211 enum MapType {
212     Hash,
213     BTree,
214 }
215 impl MapType {
216     fn name(self) -> &'static str {
217         match self {
218             Self::Hash => "HashMap",
219             Self::BTree => "BTreeMap",
220         }
221     }
222     fn entry_path(self) -> &'static str {
223         match self {
224             Self::Hash => "std::collections::hash_map::Entry",
225             Self::BTree => "std::collections::btree_map::Entry",
226         }
227     }
228 }
229
230 struct ContainsExpr<'tcx> {
231     negated: bool,
232     map: &'tcx Expr<'tcx>,
233     key: &'tcx Expr<'tcx>,
234     call_ctxt: SyntaxContext,
235 }
236 fn try_parse_contains(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) => {
240             negated = !negated;
241             Some(e)
242         },
243         _ => None,
244     });
245     match expr.kind {
246         ExprKind::MethodCall(
247             _,
248             _,
249             [
250                 map,
251                 Expr {
252                     kind: ExprKind::AddrOf(_, _, key),
253                     span: key_span,
254                     ..
255                 },
256             ],
257             _,
258         ) if key_span.ctxt() == expr.span.ctxt() => {
259             let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
260             let expr = ContainsExpr {
261                 negated,
262                 map,
263                 key,
264                 call_ctxt: expr.span.ctxt(),
265             };
266             if match_def_path(cx, id, &paths::BTREEMAP_CONTAINS_KEY) {
267                 Some((MapType::BTree, expr))
268             } else if match_def_path(cx, id, &paths::HASHMAP_CONTAINS_KEY) {
269                 Some((MapType::Hash, expr))
270             } else {
271                 None
272             }
273         },
274         _ => None,
275     }
276 }
277
278 struct InsertExpr<'tcx> {
279     map: &'tcx Expr<'tcx>,
280     key: &'tcx Expr<'tcx>,
281     value: &'tcx Expr<'tcx>,
282 }
283 fn try_parse_insert(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<InsertExpr<'tcx>> {
284     if let ExprKind::MethodCall(_, _, [map, key, value], _) = expr.kind {
285         let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
286         if match_def_path(cx, id, &paths::BTREEMAP_INSERT) || match_def_path(cx, id, &paths::HASHMAP_INSERT) {
287             Some(InsertExpr { map, key, value })
288         } else {
289             None
290         }
291     } else {
292         None
293     }
294 }
295
296 /// An edit that will need to be made to move the expression to use the entry api
297 #[derive(Clone, Copy)]
298 enum Edit<'tcx> {
299     /// A semicolon that needs to be removed. Used to create a closure for `insert_with`.
300     RemoveSemi(Span),
301     /// An insertion into the map.
302     Insertion(Insertion<'tcx>),
303 }
304 impl Edit<'tcx> {
305     fn as_insertion(self) -> Option<Insertion<'tcx>> {
306         if let Self::Insertion(i) = self { Some(i) } else { None }
307     }
308 }
309 #[derive(Clone, Copy)]
310 struct Insertion<'tcx> {
311     call: &'tcx Expr<'tcx>,
312     value: &'tcx Expr<'tcx>,
313 }
314
315 /// This visitor needs to do a multiple things:
316 /// * Find all usages of the map. An insertion can only be made before any other usages of the map.
317 /// * Determine if there's an insertion using the same key. There's no need for the entry api
318 ///   otherwise.
319 /// * Determine if the final statement executed is an insertion. This is needed to use
320 ///   `or_insert_with`.
321 /// * Determine if there's any sub-expression that can't be placed in a closure.
322 /// * Determine if there's only a single insert statement. `or_insert` can be used in this case.
323 #[allow(clippy::struct_excessive_bools)]
324 struct InsertSearcher<'cx, 'tcx> {
325     cx: &'cx LateContext<'tcx>,
326     /// The map expression used in the contains call.
327     map: &'tcx Expr<'tcx>,
328     /// The key expression used in the contains call.
329     key: &'tcx Expr<'tcx>,
330     /// The context of the top level block. All insert calls must be in the same context.
331     ctxt: SyntaxContext,
332     /// Whether this expression can be safely moved into a closure.
333     allow_insert_closure: bool,
334     /// Whether this expression can use the entry api.
335     can_use_entry: bool,
336     /// Whether this expression is the final expression in this code path. This may be a statement.
337     in_tail_pos: bool,
338     // Is this expression a single insert. A slightly better suggestion can be made in this case.
339     is_single_insert: bool,
340     /// If the visitor has seen the map being used.
341     is_map_used: bool,
342     /// The locations where changes need to be made for the suggestion.
343     edits: Vec<Edit<'tcx>>,
344     /// A stack of loops the visitor is currently in.
345     loops: Vec<HirId>,
346     /// Local variables created in the expression. These don't need to be captured.
347     locals: HirIdSet,
348 }
349 impl<'tcx> InsertSearcher<'_, 'tcx> {
350     /// Visit the expression as a branch in control flow. Multiple insert calls can be used, but
351     /// only if they are on separate code paths. This will return whether the map was used in the
352     /// given expression.
353     fn visit_cond_arm(&mut self, e: &'tcx Expr<'_>) -> bool {
354         let is_map_used = self.is_map_used;
355         let in_tail_pos = self.in_tail_pos;
356         self.visit_expr(e);
357         let res = self.is_map_used;
358         self.is_map_used = is_map_used;
359         self.in_tail_pos = in_tail_pos;
360         res
361     }
362
363     /// Visits an expression which is not itself in a tail position, but other sibling expressions
364     /// may be. e.g. if conditions
365     fn visit_non_tail_expr(&mut self, e: &'tcx Expr<'_>) {
366         let in_tail_pos = self.in_tail_pos;
367         self.in_tail_pos = false;
368         self.visit_expr(e);
369         self.in_tail_pos = in_tail_pos;
370     }
371 }
372 impl<'tcx> Visitor<'tcx> for InsertSearcher<'_, 'tcx> {
373     type Map = ErasedMap<'tcx>;
374     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
375         NestedVisitorMap::None
376     }
377
378     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
379         match stmt.kind {
380             StmtKind::Semi(e) => {
381                 self.visit_expr(e);
382
383                 if self.in_tail_pos && self.allow_insert_closure {
384                     // The spans are used to slice the top level expression into multiple parts. This requires that
385                     // they all come from the same part of the source code.
386                     if stmt.span.ctxt() == self.ctxt && e.span.ctxt() == self.ctxt {
387                         self.edits
388                             .push(Edit::RemoveSemi(stmt.span.trim_start(e.span).unwrap_or(DUMMY_SP)));
389                     } else {
390                         self.allow_insert_closure = false;
391                     }
392                 }
393             },
394             StmtKind::Expr(e) => self.visit_expr(e),
395             StmtKind::Local(l) => {
396                 self.visit_pat(l.pat);
397                 if let Some(e) = l.init {
398                     self.allow_insert_closure &= !self.in_tail_pos;
399                     self.in_tail_pos = false;
400                     self.is_single_insert = false;
401                     self.visit_expr(e);
402                 }
403             },
404             StmtKind::Item(_) => {
405                 self.allow_insert_closure &= !self.in_tail_pos;
406                 self.is_single_insert = false;
407             },
408         }
409     }
410
411     fn visit_block(&mut self, block: &'tcx Block<'_>) {
412         // If the block is in a tail position, then the last expression (possibly a statement) is in the
413         // tail position. The rest, however, are not.
414         match (block.stmts, block.expr) {
415             ([], None) => {
416                 self.allow_insert_closure &= !self.in_tail_pos;
417             },
418             ([], Some(expr)) => self.visit_expr(expr),
419             (stmts, Some(expr)) => {
420                 let in_tail_pos = self.in_tail_pos;
421                 self.in_tail_pos = false;
422                 for stmt in stmts {
423                     self.visit_stmt(stmt);
424                 }
425                 self.in_tail_pos = in_tail_pos;
426                 self.visit_expr(expr);
427             },
428             ([stmts @ .., stmt], None) => {
429                 let in_tail_pos = self.in_tail_pos;
430                 self.in_tail_pos = false;
431                 for stmt in stmts {
432                     self.visit_stmt(stmt);
433                 }
434                 self.in_tail_pos = in_tail_pos;
435                 self.visit_stmt(stmt);
436             },
437         }
438     }
439
440     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
441         if !self.can_use_entry {
442             return;
443         }
444
445         match try_parse_insert(self.cx, expr) {
446             Some(insert_expr) if SpanlessEq::new(self.cx).eq_expr(self.map, insert_expr.map) => {
447                 // Multiple inserts, inserts with a different key, and inserts from a macro can't use the entry api.
448                 if self.is_map_used
449                     || !SpanlessEq::new(self.cx).eq_expr(self.key, insert_expr.key)
450                     || expr.span.ctxt() != self.ctxt
451                 {
452                     self.can_use_entry = false;
453                     return;
454                 }
455
456                 self.edits.push(Edit::Insertion(Insertion {
457                     call: expr,
458                     value: insert_expr.value,
459                 }));
460                 self.is_map_used = true;
461                 self.allow_insert_closure &= self.in_tail_pos;
462
463                 // The value doesn't affect whether there is only a single insert expression.
464                 let is_single_insert = self.is_single_insert;
465                 self.visit_non_tail_expr(insert_expr.value);
466                 self.is_single_insert = is_single_insert;
467             },
468             _ if SpanlessEq::new(self.cx).eq_expr(self.map, expr) => {
469                 self.is_map_used = true;
470             },
471             _ => match expr.kind {
472                 ExprKind::If(cond_expr, then_expr, Some(else_expr)) => {
473                     self.is_single_insert = false;
474                     self.visit_non_tail_expr(cond_expr);
475                     // Each branch may contain it's own insert expression.
476                     let mut is_map_used = self.visit_cond_arm(then_expr);
477                     is_map_used |= self.visit_cond_arm(else_expr);
478                     self.is_map_used = is_map_used;
479                 },
480                 ExprKind::Match(scrutinee_expr, arms, _) => {
481                     self.is_single_insert = false;
482                     self.visit_non_tail_expr(scrutinee_expr);
483                     // Each branch may contain it's own insert expression.
484                     let mut is_map_used = self.is_map_used;
485                     for arm in arms {
486                         self.visit_pat(arm.pat);
487                         if let Some(Guard::If(guard) | Guard::IfLet(_, guard)) = arm.guard {
488                             self.visit_non_tail_expr(guard);
489                         }
490                         is_map_used |= self.visit_cond_arm(arm.body);
491                     }
492                     self.is_map_used = is_map_used;
493                 },
494                 ExprKind::Loop(block, ..) => {
495                     self.loops.push(expr.hir_id);
496                     self.is_single_insert = false;
497                     self.allow_insert_closure &= !self.in_tail_pos;
498                     // Don't allow insertions inside of a loop.
499                     let edit_len = self.edits.len();
500                     self.visit_block(block);
501                     if self.edits.len() != edit_len {
502                         self.can_use_entry = false;
503                     }
504                     self.loops.pop();
505                 },
506                 ExprKind::Block(block, _) => self.visit_block(block),
507                 ExprKind::InlineAsm(_) | ExprKind::LlvmInlineAsm(_) => {
508                     self.can_use_entry = false;
509                 },
510                 _ => {
511                     self.allow_insert_closure &= !self.in_tail_pos;
512                     self.allow_insert_closure &=
513                         can_move_expr_to_closure_no_visit(self.cx, expr, &self.loops, &self.locals);
514                     // Sub expressions are no longer in the tail position.
515                     self.is_single_insert = false;
516                     self.in_tail_pos = false;
517                     walk_expr(self, expr);
518                 },
519             },
520         }
521     }
522
523     fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
524         p.each_binding_or_first(&mut |_, id, _, _| {
525             self.locals.insert(id);
526         });
527     }
528 }
529
530 struct InsertSearchResults<'tcx> {
531     edits: Vec<Edit<'tcx>>,
532     allow_insert_closure: bool,
533     is_single_insert: bool,
534 }
535 impl InsertSearchResults<'tcx> {
536     fn as_single_insertion(&self) -> Option<Insertion<'tcx>> {
537         self.is_single_insert.then(|| self.edits[0].as_insertion().unwrap())
538     }
539
540     fn snippet(
541         &self,
542         cx: &LateContext<'_>,
543         mut span: Span,
544         app: &mut Applicability,
545         write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability),
546     ) -> String {
547         let ctxt = span.ctxt();
548         let mut res = String::new();
549         for insertion in self.edits.iter().filter_map(|e| e.as_insertion()) {
550             res.push_str(&snippet_with_applicability(
551                 cx,
552                 span.until(insertion.call.span),
553                 "..",
554                 app,
555             ));
556             if is_expr_used_or_unified(cx.tcx, insertion.call) {
557                 write_wrapped(&mut res, insertion, ctxt, app);
558             } else {
559                 let _ = write!(
560                     res,
561                     "e.insert({})",
562                     snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
563                 );
564             }
565             span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
566         }
567         res.push_str(&snippet_with_applicability(cx, span, "..", app));
568         res
569     }
570
571     fn snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
572         (
573             self.snippet(cx, span, app, |res, insertion, ctxt, app| {
574                 // Insertion into a map would return `Some(&mut value)`, but the entry returns `&mut value`
575                 let _ = write!(
576                     res,
577                     "Some(e.insert({}))",
578                     snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
579                 );
580             }),
581             "Occupied(mut e)",
582         )
583     }
584
585     fn snippet_vacant(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
586         (
587             self.snippet(cx, span, app, |res, insertion, ctxt, app| {
588                 // Insertion into a map would return `None`, but the entry returns a mutable reference.
589                 let _ = if is_expr_final_block_expr(cx.tcx, insertion.call) {
590                     write!(
591                         res,
592                         "e.insert({});\n{}None",
593                         snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
594                         snippet_indent(cx, insertion.call.span).as_deref().unwrap_or(""),
595                     )
596                 } else {
597                     write!(
598                         res,
599                         "{{ e.insert({}); None }}",
600                         snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
601                     )
602                 };
603             }),
604             "Vacant(e)",
605         )
606     }
607
608     fn snippet_closure(&self, cx: &LateContext<'_>, mut span: Span, app: &mut Applicability) -> String {
609         let ctxt = span.ctxt();
610         let mut res = String::new();
611         for edit in &self.edits {
612             match *edit {
613                 Edit::Insertion(insertion) => {
614                     // Cut out the value from `map.insert(key, value)`
615                     res.push_str(&snippet_with_applicability(
616                         cx,
617                         span.until(insertion.call.span),
618                         "..",
619                         app,
620                     ));
621                     res.push_str(&snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0);
622                     span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
623                 },
624                 Edit::RemoveSemi(semi_span) => {
625                     // Cut out the semicolon. This allows the value to be returned from the closure.
626                     res.push_str(&snippet_with_applicability(cx, span.until(semi_span), "..", app));
627                     span = span.trim_start(semi_span).unwrap_or(DUMMY_SP);
628                 },
629             }
630         }
631         res.push_str(&snippet_with_applicability(cx, span, "..", app));
632         res
633     }
634 }
635
636 fn find_insert_calls(
637     cx: &LateContext<'tcx>,
638     contains_expr: &ContainsExpr<'tcx>,
639     expr: &'tcx Expr<'_>,
640 ) -> Option<InsertSearchResults<'tcx>> {
641     let mut s = InsertSearcher {
642         cx,
643         map: contains_expr.map,
644         key: contains_expr.key,
645         ctxt: expr.span.ctxt(),
646         edits: Vec::new(),
647         is_map_used: false,
648         allow_insert_closure: true,
649         can_use_entry: true,
650         in_tail_pos: true,
651         is_single_insert: true,
652         loops: Vec::new(),
653         locals: HirIdSet::default(),
654     };
655     s.visit_expr(expr);
656     let allow_insert_closure = s.allow_insert_closure;
657     let is_single_insert = s.is_single_insert;
658     let edits = s.edits;
659     s.can_use_entry.then(|| InsertSearchResults {
660         edits,
661         allow_insert_closure,
662         is_single_insert,
663     })
664 }