]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/entry.rs
Auto merge of #85690 - bstrie:m2_arena, r=jackh726,nagisa
[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     intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
13     Block, Expr, ExprKind, Guard, HirId, Local, Stmt, StmtKind, UnOp,
14 };
15 use rustc_lint::{LateContext, LateLintPass};
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_span::{Span, SyntaxContext, DUMMY_SP};
18
19 declare_clippy_lint! {
20     /// ### What it does
21     /// Checks for uses of `contains_key` + `insert` on `HashMap`
22     /// or `BTreeMap`.
23     ///
24     /// ### Why is this bad?
25     /// Using `entry` is more efficient.
26     ///
27     /// ### Known problems
28     /// The suggestion may have type inference errors in some cases. e.g.
29     /// ```rust
30     /// let mut map = std::collections::HashMap::new();
31     /// let _ = if !map.contains_key(&0) {
32     ///     map.insert(0, 0)
33     /// } else {
34     ///     None
35     /// };
36     /// ```
37     ///
38     /// ### Example
39     /// ```rust
40     /// # use std::collections::HashMap;
41     /// # let mut map = HashMap::new();
42     /// # let k = 1;
43     /// # let v = 1;
44     /// if !map.contains_key(&k) {
45     ///     map.insert(k, v);
46     /// }
47     /// ```
48     /// can both be rewritten as:
49     /// ```rust
50     /// # use std::collections::HashMap;
51     /// # let mut map = HashMap::new();
52     /// # let k = 1;
53     /// # let v = 1;
54     /// map.entry(k).or_insert(v);
55     /// ```
56     pub MAP_ENTRY,
57     perf,
58     "use of `contains_key` followed by `insert` on a `HashMap` or `BTreeMap`"
59 }
60
61 declare_lint_pass!(HashMapPass => [MAP_ENTRY]);
62
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),
68             _ => return,
69         };
70
71         let (map_ty, contains_expr) = match try_parse_contains(cx, cond_expr) {
72             Some(x) => x,
73             None => return,
74         };
75
76         let then_search = match find_insert_calls(cx, &contains_expr, then_expr) {
77             Some(x) => x,
78             None => return,
79         };
80
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,
87                 None => return,
88             };
89
90             if then_search.edits.is_empty() && else_search.edits.is_empty() {
91                 // No insertions
92                 return;
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) {
96                     (true, true) => (
97                         then_search.snippet_vacant(cx, then_expr.span, &mut app),
98                         snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
99                     ),
100                     (true, false) => (
101                         then_search.snippet_occupied(cx, then_expr.span, &mut app),
102                         snippet_with_applicability(cx, else_expr.span, "{ .. }", &mut app),
103                     ),
104                     (false, true) => (
105                         else_search.snippet_occupied(cx, else_expr.span, &mut app),
106                         snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
107                     ),
108                     (false, false) => (
109                         else_search.snippet_vacant(cx, else_expr.span, &mut app),
110                         snippet_with_applicability(cx, then_expr.span, "{ .. }", &mut app),
111                     ),
112                 };
113                 format!(
114                     "if let {}::{} = {}.entry({}) {} else {}",
115                     map_ty.entry_path(),
116                     entry_kind,
117                     map_str,
118                     key_str,
119                     then_str,
120                     else_str,
121                 )
122             } else {
123                 // if .. { insert } else { insert }
124                 let ((then_str, then_entry), (else_str, else_entry)) = if contains_expr.negated {
125                     (
126                         then_search.snippet_vacant(cx, then_expr.span, &mut app),
127                         else_search.snippet_occupied(cx, else_expr.span, &mut app),
128                     )
129                 } else {
130                     (
131                         then_search.snippet_occupied(cx, then_expr.span, &mut app),
132                         else_search.snippet_vacant(cx, else_expr.span, &mut app),
133                     )
134                 };
135                 let indent_str = snippet_indent(cx, expr.span);
136                 let indent_str = indent_str.as_deref().unwrap_or("");
137                 format!(
138                     "match {}.entry({}) {{\n{indent}    {entry}::{} => {}\n\
139                         {indent}    {entry}::{} => {}\n{indent}}}",
140                     map_str,
141                     key_str,
142                     then_entry,
143                     reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
144                     else_entry,
145                     reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
146                     entry = map_ty.entry_path(),
147                     indent = indent_str,
148                 )
149             }
150         } else {
151             if then_search.edits.is_empty() {
152                 // no insertions
153                 return;
154             }
155
156             // if .. { insert }
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)
160                 } else {
161                     then_search.snippet_occupied(cx, then_expr.span, &mut app)
162                 };
163                 format!(
164                     "if let {}::{} = {}.entry({}) {}",
165                     map_ty.entry_path(),
166                     entry_kind,
167                     map_str,
168                     key_str,
169                     body_str,
170                 )
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)
176                     } else {
177                         format!("{}.entry({}).or_insert({});", map_str, key_str, value_str)
178                     }
179                 } else {
180                     // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
181                     // This would need to be a different lint.
182                     return;
183                 }
184             } else {
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)
188                 } else {
189                     // TODO: suggest using `if let Some(v) = map.get_mut(k) { .. }` here.
190                     // This would need to be a different lint.
191                     return;
192                 }
193             }
194         };
195
196         span_lint_and_sugg(
197             cx,
198             MAP_ENTRY,
199             expr.span,
200             &format!("usage of `contains_key` followed by `insert` on a `{}`", map_ty.name()),
201             "try this",
202             sugg,
203             app,
204         );
205     }
206 }
207
208 #[derive(Clone, Copy)]
209 enum MapType {
210     Hash,
211     BTree,
212 }
213 impl MapType {
214     fn name(self) -> &'static str {
215         match self {
216             Self::Hash => "HashMap",
217             Self::BTree => "BTreeMap",
218         }
219     }
220     fn entry_path(self) -> &'static str {
221         match self {
222             Self::Hash => "std::collections::hash_map::Entry",
223             Self::BTree => "std::collections::btree_map::Entry",
224         }
225     }
226 }
227
228 struct ContainsExpr<'tcx> {
229     negated: bool,
230     map: &'tcx Expr<'tcx>,
231     key: &'tcx Expr<'tcx>,
232     call_ctxt: SyntaxContext,
233 }
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) => {
238             negated = !negated;
239             Some(e)
240         },
241         _ => None,
242     });
243     match expr.kind {
244         ExprKind::MethodCall(
245             _,
246             _,
247             [map, Expr {
248                 kind: ExprKind::AddrOf(_, _, key),
249                 span: key_span,
250                 ..
251             }],
252             _,
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 {
256                 negated,
257                 map,
258                 key,
259                 call_ctxt: expr.span.ctxt(),
260             };
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))
265             } else {
266                 None
267             }
268         },
269         _ => None,
270     }
271 }
272
273 struct InsertExpr<'tcx> {
274     map: &'tcx Expr<'tcx>,
275     key: &'tcx Expr<'tcx>,
276     value: &'tcx Expr<'tcx>,
277 }
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 })
283         } else {
284             None
285         }
286     } else {
287         None
288     }
289 }
290
291 /// An edit that will need to be made to move the expression to use the entry api
292 #[derive(Clone, Copy)]
293 enum Edit<'tcx> {
294     /// A semicolon that needs to be removed. Used to create a closure for `insert_with`.
295     RemoveSemi(Span),
296     /// An insertion into the map.
297     Insertion(Insertion<'tcx>),
298 }
299 impl Edit<'tcx> {
300     fn as_insertion(self) -> Option<Insertion<'tcx>> {
301         if let Self::Insertion(i) = self { Some(i) } else { None }
302     }
303 }
304 #[derive(Clone, Copy)]
305 struct Insertion<'tcx> {
306     call: &'tcx Expr<'tcx>,
307     value: &'tcx Expr<'tcx>,
308 }
309
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
313 ///   otherwise.
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.
326     ctxt: SyntaxContext,
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.
330     can_use_entry: bool,
331     /// Whether this expression is the final expression in this code path. This may be a statement.
332     in_tail_pos: bool,
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.
336     is_map_used: bool,
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.
340     loops: Vec<HirId>,
341 }
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;
349         self.visit_expr(e);
350         let res = self.is_map_used;
351         self.is_map_used = is_map_used;
352         self.in_tail_pos = in_tail_pos;
353         res
354     }
355
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;
361         self.visit_expr(e);
362         self.in_tail_pos = in_tail_pos;
363     }
364 }
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
369     }
370
371     fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
372         match stmt.kind {
373             StmtKind::Semi(e) => {
374                 self.visit_expr(e);
375
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 {
380                         self.edits
381                             .push(Edit::RemoveSemi(stmt.span.trim_start(e.span).unwrap_or(DUMMY_SP)));
382                     } else {
383                         self.allow_insert_closure = false;
384                     }
385                 }
386             },
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;
392                 self.visit_expr(e);
393             },
394             _ => {
395                 self.allow_insert_closure &= !self.in_tail_pos;
396                 self.is_single_insert = false;
397             },
398         }
399     }
400
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) {
405             ([], None) => {
406                 self.allow_insert_closure &= !self.in_tail_pos;
407             },
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;
412                 for stmt in stmts {
413                     self.visit_stmt(stmt);
414                 }
415                 self.in_tail_pos = in_tail_pos;
416                 self.visit_expr(expr);
417             },
418             ([stmts @ .., stmt], None) => {
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_stmt(stmt);
426             },
427         }
428     }
429
430     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
431         if !self.can_use_entry {
432             return;
433         }
434
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.
438                 if self.is_map_used
439                     || !SpanlessEq::new(self.cx).eq_expr(self.key, insert_expr.key)
440                     || expr.span.ctxt() != self.ctxt
441                 {
442                     self.can_use_entry = false;
443                     return;
444                 }
445
446                 self.edits.push(Edit::Insertion(Insertion {
447                     call: expr,
448                     value: insert_expr.value,
449                 }));
450                 self.is_map_used = true;
451                 self.allow_insert_closure &= self.in_tail_pos;
452
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;
457             },
458             _ if SpanlessEq::new(self.cx).eq_expr(self.map, expr) => {
459                 self.is_map_used = true;
460             },
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;
469                 },
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;
475                     for arm in arms {
476                         if let Some(Guard::If(guard) | Guard::IfLet(_, guard)) = arm.guard {
477                             self.visit_non_tail_expr(guard);
478                         }
479                         is_map_used |= self.visit_cond_arm(arm.body);
480                     }
481                     self.is_map_used = is_map_used;
482                 },
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;
492                     }
493                     self.loops.pop();
494                 },
495                 ExprKind::Block(block, _) => self.visit_block(block),
496                 ExprKind::InlineAsm(_) | ExprKind::LlvmInlineAsm(_) => {
497                     self.can_use_entry = false;
498                 },
499                 _ => {
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);
506                 },
507             },
508         }
509     }
510 }
511
512 struct InsertSearchResults<'tcx> {
513     edits: Vec<Edit<'tcx>>,
514     allow_insert_closure: bool,
515     is_single_insert: bool,
516 }
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())
520     }
521
522     fn snippet(
523         &self,
524         cx: &LateContext<'_>,
525         mut span: Span,
526         app: &mut Applicability,
527         write_wrapped: impl Fn(&mut String, Insertion<'_>, SyntaxContext, &mut Applicability),
528     ) -> String {
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(
533                 cx,
534                 span.until(insertion.call.span),
535                 "..",
536                 app,
537             ));
538             if is_expr_used_or_unified(cx.tcx, insertion.call) {
539                 write_wrapped(&mut res, insertion, ctxt, app);
540             } else {
541                 let _ = write!(
542                     res,
543                     "e.insert({})",
544                     snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
545                 );
546             }
547             span = span.trim_start(insertion.call.span).unwrap_or(DUMMY_SP);
548         }
549         res.push_str(&snippet_with_applicability(cx, span, "..", app));
550         res
551     }
552
553     fn snippet_occupied(&self, cx: &LateContext<'_>, span: Span, app: &mut Applicability) -> (String, &'static str) {
554         (
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`
557                 let _ = write!(
558                     res,
559                     "Some(e.insert({}))",
560                     snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0
561                 );
562             }),
563             "Occupied(mut e)",
564         )
565     }
566
567     fn snippet_vacant(&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 `None`, but the entry returns a mutable reference.
571                 let _ = if is_expr_final_block_expr(cx.tcx, insertion.call) {
572                     write!(
573                         res,
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(""),
577                     )
578                 } else {
579                     write!(
580                         res,
581                         "{{ e.insert({}); None }}",
582                         snippet_with_context(cx, insertion.value.span, ctxt, "..", app).0,
583                     )
584                 };
585             }),
586             "Vacant(e)",
587         )
588     }
589
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 {
594             match *edit {
595                 Edit::Insertion(insertion) => {
596                     // Cut out the value from `map.insert(key, value)`
597                     res.push_str(&snippet_with_applicability(
598                         cx,
599                         span.until(insertion.call.span),
600                         "..",
601                         app,
602                     ));
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);
605                 },
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);
610                 },
611             }
612         }
613         res.push_str(&snippet_with_applicability(cx, span, "..", app));
614         res
615     }
616 }
617
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 {
624         cx,
625         map: contains_expr.map,
626         key: contains_expr.key,
627         ctxt: expr.span.ctxt(),
628         edits: Vec::new(),
629         is_map_used: false,
630         allow_insert_closure: true,
631         can_use_entry: true,
632         in_tail_pos: true,
633         is_single_insert: true,
634         loops: Vec::new(),
635     };
636     s.visit_expr(expr);
637     let allow_insert_closure = s.allow_insert_closure;
638     let is_single_insert = s.is_single_insert;
639     let edits = s.edits;
640     s.can_use_entry.then(|| InsertSearchResults {
641         edits,
642         allow_insert_closure,
643         is_single_insert,
644     })
645 }