]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/entry.rs
Rollup merge of #89789 - jkugelman:must-use-thread-builder, r=joshtriplett
[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     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)]
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 {
215     fn name(self) -> &'static str {
216         match self {
217             Self::Hash => "HashMap",
218             Self::BTree => "BTreeMap",
219         }
220     }
221     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 }
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             [map, Expr {
249                 kind: ExprKind::AddrOf(_, _, key),
250                 span: key_span,
251                 ..
252             }],
253             _,
254         ) if key_span.ctxt() == expr.span.ctxt() => {
255             let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
256             let expr = ContainsExpr {
257                 negated,
258                 map,
259                 key,
260                 call_ctxt: expr.span.ctxt(),
261             };
262             if match_def_path(cx, id, &paths::BTREEMAP_CONTAINS_KEY) {
263                 Some((MapType::BTree, expr))
264             } else if match_def_path(cx, id, &paths::HASHMAP_CONTAINS_KEY) {
265                 Some((MapType::Hash, expr))
266             } else {
267                 None
268             }
269         },
270         _ => None,
271     }
272 }
273
274 struct InsertExpr<'tcx> {
275     map: &'tcx Expr<'tcx>,
276     key: &'tcx Expr<'tcx>,
277     value: &'tcx Expr<'tcx>,
278 }
279 fn try_parse_insert(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<InsertExpr<'tcx>> {
280     if let ExprKind::MethodCall(_, _, [map, key, value], _) = expr.kind {
281         let id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
282         if match_def_path(cx, id, &paths::BTREEMAP_INSERT) || match_def_path(cx, id, &paths::HASHMAP_INSERT) {
283             Some(InsertExpr { map, key, value })
284         } else {
285             None
286         }
287     } else {
288         None
289     }
290 }
291
292 /// An edit that will need to be made to move the expression to use the entry api
293 #[derive(Clone, Copy)]
294 enum Edit<'tcx> {
295     /// A semicolon that needs to be removed. Used to create a closure for `insert_with`.
296     RemoveSemi(Span),
297     /// An insertion into the map.
298     Insertion(Insertion<'tcx>),
299 }
300 impl Edit<'tcx> {
301     fn as_insertion(self) -> Option<Insertion<'tcx>> {
302         if let Self::Insertion(i) = self { Some(i) } else { None }
303     }
304 }
305 #[derive(Clone, Copy)]
306 struct Insertion<'tcx> {
307     call: &'tcx Expr<'tcx>,
308     value: &'tcx Expr<'tcx>,
309 }
310
311 /// This visitor needs to do a multiple things:
312 /// * Find all usages of the map. An insertion can only be made before any other usages of the map.
313 /// * Determine if there's an insertion using the same key. There's no need for the entry api
314 ///   otherwise.
315 /// * Determine if the final statement executed is an insertion. This is needed to use
316 ///   `or_insert_with`.
317 /// * Determine if there's any sub-expression that can't be placed in a closure.
318 /// * Determine if there's only a single insert statement. `or_insert` can be used in this case.
319 #[allow(clippy::struct_excessive_bools)]
320 struct InsertSearcher<'cx, 'tcx> {
321     cx: &'cx LateContext<'tcx>,
322     /// The map expression used in the contains call.
323     map: &'tcx Expr<'tcx>,
324     /// The key expression used in the contains call.
325     key: &'tcx Expr<'tcx>,
326     /// The context of the top level block. All insert calls must be in the same context.
327     ctxt: SyntaxContext,
328     /// Whether this expression can be safely moved into a closure.
329     allow_insert_closure: bool,
330     /// Whether this expression can use the entry api.
331     can_use_entry: bool,
332     /// Whether this expression is the final expression in this code path. This may be a statement.
333     in_tail_pos: bool,
334     // Is this expression a single insert. A slightly better suggestion can be made in this case.
335     is_single_insert: bool,
336     /// If the visitor has seen the map being used.
337     is_map_used: bool,
338     /// The locations where changes need to be made for the suggestion.
339     edits: Vec<Edit<'tcx>>,
340     /// A stack of loops the visitor is currently in.
341     loops: Vec<HirId>,
342     /// Local variables created in the expression. These don't need to be captured.
343     locals: HirIdSet,
344 }
345 impl<'tcx> InsertSearcher<'_, 'tcx> {
346     /// Visit the expression as a branch in control flow. Multiple insert calls can be used, but
347     /// only if they are on separate code paths. This will return whether the map was used in the
348     /// given expression.
349     fn visit_cond_arm(&mut self, e: &'tcx Expr<'_>) -> bool {
350         let is_map_used = self.is_map_used;
351         let in_tail_pos = self.in_tail_pos;
352         self.visit_expr(e);
353         let res = self.is_map_used;
354         self.is_map_used = is_map_used;
355         self.in_tail_pos = in_tail_pos;
356         res
357     }
358
359     /// Visits an expression which is not itself in a tail position, but other sibling expressions
360     /// may be. e.g. if conditions
361     fn visit_non_tail_expr(&mut self, e: &'tcx Expr<'_>) {
362         let in_tail_pos = self.in_tail_pos;
363         self.in_tail_pos = false;
364         self.visit_expr(e);
365         self.in_tail_pos = in_tail_pos;
366     }
367 }
368 impl<'tcx> Visitor<'tcx> for InsertSearcher<'_, 'tcx> {
369     type Map = ErasedMap<'tcx>;
370     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
371         NestedVisitorMap::None
372     }
373
374     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
375         match stmt.kind {
376             StmtKind::Semi(e) => {
377                 self.visit_expr(e);
378
379                 if self.in_tail_pos && self.allow_insert_closure {
380                     // The spans are used to slice the top level expression into multiple parts. This requires that
381                     // they all come from the same part of the source code.
382                     if stmt.span.ctxt() == self.ctxt && e.span.ctxt() == self.ctxt {
383                         self.edits
384                             .push(Edit::RemoveSemi(stmt.span.trim_start(e.span).unwrap_or(DUMMY_SP)));
385                     } else {
386                         self.allow_insert_closure = false;
387                     }
388                 }
389             },
390             StmtKind::Expr(e) => self.visit_expr(e),
391             StmtKind::Local(l) => {
392                 self.visit_pat(l.pat);
393                 if let Some(e) = l.init {
394                     self.allow_insert_closure &= !self.in_tail_pos;
395                     self.in_tail_pos = false;
396                     self.is_single_insert = false;
397                     self.visit_expr(e);
398                 }
399             },
400             StmtKind::Item(_) => {
401                 self.allow_insert_closure &= !self.in_tail_pos;
402                 self.is_single_insert = false;
403             },
404         }
405     }
406
407     fn visit_block(&mut self, block: &'tcx Block<'_>) {
408         // If the block is in a tail position, then the last expression (possibly a statement) is in the
409         // tail position. The rest, however, are not.
410         match (block.stmts, block.expr) {
411             ([], None) => {
412                 self.allow_insert_closure &= !self.in_tail_pos;
413             },
414             ([], Some(expr)) => self.visit_expr(expr),
415             (stmts, Some(expr)) => {
416                 let in_tail_pos = self.in_tail_pos;
417                 self.in_tail_pos = false;
418                 for stmt in stmts {
419                     self.visit_stmt(stmt);
420                 }
421                 self.in_tail_pos = in_tail_pos;
422                 self.visit_expr(expr);
423             },
424             ([stmts @ .., stmt], None) => {
425                 let in_tail_pos = self.in_tail_pos;
426                 self.in_tail_pos = false;
427                 for stmt in stmts {
428                     self.visit_stmt(stmt);
429                 }
430                 self.in_tail_pos = in_tail_pos;
431                 self.visit_stmt(stmt);
432             },
433         }
434     }
435
436     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
437         if !self.can_use_entry {
438             return;
439         }
440
441         match try_parse_insert(self.cx, expr) {
442             Some(insert_expr) if SpanlessEq::new(self.cx).eq_expr(self.map, insert_expr.map) => {
443                 // Multiple inserts, inserts with a different key, and inserts from a macro can't use the entry api.
444                 if self.is_map_used
445                     || !SpanlessEq::new(self.cx).eq_expr(self.key, insert_expr.key)
446                     || expr.span.ctxt() != self.ctxt
447                 {
448                     self.can_use_entry = false;
449                     return;
450                 }
451
452                 self.edits.push(Edit::Insertion(Insertion {
453                     call: expr,
454                     value: insert_expr.value,
455                 }));
456                 self.is_map_used = true;
457                 self.allow_insert_closure &= self.in_tail_pos;
458
459                 // The value doesn't affect whether there is only a single insert expression.
460                 let is_single_insert = self.is_single_insert;
461                 self.visit_non_tail_expr(insert_expr.value);
462                 self.is_single_insert = is_single_insert;
463             },
464             _ if SpanlessEq::new(self.cx).eq_expr(self.map, expr) => {
465                 self.is_map_used = true;
466             },
467             _ => match expr.kind {
468                 ExprKind::If(cond_expr, then_expr, Some(else_expr)) => {
469                     self.is_single_insert = false;
470                     self.visit_non_tail_expr(cond_expr);
471                     // Each branch may contain it's own insert expression.
472                     let mut is_map_used = self.visit_cond_arm(then_expr);
473                     is_map_used |= self.visit_cond_arm(else_expr);
474                     self.is_map_used = is_map_used;
475                 },
476                 ExprKind::Match(scrutinee_expr, arms, _) => {
477                     self.is_single_insert = false;
478                     self.visit_non_tail_expr(scrutinee_expr);
479                     // Each branch may contain it's own insert expression.
480                     let mut is_map_used = self.is_map_used;
481                     for arm in arms {
482                         self.visit_pat(arm.pat);
483                         if let Some(Guard::If(guard) | Guard::IfLet(_, guard)) = arm.guard {
484                             self.visit_non_tail_expr(guard);
485                         }
486                         is_map_used |= self.visit_cond_arm(arm.body);
487                     }
488                     self.is_map_used = is_map_used;
489                 },
490                 ExprKind::Loop(block, ..) => {
491                     self.loops.push(expr.hir_id);
492                     self.is_single_insert = false;
493                     self.allow_insert_closure &= !self.in_tail_pos;
494                     // Don't allow insertions inside of a loop.
495                     let edit_len = self.edits.len();
496                     self.visit_block(block);
497                     if self.edits.len() != edit_len {
498                         self.can_use_entry = false;
499                     }
500                     self.loops.pop();
501                 },
502                 ExprKind::Block(block, _) => self.visit_block(block),
503                 ExprKind::InlineAsm(_) | ExprKind::LlvmInlineAsm(_) => {
504                     self.can_use_entry = false;
505                 },
506                 _ => {
507                     self.allow_insert_closure &= !self.in_tail_pos;
508                     self.allow_insert_closure &=
509                         can_move_expr_to_closure_no_visit(self.cx, expr, &self.loops, &self.locals);
510                     // Sub expressions are no longer in the tail position.
511                     self.is_single_insert = false;
512                     self.in_tail_pos = false;
513                     walk_expr(self, expr);
514                 },
515             },
516         }
517     }
518
519     fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
520         p.each_binding_or_first(&mut |_, id, _, _| {
521             self.locals.insert(id);
522         });
523     }
524 }
525
526 struct InsertSearchResults<'tcx> {
527     edits: Vec<Edit<'tcx>>,
528     allow_insert_closure: bool,
529     is_single_insert: bool,
530 }
531 impl InsertSearchResults<'tcx> {
532     fn as_single_insertion(&self) -> Option<Insertion<'tcx>> {
533         self.is_single_insert.then(|| self.edits[0].as_insertion().unwrap())
534     }
535
536     fn snippet(
537         &self,
538         cx: &LateContext<'_>,
539         mut span: Span,
540         app: &mut Applicability,
541         write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability),
542     ) -> String {
543         let ctxt = span.ctxt();
544         let mut res = String::new();
545         for insertion in self.edits.iter().filter_map(|e| e.as_insertion()) {
546             res.push_str(&snippet_with_applicability(
547                 cx,
548                 span.until(insertion.call.span),
549                 "..",
550                 app,
551             ));
552             if is_expr_used_or_unified(cx.tcx, insertion.call) {
553                 write_wrapped(&mut res, insertion, ctxt, app);
554             } else {
555                 let _ = write!(
556                     res,
557                     "e.insert({})",
558                     snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
559                 );
560             }
561             span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
562         }
563         res.push_str(&snippet_with_applicability(cx, span, "..", app));
564         res
565     }
566
567     fn snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
568         (
569             self.snippet(cx, span, app, |res, insertion, ctxt, app| {
570                 // Insertion into a map would return `Some(&mut value)`, but the entry returns `&mut value`
571                 let _ = write!(
572                     res,
573                     "Some(e.insert({}))",
574                     snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
575                 );
576             }),
577             "Occupied(mut e)",
578         )
579     }
580
581     fn snippet_vacant(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
582         (
583             self.snippet(cx, span, app, |res, insertion, ctxt, app| {
584                 // Insertion into a map would return `None`, but the entry returns a mutable reference.
585                 let _ = if is_expr_final_block_expr(cx.tcx, insertion.call) {
586                     write!(
587                         res,
588                         "e.insert({});\n{}None",
589                         snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
590                         snippet_indent(cx, insertion.call.span).as_deref().unwrap_or(""),
591                     )
592                 } else {
593                     write!(
594                         res,
595                         "{{ e.insert({}); None }}",
596                         snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
597                     )
598                 };
599             }),
600             "Vacant(e)",
601         )
602     }
603
604     fn snippet_closure(&self, cx: &LateContext<'_>, mut span: Span, app: &mut Applicability) -> String {
605         let ctxt = span.ctxt();
606         let mut res = String::new();
607         for edit in &self.edits {
608             match *edit {
609                 Edit::Insertion(insertion) => {
610                     // Cut out the value from `map.insert(key, value)`
611                     res.push_str(&snippet_with_applicability(
612                         cx,
613                         span.until(insertion.call.span),
614                         "..",
615                         app,
616                     ));
617                     res.push_str(&snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0);
618                     span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
619                 },
620                 Edit::RemoveSemi(semi_span) => {
621                     // Cut out the semicolon. This allows the value to be returned from the closure.
622                     res.push_str(&snippet_with_applicability(cx, span.until(semi_span), "..", app));
623                     span = span.trim_start(semi_span).unwrap_or(DUMMY_SP);
624                 },
625             }
626         }
627         res.push_str(&snippet_with_applicability(cx, span, "..", app));
628         res
629     }
630 }
631
632 fn find_insert_calls(
633     cx: &LateContext<'tcx>,
634     contains_expr: &ContainsExpr<'tcx>,
635     expr: &'tcx Expr<'_>,
636 ) -> Option<InsertSearchResults<'tcx>> {
637     let mut s = InsertSearcher {
638         cx,
639         map: contains_expr.map,
640         key: contains_expr.key,
641         ctxt: expr.span.ctxt(),
642         edits: Vec::new(),
643         is_map_used: false,
644         allow_insert_closure: true,
645         can_use_entry: true,
646         in_tail_pos: true,
647         is_single_insert: true,
648         loops: Vec::new(),
649         locals: HirIdSet::default(),
650     };
651     s.visit_expr(expr);
652     let allow_insert_closure = s.allow_insert_closure;
653     let is_single_insert = s.is_single_insert;
654     let edits = s.edits;
655     s.can_use_entry.then(|| InsertSearchResults {
656         edits,
657         allow_insert_closure,
658         is_single_insert,
659     })
660 }