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