]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir_build/build/matches/mod.rs
Implement general or-patterns in `match` expressions
[rust.git] / src / librustc_mir_build / build / matches / mod.rs
1 //! Code related to match expressions. These are sufficiently complex to
2 //! warrant their own module and submodules. :) This main module includes the
3 //! high-level algorithm, the submodules contain the details.
4 //!
5 //! This also includes code for pattern bindings in `let` statements and
6 //! function parameters.
7
8 use crate::build::scope::DropKind;
9 use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard};
10 use crate::build::{BlockAnd, BlockAndExtension, Builder};
11 use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode};
12 use crate::hair::{self, *};
13 use rustc::middle::region;
14 use rustc::mir::*;
15 use rustc::ty::layout::VariantIdx;
16 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty};
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_hir::HirId;
19 use rustc_index::bit_set::BitSet;
20 use rustc_span::Span;
21 use smallvec::{smallvec, SmallVec};
22 use syntax::ast::Name;
23
24 // helper functions, broken out by category:
25 mod simplify;
26 mod test;
27 mod util;
28
29 use std::borrow::Borrow;
30 use std::convert::TryFrom;
31 use std::mem;
32
33 impl<'a, 'tcx> Builder<'a, 'tcx> {
34     /// Generates MIR for a `match` expression.
35     ///
36     /// The MIR that we generate for a match looks like this.
37     ///
38     /// ```text
39     /// [ 0. Pre-match ]
40     ///        |
41     /// [ 1. Evaluate Scrutinee (expression being matched on) ]
42     /// [ (fake read of scrutinee) ]
43     ///        |
44     /// [ 2. Decision tree -- check discriminants ] <--------+
45     ///        |                                             |
46     ///        | (once a specific arm is chosen)             |
47     ///        |                                             |
48     /// [pre_binding_block]                           [otherwise_block]
49     ///        |                                             |
50     /// [ 3. Create "guard bindings" for arm ]               |
51     /// [ (create fake borrows) ]                            |
52     ///        |                                             |
53     /// [ 4. Execute guard code ]                            |
54     /// [ (read fake borrows) ] --(guard is false)-----------+
55     ///        |
56     ///        | (guard results in true)
57     ///        |
58     /// [ 5. Create real bindings and execute arm ]
59     ///        |
60     /// [ Exit match ]
61     /// ```
62     ///
63     /// All of the different arms have been stacked on top of each other to
64     /// simplify the diagram. For an arm with no guard the blocks marked 3 and
65     /// 4 and the fake borrows are omitted.
66     ///
67     /// We generate MIR in the following steps:
68     ///
69     /// 1. Evaluate the scrutinee and add the fake read of it ([Builder::lower_scrutinee]).
70     /// 2. Create the decision tree ([Builder::lower_match_tree]).
71     /// 3. Determine the fake borrows that are needed from the places that were
72     ///    matched against and create the required temporaries for them
73     ///    ([Builder::calculate_fake_borrows]).
74     /// 4. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
75     ///
76     /// ## False edges
77     ///
78     /// We don't want to have the exact structure of the decision tree be
79     /// visible through borrow checking. False edges ensure that the CFG as
80     /// seen by borrow checking doesn't encode this. False edges are added:
81     ///
82     /// * From each prebinding block to the next prebinding block.
83     /// * From each otherwise block to the next prebinding block.
84     crate fn match_expr(
85         &mut self,
86         destination: &Place<'tcx>,
87         span: Span,
88         mut block: BasicBlock,
89         scrutinee: ExprRef<'tcx>,
90         arms: Vec<Arm<'tcx>>,
91     ) -> BlockAnd<()> {
92         let scrutinee_span = scrutinee.span();
93         let scrutinee_place =
94             unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,));
95
96         let mut arm_candidates = self.create_match_candidates(&scrutinee_place, &arms);
97
98         let match_has_guard = arms.iter().any(|arm| arm.guard.is_some());
99         let candidates =
100             arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::<Vec<_>>();
101
102         let fake_borrow_temps =
103             self.lower_match_tree(block, scrutinee_span, match_has_guard, candidates);
104
105         self.lower_match_arms(
106             &destination,
107             scrutinee_place,
108             scrutinee_span,
109             arm_candidates,
110             self.source_info(span),
111             fake_borrow_temps,
112         )
113     }
114
115     /// Evaluate the scrutinee and add the fake read of it.
116     fn lower_scrutinee(
117         &mut self,
118         mut block: BasicBlock,
119         scrutinee: ExprRef<'tcx>,
120         scrutinee_span: Span,
121     ) -> BlockAnd<Place<'tcx>> {
122         let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
123         // Matching on a `scrutinee_place` with an uninhabited type doesn't
124         // generate any memory reads by itself, and so if the place "expression"
125         // contains unsafe operations like raw pointer dereferences or union
126         // field projections, we wouldn't know to require an `unsafe` block
127         // around a `match` equivalent to `std::intrinsics::unreachable()`.
128         // See issue #47412 for this hole being discovered in the wild.
129         //
130         // HACK(eddyb) Work around the above issue by adding a dummy inspection
131         // of `scrutinee_place`, specifically by applying `ReadForMatch`.
132         //
133         // NOTE: ReadForMatch also checks that the scrutinee is initialized.
134         // This is currently needed to not allow matching on an uninitialized,
135         // uninhabited value. If we get never patterns, those will check that
136         // the place is initialized, and so this read would only be used to
137         // check safety.
138         let cause_matched_place = FakeReadCause::ForMatchedPlace;
139         let source_info = self.source_info(scrutinee_span);
140         self.cfg.push_fake_read(block, source_info, cause_matched_place, scrutinee_place.clone());
141
142         block.and(scrutinee_place)
143     }
144
145     /// Create the initial `Candidate`s for a `match` expression.
146     fn create_match_candidates<'pat>(
147         &mut self,
148         scrutinee: &Place<'tcx>,
149         arms: &'pat [Arm<'tcx>],
150     ) -> Vec<(&'pat Arm<'tcx>, Candidate<'pat, 'tcx>)> {
151         // Assemble a list of candidates: there is one candidate per pattern,
152         // which means there may be more than one candidate *per arm*.
153         arms.iter()
154             .map(|arm| {
155                 let arm_has_guard = arm.guard.is_some();
156                 let arm_candidate = Candidate {
157                     span: arm.pattern.span,
158                     match_pairs: smallvec![MatchPair::new(*scrutinee, &arm.pattern),],
159                     bindings: vec![],
160                     ascriptions: vec![],
161                     has_guard: arm_has_guard,
162                     needs_otherwise_block: arm_has_guard,
163                     otherwise_block: None,
164                     pre_binding_block: None,
165                     next_candidate_pre_binding_block: None,
166                     subcandidates: vec![],
167                 };
168                 (arm, arm_candidate)
169             })
170             .collect()
171     }
172
173     /// Create the decision tree for the match expression, starting from `block`.
174     ///
175     /// Modifies `candidates` to store the bindings and type ascriptions for
176     /// that candidate.
177     ///
178     /// Returns the places that need fake borrows because we bind or test them.
179     fn lower_match_tree<'pat>(
180         &mut self,
181         block: BasicBlock,
182         scrutinee_span: Span,
183         match_has_guard: bool,
184         mut candidates: Vec<&mut Candidate<'pat, 'tcx>>,
185     ) -> Vec<(Place<'tcx>, Local)> {
186         // The set of places that we are creating fake borrows of. If there are
187         // no match guards then we don't need any fake borrows, so don't track
188         // them.
189         let mut fake_borrows = if match_has_guard { Some(FxHashSet::default()) } else { None };
190
191         let mut otherwise = None;
192
193         // This will generate code to test scrutinee_place and
194         // branch to the appropriate arm block
195         self.match_candidates(
196             scrutinee_span,
197             block,
198             &mut otherwise,
199             &mut candidates,
200             &mut fake_borrows,
201         );
202
203         if let Some(otherwise_block) = otherwise {
204             let source_info = self.source_info(scrutinee_span);
205             self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
206         }
207
208         let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None;
209
210         for candidate in candidates.into_iter() {
211             candidate.visit_leaves(|leaf_candidate| {
212                 if let Some(ref mut prev) = previous_candidate {
213                     prev.next_candidate_pre_binding_block = leaf_candidate.pre_binding_block;
214                 }
215                 previous_candidate = Some(leaf_candidate);
216             });
217         }
218
219         if let Some(ref borrows) = fake_borrows {
220             self.calculate_fake_borrows(borrows, scrutinee_span)
221         } else {
222             Vec::new()
223         }
224     }
225
226     /// Lower the bindings, guards and arm bodies of a `match` expression.
227     ///
228     /// The decision tree should have already been created
229     /// (by [Builder::lower_match_tree]).
230     ///
231     /// `outer_source_info` is the SourceInfo for the whole match.
232     fn lower_match_arms(
233         &mut self,
234         destination: &Place<'tcx>,
235         scrutinee_place: Place<'tcx>,
236         scrutinee_span: Span,
237         arm_candidates: Vec<(&'_ Arm<'tcx>, Candidate<'_, 'tcx>)>,
238         outer_source_info: SourceInfo,
239         fake_borrow_temps: Vec<(Place<'tcx>, Local)>,
240     ) -> BlockAnd<()> {
241         let match_scope = self.scopes.topmost();
242
243         let arm_end_blocks: Vec<_> = arm_candidates
244             .into_iter()
245             .map(|(arm, candidate)| {
246                 debug!("lowering arm {:?}\ncanidate = {:?}", arm, candidate);
247
248                 let arm_source_info = self.source_info(arm.span);
249                 let arm_scope = (arm.scope, arm_source_info);
250                 self.in_scope(arm_scope, arm.lint_level, |this| {
251                     let body = this.hir.mirror(arm.body.clone());
252                     let scope = this.declare_bindings(
253                         None,
254                         arm.span,
255                         &arm.pattern,
256                         ArmHasGuard(arm.guard.is_some()),
257                         Some((Some(&scrutinee_place), scrutinee_span)),
258                     );
259
260                     let arm_block = this.bind_pattern(
261                         outer_source_info,
262                         candidate,
263                         arm.guard.as_ref().map(|g| (g, match_scope)),
264                         &fake_borrow_temps,
265                         scrutinee_span,
266                         arm.scope,
267                     );
268
269                     if let Some(source_scope) = scope {
270                         this.source_scope = source_scope;
271                     }
272
273                     this.into(destination, arm_block, body)
274                 })
275             })
276             .collect();
277
278         // all the arm blocks will rejoin here
279         let end_block = self.cfg.start_new_block();
280
281         for arm_block in arm_end_blocks {
282             self.cfg.goto(unpack!(arm_block), outer_source_info, end_block);
283         }
284
285         self.source_scope = outer_source_info.scope;
286
287         end_block.unit()
288     }
289
290     /// Binds the variables and ascribes types for a given `match` arm.
291     ///
292     /// Also check if the guard matches, if it's provided.
293     fn bind_pattern(
294         &mut self,
295         outer_source_info: SourceInfo,
296         candidate: Candidate<'_, 'tcx>,
297         guard: Option<(&Guard<'tcx>, region::Scope)>,
298         fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
299         scrutinee_span: Span,
300         arm_scope: region::Scope,
301     ) -> BasicBlock {
302         if candidate.subcandidates.is_empty() {
303             // Avoid generating another `BasicBlock` when we only have one
304             // candidate.
305             self.bind_and_guard_matched_candidate(
306                 candidate,
307                 &[],
308                 guard,
309                 fake_borrow_temps,
310                 scrutinee_span,
311             )
312         } else {
313             let target_block = self.cfg.start_new_block();
314
315             // We keep a stack of all of the bindings and type asciptions
316             // from the the parent candidates that we visit, that also need to
317             // be bound for each candidate.
318             traverse_candidate(
319                 candidate,
320                 &mut Vec::new(),
321                 &mut |leaf_candidate, parent_bindings| {
322                     self.clear_top_scope(arm_scope);
323                     let binding_end = self.bind_and_guard_matched_candidate(
324                         leaf_candidate,
325                         parent_bindings,
326                         guard,
327                         &fake_borrow_temps,
328                         scrutinee_span,
329                     );
330                     self.cfg.goto(binding_end, outer_source_info, target_block);
331                 },
332                 |inner_candidate, parent_bindings| {
333                     parent_bindings.push((inner_candidate.bindings, inner_candidate.ascriptions));
334                     inner_candidate.subcandidates.into_iter()
335                 },
336                 |parent_bindings| {
337                     parent_bindings.pop();
338                 },
339             );
340
341             target_block
342         }
343     }
344
345     pub(super) fn expr_into_pattern(
346         &mut self,
347         mut block: BasicBlock,
348         irrefutable_pat: Pat<'tcx>,
349         initializer: ExprRef<'tcx>,
350     ) -> BlockAnd<()> {
351         match *irrefutable_pat.kind {
352             // Optimize the case of `let x = ...` to write directly into `x`
353             PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
354                 let place =
355                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
356                 unpack!(block = self.into(&place, block, initializer));
357
358                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
359                 let source_info = self.source_info(irrefutable_pat.span);
360                 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet, place);
361
362                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
363                 block.unit()
364             }
365
366             // Optimize the case of `let x: T = ...` to write directly
367             // into `x` and then require that `T == typeof(x)`.
368             //
369             // Weirdly, this is needed to prevent the
370             // `intrinsic-move-val.rs` test case from crashing. That
371             // test works with uninitialized values in a rather
372             // dubious way, so it may be that the test is kind of
373             // broken.
374             PatKind::AscribeUserType {
375                 subpattern:
376                     Pat {
377                         kind:
378                             box PatKind::Binding {
379                                 mode: BindingMode::ByValue,
380                                 var,
381                                 subpattern: None,
382                                 ..
383                             },
384                         ..
385                     },
386                 ascription:
387                     hair::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
388             } => {
389                 let place =
390                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
391                 unpack!(block = self.into(&place, block, initializer));
392
393                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
394                 let pattern_source_info = self.source_info(irrefutable_pat.span);
395                 let cause_let = FakeReadCause::ForLet;
396                 self.cfg.push_fake_read(block, pattern_source_info, cause_let, place.clone());
397
398                 let ty_source_info = self.source_info(user_ty_span);
399                 let user_ty = pat_ascription_ty.user_ty(
400                     &mut self.canonical_user_type_annotations,
401                     place.ty(&self.local_decls, self.hir.tcx()).ty,
402                     ty_source_info.span,
403                 );
404                 self.cfg.push(
405                     block,
406                     Statement {
407                         source_info: ty_source_info,
408                         kind: StatementKind::AscribeUserType(
409                             box (place, user_ty),
410                             // We always use invariant as the variance here. This is because the
411                             // variance field from the ascription refers to the variance to use
412                             // when applying the type to the value being matched, but this
413                             // ascription applies rather to the type of the binding. e.g., in this
414                             // example:
415                             //
416                             // ```
417                             // let x: T = <expr>
418                             // ```
419                             //
420                             // We are creating an ascription that defines the type of `x` to be
421                             // exactly `T` (i.e., with invariance). The variance field, in
422                             // contrast, is intended to be used to relate `T` to the type of
423                             // `<expr>`.
424                             ty::Variance::Invariant,
425                         ),
426                     },
427                 );
428
429                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
430                 block.unit()
431             }
432
433             _ => {
434                 let place = unpack!(block = self.as_place(block, initializer));
435                 self.place_into_pattern(block, irrefutable_pat, &place, true)
436             }
437         }
438     }
439
440     crate fn place_into_pattern(
441         &mut self,
442         block: BasicBlock,
443         irrefutable_pat: Pat<'tcx>,
444         initializer: &Place<'tcx>,
445         set_match_place: bool,
446     ) -> BlockAnd<()> {
447         // create a dummy candidate
448         let mut candidate = Candidate {
449             span: irrefutable_pat.span,
450             has_guard: false,
451             needs_otherwise_block: false,
452             match_pairs: smallvec![MatchPair::new(*initializer, &irrefutable_pat)],
453             bindings: vec![],
454             ascriptions: vec![],
455
456             // since we don't call `match_candidates`, next fields are unused
457             otherwise_block: None,
458             pre_binding_block: None,
459             next_candidate_pre_binding_block: None,
460             subcandidates: vec![],
461         };
462
463         // Simplify the candidate. Since the pattern is irrefutable, this should
464         // always convert all match-pairs into bindings.
465         self.simplify_candidate(&mut candidate);
466
467         if !candidate.match_pairs.is_empty() {
468             // ICE if no other errors have been emitted. This used to be a hard error that wouldn't
469             // be reached because `hair::pattern::check_match::check_match` wouldn't have let the
470             // compiler continue. In our tests this is only ever hit by
471             // `ui/consts/const-match-check.rs` with `--cfg eval1`, and that file already generates
472             // a different error before hand.
473             self.hir.tcx().sess.delay_span_bug(
474                 candidate.match_pairs[0].pattern.span,
475                 &format!(
476                     "match pairs {:?} remaining after simplifying irrefutable pattern",
477                     candidate.match_pairs,
478                 ),
479             );
480         }
481
482         // for matches and function arguments, the place that is being matched
483         // can be set when creating the variables. But the place for
484         // let PATTERN = ... might not even exist until we do the assignment.
485         // so we set it here instead
486         if set_match_place {
487             for binding in &candidate.bindings {
488                 let local = self.var_local_id(binding.var_id, OutsideGuard);
489
490                 if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
491                     opt_match_place: Some((ref mut match_place, _)),
492                     ..
493                 }))) = self.local_decls[local].local_info
494                 {
495                     *match_place = Some(*initializer);
496                 } else {
497                     bug!("Let binding to non-user variable.")
498                 }
499             }
500         }
501
502         self.ascribe_types(block, &candidate.ascriptions);
503
504         // now apply the bindings, which will also declare the variables
505         self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
506
507         block.unit()
508     }
509
510     /// Declares the bindings of the given patterns and returns the visibility
511     /// scope for the bindings in these patterns, if such a scope had to be
512     /// created. NOTE: Declaring the bindings should always be done in their
513     /// drop scope.
514     crate fn declare_bindings(
515         &mut self,
516         mut visibility_scope: Option<SourceScope>,
517         scope_span: Span,
518         pattern: &Pat<'tcx>,
519         has_guard: ArmHasGuard,
520         opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
521     ) -> Option<SourceScope> {
522         debug!("declare_bindings: pattern={:?}", pattern);
523         self.visit_bindings(
524             &pattern,
525             UserTypeProjections::none(),
526             &mut |this, mutability, name, mode, var, span, ty, user_ty| {
527                 if visibility_scope.is_none() {
528                     visibility_scope =
529                         Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
530                 }
531                 let source_info = SourceInfo { span, scope: this.source_scope };
532                 let visibility_scope = visibility_scope.unwrap();
533                 this.declare_binding(
534                     source_info,
535                     visibility_scope,
536                     mutability,
537                     name,
538                     mode,
539                     var,
540                     ty,
541                     user_ty,
542                     has_guard,
543                     opt_match_place.map(|(x, y)| (x.cloned(), y)),
544                     pattern.span,
545                 );
546             },
547         );
548         visibility_scope
549     }
550
551     crate fn storage_live_binding(
552         &mut self,
553         block: BasicBlock,
554         var: HirId,
555         span: Span,
556         for_guard: ForGuard,
557     ) -> Place<'tcx> {
558         let local_id = self.var_local_id(var, for_guard);
559         let source_info = self.source_info(span);
560         self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
561         let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
562         self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
563         Place::from(local_id)
564     }
565
566     crate fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
567         let local_id = self.var_local_id(var, for_guard);
568         let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
569         self.schedule_drop(span, region_scope, local_id, DropKind::Value);
570     }
571
572     pub(super) fn visit_bindings(
573         &mut self,
574         pattern: &Pat<'tcx>,
575         pattern_user_ty: UserTypeProjections,
576         f: &mut impl FnMut(
577             &mut Self,
578             Mutability,
579             Name,
580             BindingMode,
581             HirId,
582             Span,
583             Ty<'tcx>,
584             UserTypeProjections,
585         ),
586     ) {
587         debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
588         match *pattern.kind {
589             PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, .. } => {
590                 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
591                 if let Some(subpattern) = subpattern.as_ref() {
592                     self.visit_bindings(subpattern, pattern_user_ty, f);
593                 }
594             }
595
596             PatKind::Array { ref prefix, ref slice, ref suffix }
597             | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
598                 let from = u32::try_from(prefix.len()).unwrap();
599                 let to = u32::try_from(suffix.len()).unwrap();
600                 for subpattern in prefix {
601                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
602                 }
603                 for subpattern in slice {
604                     self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
605                 }
606                 for subpattern in suffix {
607                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
608                 }
609             }
610
611             PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
612
613             PatKind::Deref { ref subpattern } => {
614                 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
615             }
616
617             PatKind::AscribeUserType {
618                 ref subpattern,
619                 ascription: hair::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
620             } => {
621                 // This corresponds to something like
622                 //
623                 // ```
624                 // let A::<'a>(_): A<'static> = ...;
625                 // ```
626                 //
627                 // Note that the variance doesn't apply here, as we are tracking the effect
628                 // of `user_ty` on any bindings contained with subpattern.
629                 let annotation = CanonicalUserTypeAnnotation {
630                     span: user_ty_span,
631                     user_ty: user_ty.user_ty,
632                     inferred_ty: subpattern.ty,
633                 };
634                 let projection = UserTypeProjection {
635                     base: self.canonical_user_type_annotations.push(annotation),
636                     projs: Vec::new(),
637                 };
638                 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
639                 self.visit_bindings(subpattern, subpattern_user_ty, f)
640             }
641
642             PatKind::Leaf { ref subpatterns } => {
643                 for subpattern in subpatterns {
644                     let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
645                     debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
646                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
647                 }
648             }
649
650             PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
651                 for subpattern in subpatterns {
652                     let subpattern_user_ty =
653                         pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
654                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
655                 }
656             }
657             PatKind::Or { ref pats } => {
658                 self.visit_bindings(&pats[0], pattern_user_ty.clone(), f);
659             }
660         }
661     }
662 }
663
664 #[derive(Debug)]
665 crate struct Candidate<'pat, 'tcx> {
666     /// `Span` of the original pattern that gave rise to this candidate
667     span: Span,
668
669     /// This `Candidate` has a guard.
670     has_guard: bool,
671
672     /// This `Candidate` needs and otherwise block, either because it has a
673     /// guard or it has subcandidates.
674     needs_otherwise_block: bool,
675
676     /// All of these must be satisfied...
677     match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
678
679     /// ...these bindings established...
680     bindings: Vec<Binding<'tcx>>,
681
682     /// ...and these types asserted...
683     ascriptions: Vec<Ascription<'tcx>>,
684
685     /// ... and if this is non-empty, one of these subcandidates also has to match ...
686     subcandidates: Vec<Candidate<'pat, 'tcx>>,
687
688     /// ...and the guard must be evaluated, if false branch to Block...
689     otherwise_block: Option<BasicBlock>,
690
691     /// ...and the blocks for add false edges between candidates
692     pre_binding_block: Option<BasicBlock>,
693     next_candidate_pre_binding_block: Option<BasicBlock>,
694 }
695
696 impl Candidate<'_, '_> {
697     /// Visit the leaf candidates (those with no subcandidates) contained in
698     /// this candidate.
699     fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
700         traverse_candidate(
701             self,
702             &mut (),
703             &mut move |c, _| visit_leaf(c),
704             move |c, _| c.subcandidates.iter_mut(),
705             |_| {},
706         );
707     }
708 }
709
710 /// A depth-first traversal of the `Candidate` and all of its recursive
711 /// subcandidates.
712 fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>(
713     candidate: C,
714     context: &mut T,
715     visit_leaf: &mut impl FnMut(C, &mut T),
716     get_children: impl Copy + Fn(C, &mut T) -> I,
717     complete_children: impl Copy + Fn(&mut T),
718 ) where
719     C: Borrow<Candidate<'pat, 'tcx>>,
720     I: Iterator<Item = C>,
721 {
722     if candidate.borrow().subcandidates.is_empty() {
723         visit_leaf(candidate, context)
724     } else {
725         for child in get_children(candidate, context) {
726             traverse_candidate(child, context, visit_leaf, get_children, complete_children);
727         }
728         complete_children(context)
729     }
730 }
731
732 #[derive(Clone, Debug)]
733 struct Binding<'tcx> {
734     span: Span,
735     source: Place<'tcx>,
736     name: Name,
737     var_id: HirId,
738     var_ty: Ty<'tcx>,
739     mutability: Mutability,
740     binding_mode: BindingMode,
741 }
742
743 /// Indicates that the type of `source` must be a subtype of the
744 /// user-given type `user_ty`; this is basically a no-op but can
745 /// influence region inference.
746 #[derive(Clone, Debug)]
747 struct Ascription<'tcx> {
748     span: Span,
749     source: Place<'tcx>,
750     user_ty: PatTyProj<'tcx>,
751     variance: ty::Variance,
752 }
753
754 #[derive(Clone, Debug)]
755 crate struct MatchPair<'pat, 'tcx> {
756     // this place...
757     place: Place<'tcx>,
758
759     // ... must match this pattern.
760     pattern: &'pat Pat<'tcx>,
761 }
762
763 #[derive(Clone, Debug, PartialEq)]
764 enum TestKind<'tcx> {
765     /// Test the branches of enum.
766     Switch {
767         /// The enum being tested
768         adt_def: &'tcx ty::AdtDef,
769         /// The set of variants that we should create a branch for. We also
770         /// create an additional "otherwise" case.
771         variants: BitSet<VariantIdx>,
772     },
773
774     /// Test what value an `integer`, `bool` or `char` has.
775     SwitchInt {
776         /// The type of the value that we're testing.
777         switch_ty: Ty<'tcx>,
778         /// The (ordered) set of values that we test for.
779         ///
780         /// For integers and `char`s we create a branch to each of the values in
781         /// `options`, as well as an "otherwise" branch for all other values, even
782         /// in the (rare) case that options is exhaustive.
783         ///
784         /// For `bool` we always generate two edges, one for `true` and one for
785         /// `false`.
786         options: Vec<u128>,
787         /// Reverse map used to ensure that the values in `options` are unique.
788         indices: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
789     },
790
791     /// Test for equality with value, possibly after an unsizing coercion to
792     /// `ty`,
793     Eq {
794         value: &'tcx ty::Const<'tcx>,
795         // Integer types are handled by `SwitchInt`, and constants with ADT
796         // types are converted back into patterns, so this can only be `&str`,
797         // `&[T]`, `f32` or `f64`.
798         ty: Ty<'tcx>,
799     },
800
801     /// Test whether the value falls within an inclusive or exclusive range
802     Range(PatRange<'tcx>),
803
804     /// Test length of the slice is equal to len
805     Len { len: u64, op: BinOp },
806 }
807
808 #[derive(Debug)]
809 crate struct Test<'tcx> {
810     span: Span,
811     kind: TestKind<'tcx>,
812 }
813
814 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
815 /// a match arm has a guard expression attached to it.
816 #[derive(Copy, Clone, Debug)]
817 crate struct ArmHasGuard(crate bool);
818
819 ///////////////////////////////////////////////////////////////////////////
820 // Main matching algorithm
821
822 impl<'a, 'tcx> Builder<'a, 'tcx> {
823     /// The main match algorithm. It begins with a set of candidates
824     /// `candidates` and has the job of generating code to determine
825     /// which of these candidates, if any, is the correct one. The
826     /// candidates are sorted such that the first item in the list
827     /// has the highest priority. When a candidate is found to match
828     /// the value, we will set and generate a branch to the appropriate
829     /// prebinding block.
830     ///
831     /// If we find that *NONE* of the candidates apply, we branch to the
832     /// `otherwise_block`, setting it to `Some` if required. In principle, this
833     /// means that the input list was not exhaustive, though at present we
834     /// sometimes are not smart enough to recognize all exhaustive inputs.
835     ///
836     /// It might be surprising that the input can be inexhaustive.
837     /// Indeed, initially, it is not, because all matches are
838     /// exhaustive in Rust. But during processing we sometimes divide
839     /// up the list of candidates and recurse with a non-exhaustive
840     /// list. This is important to keep the size of the generated code
841     /// under control. See `test_candidates` for more details.
842     ///
843     /// If `fake_borrows` is Some, then places which need fake borrows
844     /// will be added to it.
845     fn match_candidates<'pat>(
846         &mut self,
847         span: Span,
848         start_block: BasicBlock,
849         otherwise_block: &mut Option<BasicBlock>,
850         candidates: &mut [&mut Candidate<'pat, 'tcx>],
851         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
852     ) {
853         debug!(
854             "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
855             span, candidates, start_block, otherwise_block,
856         );
857
858         // Start by simplifying candidates. Once this process is complete, all
859         // the match pairs which remain require some form of test, whether it
860         // be a switch or pattern comparison.
861         let mut split_or_candidate = false;
862         for candidate in &mut *candidates {
863             split_or_candidate |= self.simplify_candidate(candidate);
864         }
865
866         if split_or_candidate {
867             // At least one of the candidates has been split into subcandidates.
868             // We need to change the candidate list to include those.
869             let mut new_candidates = Vec::new();
870
871             for candidate in candidates {
872                 candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate));
873             }
874             self.match_simplified_candidates(
875                 span,
876                 start_block,
877                 otherwise_block,
878                 &mut *new_candidates,
879                 fake_borrows,
880             );
881         } else {
882             self.match_simplified_candidates(
883                 span,
884                 start_block,
885                 otherwise_block,
886                 candidates,
887                 fake_borrows,
888             );
889         };
890     }
891
892     fn match_simplified_candidates(
893         &mut self,
894         span: Span,
895         start_block: BasicBlock,
896         otherwise_block: &mut Option<BasicBlock>,
897         candidates: &mut [&mut Candidate<_, 'tcx>],
898         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
899     ) {
900         // The candidates are sorted by priority. Check to see whether the
901         // higher priority candidates (and hence at the front of the slice)
902         // have satisfied all their match pairs.
903         let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
904         debug!("match_candidates: {:?} candidates fully matched", fully_matched);
905         let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
906
907         let block = if !matched_candidates.is_empty() {
908             let otherwise_block =
909                 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
910
911             if let Some(last_otherwise_block) = otherwise_block {
912                 last_otherwise_block
913             } else {
914                 // Any remaining candidates are unreachable.
915                 if unmatched_candidates.is_empty() {
916                     return;
917                 }
918                 self.cfg.start_new_block()
919             }
920         } else {
921             start_block
922         };
923
924         // If there are no candidates that still need testing, we're
925         // done. Since all matches are exhaustive, execution should
926         // never reach this point.
927         if unmatched_candidates.is_empty() {
928             let source_info = self.source_info(span);
929             if let Some(otherwise) = *otherwise_block {
930                 self.cfg.goto(block, source_info, otherwise);
931             } else {
932                 *otherwise_block = Some(block);
933             }
934             return;
935         }
936
937         // Test for the remaining candidates.
938         self.test_candidates_with_or(
939             span,
940             unmatched_candidates,
941             block,
942             otherwise_block,
943             fake_borrows,
944         );
945     }
946
947     /// Link up matched candidates. For example, if we have something like
948     /// this:
949     ///
950     /// ...
951     /// Some(x) if cond => ...
952     /// Some(x) => ...
953     /// Some(x) if cond => ...
954     /// ...
955     ///
956     /// We generate real edges from:
957     /// * `start_block` to the `prebinding_block` of the first pattern,
958     /// * the otherwise block of the first pattern to the second pattern,
959     /// * the otherwise block of the third pattern to the a block with an
960     ///   Unreachable terminator.
961     ///
962     /// As well as that we add fake edges from the otherwise blocks to the
963     /// prebinding block of the next candidate in the original set of
964     /// candidates.
965     fn select_matched_candidates(
966         &mut self,
967         matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
968         start_block: BasicBlock,
969         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
970     ) -> Option<BasicBlock> {
971         debug_assert!(
972             !matched_candidates.is_empty(),
973             "select_matched_candidates called with no candidates",
974         );
975         debug_assert!(
976             matched_candidates.iter().all(|c| c.subcandidates.is_empty()),
977             "subcandidates should be empty in select_matched_candidates",
978         );
979
980         // Insert a borrows of prefixes of places that are bound and are
981         // behind a dereference projection.
982         //
983         // These borrows are taken to avoid situations like the following:
984         //
985         // match x[10] {
986         //     _ if { x = &[0]; false } => (),
987         //     y => (), // Out of bounds array access!
988         // }
989         //
990         // match *x {
991         //     // y is bound by reference in the guard and then by copy in the
992         //     // arm, so y is 2 in the arm!
993         //     y if { y == 1 && (x = &2) == () } => y,
994         //     _ => 3,
995         // }
996         if let Some(fake_borrows) = fake_borrows {
997             for Binding { source, .. } in
998                 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
999             {
1000                 if let Some(i) =
1001                     source.projection.iter().rposition(|elem| *elem == ProjectionElem::Deref)
1002                 {
1003                     let proj_base = &source.projection[..i];
1004
1005                     fake_borrows.insert(Place {
1006                         local: source.local,
1007                         projection: self.hir.tcx().intern_place_elems(proj_base),
1008                     });
1009                 }
1010             }
1011         }
1012
1013         let fully_matched_with_guard = matched_candidates
1014             .iter()
1015             .position(|c| !c.needs_otherwise_block)
1016             .unwrap_or(matched_candidates.len() - 1);
1017
1018         let (reachable_candidates, unreachable_candidates) =
1019             matched_candidates.split_at_mut(fully_matched_with_guard + 1);
1020
1021         let mut next_prebinding = start_block;
1022
1023         for candidate in reachable_candidates.iter_mut() {
1024             assert!(candidate.otherwise_block.is_none());
1025             assert!(candidate.pre_binding_block.is_none());
1026             candidate.pre_binding_block = Some(next_prebinding);
1027             if candidate.needs_otherwise_block {
1028                 next_prebinding = self.cfg.start_new_block();
1029                 candidate.otherwise_block = Some(next_prebinding);
1030             }
1031         }
1032
1033         debug!(
1034             "match_candidates: add pre_binding_blocks for unreachable {:?}",
1035             unreachable_candidates,
1036         );
1037         for candidate in unreachable_candidates {
1038             assert!(candidate.pre_binding_block.is_none());
1039             candidate.pre_binding_block = Some(self.cfg.start_new_block());
1040         }
1041
1042         reachable_candidates.last_mut().unwrap().otherwise_block
1043     }
1044
1045     fn test_candidates_with_or(
1046         &mut self,
1047         span: Span,
1048         candidates: &mut [&mut Candidate<'_, 'tcx>],
1049         block: BasicBlock,
1050         otherwise_block: &mut Option<BasicBlock>,
1051         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1052     ) {
1053         let (first_candidate, remaining_candidates) = candidates.split_first_mut().unwrap();
1054
1055         if let PatKind::Or { .. } = *first_candidate.match_pairs[0].pattern.kind {
1056             let match_pairs = mem::take(&mut first_candidate.match_pairs);
1057             first_candidate.needs_otherwise_block = true;
1058             first_candidate.pre_binding_block = Some(block);
1059
1060             // We sort or-patterns to the end in `simplify_candidate`, so all
1061             // the remaining match pairs are or-patterns.
1062             for match_pair in match_pairs {
1063                 if let PatKind::Or { ref pats } = *match_pair.pattern.kind {
1064                     let or_span = match_pair.pattern.span;
1065                     let place = &match_pair.place;
1066
1067                     first_candidate.visit_leaves(|leaf_candidate| {
1068                         self.test_or_pattern(leaf_candidate, pats, or_span, place, fake_borrows);
1069                     });
1070                 } else {
1071                     bug!("Or patterns should have been sorted to the end");
1072                 }
1073             }
1074             let remainder_start =
1075                 first_candidate.otherwise_block.unwrap_or_else(|| self.cfg.start_new_block());
1076             self.match_candidates(
1077                 span,
1078                 remainder_start,
1079                 otherwise_block,
1080                 remaining_candidates,
1081                 fake_borrows,
1082             )
1083         } else {
1084             self.test_candidates(span, candidates, block, otherwise_block, fake_borrows)
1085         }
1086     }
1087
1088     fn test_or_pattern<'pat>(
1089         &mut self,
1090         candidate: &mut Candidate<'pat, 'tcx>,
1091         pats: &'pat [Pat<'tcx>],
1092         or_span: Span,
1093         place: &Place<'tcx>,
1094         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1095     ) {
1096         debug!("test_or_pattern:\ncandidate={:#?}\npats={:#?}", candidate, pats);
1097         let mut or_candidates: Vec<_> = pats
1098             .iter()
1099             .map(|pat| {
1100                 let new_match_pair = smallvec![MatchPair { pattern: pat, place: place.clone() }];
1101                 Candidate {
1102                     span: pat.span,
1103                     has_guard: candidate.has_guard,
1104                     needs_otherwise_block: candidate.needs_otherwise_block,
1105                     match_pairs: new_match_pair,
1106                     bindings: Vec::new(),
1107                     ascriptions: Vec::new(),
1108                     otherwise_block: None,
1109                     pre_binding_block: None,
1110                     next_candidate_pre_binding_block: None,
1111                     subcandidates: Vec::new(),
1112                 }
1113             })
1114             .collect();
1115         let mut or_candidate_refs: Vec<_> = or_candidates.iter_mut().collect();
1116         self.match_candidates(
1117             or_span,
1118             candidate.pre_binding_block.unwrap(),
1119             &mut candidate.otherwise_block,
1120             &mut or_candidate_refs,
1121             fake_borrows,
1122         );
1123         candidate.subcandidates = or_candidates;
1124         self.merge_trivial_subcandidates(candidate, self.source_info(or_span));
1125     }
1126
1127     /// Try to merge all of the subcandidates of the given candidate into one.
1128     /// This avoids exponentially large CFGs in cases like `(1 | 2, 3 | 4, ...)`.
1129     fn merge_trivial_subcandidates(
1130         &mut self,
1131         candidate: &mut Candidate<'_, 'tcx>,
1132         source_info: SourceInfo,
1133     ) {
1134         if candidate.subcandidates.is_empty() {
1135             return;
1136         }
1137         let mut can_merge = !candidate.has_guard;
1138
1139         // Not `Iterator::all` because we don't want to short-circuit.
1140         for subcandidate in &mut candidate.subcandidates {
1141             self.merge_trivial_subcandidates(subcandidate, source_info);
1142
1143             // FIXME(or_patterns; matthewjasper) Try to be more aggressive here.
1144             can_merge &= subcandidate.subcandidates.is_empty()
1145                 && subcandidate.bindings.is_empty()
1146                 && subcandidate.ascriptions.is_empty();
1147         }
1148
1149         if can_merge {
1150             let any_matches = self.cfg.start_new_block();
1151             for subcandidate in mem::take(&mut candidate.subcandidates) {
1152                 let or_block = subcandidate.pre_binding_block.unwrap();
1153                 self.cfg.goto(or_block, source_info, any_matches);
1154             }
1155             candidate.pre_binding_block = Some(any_matches);
1156         }
1157     }
1158
1159     /// This is the most subtle part of the matching algorithm. At
1160     /// this point, the input candidates have been fully simplified,
1161     /// and so we know that all remaining match-pairs require some
1162     /// sort of test. To decide what test to do, we take the highest
1163     /// priority candidate (last one in the list) and extract the
1164     /// first match-pair from the list. From this we decide what kind
1165     /// of test is needed using `test`, defined in the `test` module.
1166     ///
1167     /// *Note:* taking the first match pair is somewhat arbitrary, and
1168     /// we might do better here by choosing more carefully what to
1169     /// test.
1170     ///
1171     /// For example, consider the following possible match-pairs:
1172     ///
1173     /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
1174     /// 2. `x @ 22` -- we will do a `SwitchInt`
1175     /// 3. `x @ 3..5` -- we will do a range test
1176     /// 4. etc.
1177     ///
1178     /// Once we know what sort of test we are going to perform, this
1179     /// Tests may also help us with other candidates. So we walk over
1180     /// the candidates (from high to low priority) and check. This
1181     /// gives us, for each outcome of the test, a transformed list of
1182     /// candidates. For example, if we are testing the current
1183     /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
1184     /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
1185     /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
1186     /// simpler (and, in fact, irrefutable).
1187     ///
1188     /// But there may also be candidates that the test just doesn't
1189     /// apply to. The classical example involves wildcards:
1190     ///
1191     /// ```
1192     /// # let (x, y, z) = (true, true, true);
1193     /// match (x, y, z) {
1194     ///     (true, _, true) => true,    // (0)
1195     ///     (_, true, _) => true,       // (1)
1196     ///     (false, false, _) => false, // (2)
1197     ///     (true, _, false) => false,  // (3)
1198     /// }
1199     /// ```
1200     ///
1201     /// In that case, after we test on `x`, there are 2 overlapping candidate
1202     /// sets:
1203     ///
1204     /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1205     /// - If the outcome is that `x` is false, candidates 1 and 2
1206     ///
1207     /// Here, the traditional "decision tree" method would generate 2
1208     /// separate code-paths for the 2 separate cases.
1209     ///
1210     /// In some cases, this duplication can create an exponential amount of
1211     /// code. This is most easily seen by noticing that this method terminates
1212     /// with precisely the reachable arms being reachable - but that problem
1213     /// is trivially NP-complete:
1214     ///
1215     /// ```rust
1216     ///     match (var0, var1, var2, var3, ..) {
1217     ///         (true, _, _, false, true, ...) => false,
1218     ///         (_, true, true, false, _, ...) => false,
1219     ///         (false, _, false, false, _, ...) => false,
1220     ///         ...
1221     ///         _ => true
1222     ///     }
1223     /// ```
1224     ///
1225     /// Here the last arm is reachable only if there is an assignment to
1226     /// the variables that does not match any of the literals. Therefore,
1227     /// compilation would take an exponential amount of time in some cases.
1228     ///
1229     /// That kind of exponential worst-case might not occur in practice, but
1230     /// our simplistic treatment of constants and guards would make it occur
1231     /// in very common situations - for example #29740:
1232     ///
1233     /// ```rust
1234     /// match x {
1235     ///     "foo" if foo_guard => ...,
1236     ///     "bar" if bar_guard => ...,
1237     ///     "baz" if baz_guard => ...,
1238     ///     ...
1239     /// }
1240     /// ```
1241     ///
1242     /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1243     ///
1244     /// It might seem that we would end up with 2 disjoint candidate
1245     /// sets, consisting of the first candidate or the other 3, but our
1246     /// algorithm doesn't reason about "foo" being distinct from the other
1247     /// constants; it considers the latter arms to potentially match after
1248     /// both outcomes, which obviously leads to an exponential amount
1249     /// of tests.
1250     ///
1251     /// To avoid these kinds of problems, our algorithm tries to ensure
1252     /// the amount of generated tests is linear. When we do a k-way test,
1253     /// we return an additional "unmatched" set alongside the obvious `k`
1254     /// sets. When we encounter a candidate that would be present in more
1255     /// than one of the sets, we put it and all candidates below it into the
1256     /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1257     ///
1258     /// After we perform our test, we branch into the appropriate candidate
1259     /// set and recurse with `match_candidates`. These sub-matches are
1260     /// obviously inexhaustive - as we discarded our otherwise set - so
1261     /// we set their continuation to do `match_candidates` on the
1262     /// "unmatched" set (which is again inexhaustive).
1263     ///
1264     /// If you apply this to the above test, you basically wind up
1265     /// with an if-else-if chain, testing each candidate in turn,
1266     /// which is precisely what we want.
1267     ///
1268     /// In addition to avoiding exponential-time blowups, this algorithm
1269     /// also has nice property that each guard and arm is only generated
1270     /// once.
1271     fn test_candidates<'pat, 'b, 'c>(
1272         &mut self,
1273         span: Span,
1274         mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1275         block: BasicBlock,
1276         otherwise_block: &mut Option<BasicBlock>,
1277         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1278     ) {
1279         // extract the match-pair from the highest priority candidate
1280         let match_pair = &candidates.first().unwrap().match_pairs[0];
1281         let mut test = self.test(match_pair);
1282         let match_place = match_pair.place;
1283
1284         // most of the time, the test to perform is simply a function
1285         // of the main candidate; but for a test like SwitchInt, we
1286         // may want to add cases based on the candidates that are
1287         // available
1288         match test.kind {
1289             TestKind::SwitchInt { switch_ty, ref mut options, ref mut indices } => {
1290                 for candidate in candidates.iter() {
1291                     if !self.add_cases_to_switch(
1292                         &match_place,
1293                         candidate,
1294                         switch_ty,
1295                         options,
1296                         indices,
1297                     ) {
1298                         break;
1299                     }
1300                 }
1301             }
1302             TestKind::Switch { adt_def: _, ref mut variants } => {
1303                 for candidate in candidates.iter() {
1304                     if !self.add_variants_to_switch(&match_place, candidate, variants) {
1305                         break;
1306                     }
1307                 }
1308             }
1309             _ => {}
1310         }
1311
1312         // Insert a Shallow borrow of any places that is switched on.
1313         fake_borrows.as_mut().map(|fb| fb.insert(match_place.clone()));
1314
1315         // perform the test, branching to one of N blocks. For each of
1316         // those N possible outcomes, create a (initially empty)
1317         // vector of candidates. Those are the candidates that still
1318         // apply if the test has that particular outcome.
1319         debug!("match_candidates: test={:?} match_pair={:?}", test, match_pair);
1320         let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1321         target_candidates.resize_with(test.targets(), Default::default);
1322
1323         let total_candidate_count = candidates.len();
1324
1325         // Sort the candidates into the appropriate vector in
1326         // `target_candidates`. Note that at some point we may
1327         // encounter a candidate where the test is not relevant; at
1328         // that point, we stop sorting.
1329         while let Some(candidate) = candidates.first_mut() {
1330             if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1331                 let (candidate, rest) = candidates.split_first_mut().unwrap();
1332                 target_candidates[idx].push(candidate);
1333                 candidates = rest;
1334             } else {
1335                 break;
1336             }
1337         }
1338         // at least the first candidate ought to be tested
1339         assert!(total_candidate_count > candidates.len());
1340         debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1341         debug!("untested_candidates: {}", candidates.len());
1342
1343         // HACK(matthewjasper) This is a closure so that we can let the test
1344         // create its blocks before the rest of the match. This currently
1345         // improves the speed of llvm when optimizing long string literal
1346         // matches
1347         let make_target_blocks = move |this: &mut Self| -> Vec<BasicBlock> {
1348             // The block that we should branch to if none of the
1349             // `target_candidates` match. This is either the block where we
1350             // start matching the untested candidates if there are any,
1351             // otherwise it's the `otherwise_block`.
1352             let remainder_start = &mut None;
1353             let remainder_start =
1354                 if candidates.is_empty() { &mut *otherwise_block } else { remainder_start };
1355
1356             // For each outcome of test, process the candidates that still
1357             // apply. Collect a list of blocks where control flow will
1358             // branch if one of the `target_candidate` sets is not
1359             // exhaustive.
1360             let target_blocks: Vec<_> = target_candidates
1361                 .into_iter()
1362                 .map(|mut candidates| {
1363                     if candidates.len() != 0 {
1364                         let candidate_start = this.cfg.start_new_block();
1365                         this.match_candidates(
1366                             span,
1367                             candidate_start,
1368                             remainder_start,
1369                             &mut *candidates,
1370                             fake_borrows,
1371                         );
1372                         candidate_start
1373                     } else {
1374                         *remainder_start.get_or_insert_with(|| this.cfg.start_new_block())
1375                     }
1376                 })
1377                 .collect();
1378
1379             if !candidates.is_empty() {
1380                 let remainder_start = remainder_start.unwrap_or_else(|| this.cfg.start_new_block());
1381                 this.match_candidates(
1382                     span,
1383                     remainder_start,
1384                     otherwise_block,
1385                     candidates,
1386                     fake_borrows,
1387                 );
1388             };
1389
1390             target_blocks
1391         };
1392
1393         self.perform_test(block, &match_place, &test, make_target_blocks);
1394     }
1395
1396     /// Determine the fake borrows that are needed from a set of places that
1397     /// have to be stable across match guards.
1398     ///
1399     /// Returns a list of places that need a fake borrow and the temporary
1400     /// that's used to store the fake borrow.
1401     ///
1402     /// Match exhaustiveness checking is not able to handle the case where the
1403     /// place being matched on is mutated in the guards. We add "fake borrows"
1404     /// to the guards that prevent any mutation of the place being matched.
1405     /// There are a some subtleties:
1406     ///
1407     /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
1408     ///    reference, the borrow isn't even tracked. As such we have to add fake
1409     ///    borrows of any prefixes of a place
1410     /// 2. We don't want `match x { _ => (), }` to conflict with mutable
1411     ///    borrows of `x`, so we only add fake borrows for places which are
1412     ///    bound or tested by the match.
1413     /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
1414     ///    so we use a special BorrowKind for them.
1415     /// 4. The fake borrows may be of places in inactive variants, so it would
1416     ///    be UB to generate code for them. They therefore have to be removed
1417     ///    by a MIR pass run after borrow checking.
1418     fn calculate_fake_borrows<'b>(
1419         &mut self,
1420         fake_borrows: &'b FxHashSet<Place<'tcx>>,
1421         temp_span: Span,
1422     ) -> Vec<(Place<'tcx>, Local)> {
1423         let tcx = self.hir.tcx();
1424
1425         debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1426
1427         let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1428
1429         // Insert a Shallow borrow of the prefixes of any fake borrows.
1430         for place in fake_borrows {
1431             let mut cursor = place.projection.as_ref();
1432             while let [proj_base @ .., elem] = cursor {
1433                 cursor = proj_base;
1434
1435                 if let ProjectionElem::Deref = elem {
1436                     // Insert a shallow borrow after a deref. For other
1437                     // projections the borrow of prefix_cursor will
1438                     // conflict with any mutation of base.
1439                     all_fake_borrows.push(PlaceRef { local: place.local, projection: proj_base });
1440                 }
1441             }
1442
1443             all_fake_borrows.push(place.as_ref());
1444         }
1445
1446         // Deduplicate and ensure a deterministic order.
1447         all_fake_borrows.sort();
1448         all_fake_borrows.dedup();
1449
1450         debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1451
1452         all_fake_borrows
1453             .into_iter()
1454             .map(|matched_place_ref| {
1455                 let matched_place = Place {
1456                     local: matched_place_ref.local,
1457                     projection: tcx.intern_place_elems(matched_place_ref.projection),
1458                 };
1459                 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1460                 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1461                 let fake_borrow_temp =
1462                     self.local_decls.push(LocalDecl::new_temp(fake_borrow_ty, temp_span));
1463
1464                 (matched_place, fake_borrow_temp)
1465             })
1466             .collect()
1467     }
1468 }
1469
1470 ///////////////////////////////////////////////////////////////////////////
1471 // Pat binding - used for `let` and function parameters as well.
1472
1473 impl<'a, 'tcx> Builder<'a, 'tcx> {
1474     /// Initializes each of the bindings from the candidate by
1475     /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1476     /// any, and then branches to the arm. Returns the block for the case where
1477     /// the guard fails.
1478     ///
1479     /// Note: we do not check earlier that if there is a guard,
1480     /// there cannot be move bindings. We avoid a use-after-move by only
1481     /// moving the binding once the guard has evaluated to true (see below).
1482     fn bind_and_guard_matched_candidate<'pat>(
1483         &mut self,
1484         candidate: Candidate<'pat, 'tcx>,
1485         parent_bindings: &[(Vec<Binding<'tcx>>, Vec<Ascription<'tcx>>)],
1486         guard: Option<(&Guard<'tcx>, region::Scope)>,
1487         fake_borrows: &Vec<(Place<'tcx>, Local)>,
1488         scrutinee_span: Span,
1489     ) -> BasicBlock {
1490         debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1491
1492         debug_assert!(candidate.match_pairs.is_empty());
1493
1494         let candidate_source_info = self.source_info(candidate.span);
1495
1496         let mut block = candidate.pre_binding_block.unwrap();
1497
1498         if candidate.next_candidate_pre_binding_block.is_some() {
1499             let fresh_block = self.cfg.start_new_block();
1500             self.false_edges(
1501                 block,
1502                 fresh_block,
1503                 candidate.next_candidate_pre_binding_block,
1504                 candidate_source_info,
1505             );
1506             block = fresh_block;
1507         }
1508
1509         self.ascribe_types(
1510             block,
1511             parent_bindings
1512                 .iter()
1513                 .flat_map(|(_, ascriptions)| ascriptions)
1514                 .chain(&candidate.ascriptions),
1515         );
1516
1517         // rust-lang/rust#27282: The `autoref` business deserves some
1518         // explanation here.
1519         //
1520         // The intent of the `autoref` flag is that when it is true,
1521         // then any pattern bindings of type T will map to a `&T`
1522         // within the context of the guard expression, but will
1523         // continue to map to a `T` in the context of the arm body. To
1524         // avoid surfacing this distinction in the user source code
1525         // (which would be a severe change to the language and require
1526         // far more revision to the compiler), when `autoref` is true,
1527         // then any occurrence of the identifier in the guard
1528         // expression will automatically get a deref op applied to it.
1529         //
1530         // So an input like:
1531         //
1532         // ```
1533         // let place = Foo::new();
1534         // match place { foo if inspect(foo)
1535         //     => feed(foo), ...  }
1536         // ```
1537         //
1538         // will be treated as if it were really something like:
1539         //
1540         // ```
1541         // let place = Foo::new();
1542         // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1543         //     => { let tmp2 = place; feed(tmp2) }, ... }
1544         //
1545         // And an input like:
1546         //
1547         // ```
1548         // let place = Foo::new();
1549         // match place { ref mut foo if inspect(foo)
1550         //     => feed(foo), ...  }
1551         // ```
1552         //
1553         // will be treated as if it were really something like:
1554         //
1555         // ```
1556         // let place = Foo::new();
1557         // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1558         //     => { let tmp2 = &mut place; feed(tmp2) }, ... }
1559         // ```
1560         //
1561         // In short, any pattern binding will always look like *some*
1562         // kind of `&T` within the guard at least in terms of how the
1563         // MIR-borrowck views it, and this will ensure that guard
1564         // expressions cannot mutate their the match inputs via such
1565         // bindings. (It also ensures that guard expressions can at
1566         // most *copy* values from such bindings; non-Copy things
1567         // cannot be moved via pattern bindings in guard expressions.)
1568         //
1569         // ----
1570         //
1571         // Implementation notes (under assumption `autoref` is true).
1572         //
1573         // To encode the distinction above, we must inject the
1574         // temporaries `tmp1` and `tmp2`.
1575         //
1576         // There are two cases of interest: binding by-value, and binding by-ref.
1577         //
1578         // 1. Binding by-value: Things are simple.
1579         //
1580         //    * Establishing `tmp1` creates a reference into the
1581         //      matched place. This code is emitted by
1582         //      bind_matched_candidate_for_guard.
1583         //
1584         //    * `tmp2` is only initialized "lazily", after we have
1585         //      checked the guard. Thus, the code that can trigger
1586         //      moves out of the candidate can only fire after the
1587         //      guard evaluated to true. This initialization code is
1588         //      emitted by bind_matched_candidate_for_arm.
1589         //
1590         // 2. Binding by-reference: Things are tricky.
1591         //
1592         //    * Here, the guard expression wants a `&&` or `&&mut`
1593         //      into the original input. This means we need to borrow
1594         //      the reference that we create for the arm.
1595         //    * So we eagerly create the reference for the arm and then take a
1596         //      reference to that.
1597         if let Some((guard, region_scope)) = guard {
1598             let tcx = self.hir.tcx();
1599             let bindings = parent_bindings
1600                 .iter()
1601                 .flat_map(|(bindings, _)| bindings)
1602                 .chain(&candidate.bindings);
1603
1604             self.bind_matched_candidate_for_guard(block, bindings.clone());
1605             let guard_frame = GuardFrame {
1606                 locals: bindings.map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode)).collect(),
1607             };
1608             debug!("entering guard building context: {:?}", guard_frame);
1609             self.guard_context.push(guard_frame);
1610
1611             let re_erased = tcx.lifetimes.re_erased;
1612             let scrutinee_source_info = self.source_info(scrutinee_span);
1613             for (place, temp) in fake_borrows {
1614                 let borrow = Rvalue::Ref(re_erased, BorrowKind::Shallow, *place);
1615                 self.cfg.push_assign(block, scrutinee_source_info, &Place::from(*temp), borrow);
1616             }
1617
1618             // the block to branch to if the guard fails; if there is no
1619             // guard, this block is simply unreachable
1620             let guard = match guard {
1621                 Guard::If(e) => self.hir.mirror(e.clone()),
1622             };
1623             let source_info = self.source_info(guard.span);
1624             let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1625             let (post_guard_block, otherwise_post_guard_block) =
1626                 self.test_bool(block, guard, source_info);
1627             let guard_frame = self.guard_context.pop().unwrap();
1628             debug!("Exiting guard building context with locals: {:?}", guard_frame);
1629
1630             for &(_, temp) in fake_borrows {
1631                 let cause = FakeReadCause::ForMatchGuard;
1632                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
1633             }
1634
1635             let otherwise_block = candidate.otherwise_block.unwrap_or_else(|| {
1636                 let unreachable = self.cfg.start_new_block();
1637                 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
1638                 unreachable
1639             });
1640             let outside_scope = self.cfg.start_new_block();
1641             self.exit_scope(
1642                 source_info.span,
1643                 region_scope,
1644                 otherwise_post_guard_block,
1645                 outside_scope,
1646             );
1647             self.false_edges(
1648                 outside_scope,
1649                 otherwise_block,
1650                 candidate.next_candidate_pre_binding_block,
1651                 source_info,
1652             );
1653
1654             // We want to ensure that the matched candidates are bound
1655             // after we have confirmed this candidate *and* any
1656             // associated guard; Binding them on `block` is too soon,
1657             // because that would be before we've checked the result
1658             // from the guard.
1659             //
1660             // But binding them on the arm is *too late*, because
1661             // then all of the candidates for a single arm would be
1662             // bound in the same place, that would cause a case like:
1663             //
1664             // ```rust
1665             // match (30, 2) {
1666             //     (mut x, 1) | (2, mut x) if { true } => { ... }
1667             //     ...                                 // ^^^^^^^ (this is `arm_block`)
1668             // }
1669             // ```
1670             //
1671             // would yield a `arm_block` something like:
1672             //
1673             // ```
1674             // StorageLive(_4);        // _4 is `x`
1675             // _4 = &mut (_1.0: i32);  // this is handling `(mut x, 1)` case
1676             // _4 = &mut (_1.1: i32);  // this is handling `(2, mut x)` case
1677             // ```
1678             //
1679             // and that is clearly not correct.
1680             let by_value_bindings =
1681                 parent_bindings
1682                     .iter()
1683                     .flat_map(|(bindings, _)| bindings)
1684                     .chain(&candidate.bindings)
1685                     .filter(|binding| {
1686                         if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1687                     });
1688             // Read all of the by reference bindings to ensure that the
1689             // place they refer to can't be modified by the guard.
1690             for binding in by_value_bindings.clone() {
1691                 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1692                 let cause = FakeReadCause::ForGuardBinding;
1693                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
1694             }
1695             self.bind_matched_candidate_for_arm_body(post_guard_block, by_value_bindings);
1696
1697             post_guard_block
1698         } else {
1699             // (Here, it is not too early to bind the matched
1700             // candidate on `block`, because there is no guard result
1701             // that we have to inspect before we bind them.)
1702             self.bind_matched_candidate_for_arm_body(
1703                 block,
1704                 parent_bindings
1705                     .iter()
1706                     .flat_map(|(bindings, _)| bindings)
1707                     .chain(&candidate.bindings),
1708             );
1709             block
1710         }
1711     }
1712
1713     /// Append `AscribeUserType` statements onto the end of `block`
1714     /// for each ascription
1715     fn ascribe_types<'b>(
1716         &mut self,
1717         block: BasicBlock,
1718         ascriptions: impl IntoIterator<Item = &'b Ascription<'tcx>>,
1719     ) where
1720         'tcx: 'b,
1721     {
1722         for ascription in ascriptions {
1723             let source_info = self.source_info(ascription.span);
1724
1725             debug!(
1726                 "adding user ascription at span {:?} of place {:?} and {:?}",
1727                 source_info.span, ascription.source, ascription.user_ty,
1728             );
1729
1730             let user_ty = ascription.user_ty.clone().user_ty(
1731                 &mut self.canonical_user_type_annotations,
1732                 ascription.source.ty(&self.local_decls, self.hir.tcx()).ty,
1733                 source_info.span,
1734             );
1735             self.cfg.push(
1736                 block,
1737                 Statement {
1738                     source_info,
1739                     kind: StatementKind::AscribeUserType(
1740                         box (ascription.source, user_ty),
1741                         ascription.variance,
1742                     ),
1743                 },
1744             );
1745         }
1746     }
1747
1748     fn bind_matched_candidate_for_guard<'b>(
1749         &mut self,
1750         block: BasicBlock,
1751         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1752     ) where
1753         'tcx: 'b,
1754     {
1755         debug!("bind_matched_candidate_for_guard(block={:?})", block);
1756
1757         // Assign each of the bindings. Since we are binding for a
1758         // guard expression, this will never trigger moves out of the
1759         // candidate.
1760         let re_erased = self.hir.tcx().lifetimes.re_erased;
1761         for binding in bindings {
1762             debug!("bind_matched_candidate_for_guard(binding={:?})", binding);
1763             let source_info = self.source_info(binding.span);
1764
1765             // For each pattern ident P of type T, `ref_for_guard` is
1766             // a reference R: &T pointing to the location matched by
1767             // the pattern, and every occurrence of P within a guard
1768             // denotes *R.
1769             let ref_for_guard =
1770                 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1771             match binding.binding_mode {
1772                 BindingMode::ByValue => {
1773                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source);
1774                     self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1775                 }
1776                 BindingMode::ByRef(borrow_kind) => {
1777                     let value_for_arm = self.storage_live_binding(
1778                         block,
1779                         binding.var_id,
1780                         binding.span,
1781                         OutsideGuard,
1782                     );
1783
1784                     let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source);
1785                     self.cfg.push_assign(block, source_info, &value_for_arm, rvalue);
1786                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1787                     self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1788                 }
1789             }
1790         }
1791     }
1792
1793     fn bind_matched_candidate_for_arm_body<'b>(
1794         &mut self,
1795         block: BasicBlock,
1796         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1797     ) where
1798         'tcx: 'b,
1799     {
1800         debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1801
1802         let re_erased = self.hir.tcx().lifetimes.re_erased;
1803         // Assign each of the bindings. This may trigger moves out of the candidate.
1804         for binding in bindings {
1805             let source_info = self.source_info(binding.span);
1806             let local =
1807                 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1808             self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1809             let rvalue = match binding.binding_mode {
1810                 BindingMode::ByValue => {
1811                     Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1812                 }
1813                 BindingMode::ByRef(borrow_kind) => {
1814                     Rvalue::Ref(re_erased, borrow_kind, binding.source)
1815                 }
1816             };
1817             self.cfg.push_assign(block, source_info, &local, rvalue);
1818         }
1819     }
1820
1821     /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1822     /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1823     /// first local is a binding for occurrences of `var` in the guard, which
1824     /// will have type `&T`. The second local is a binding for occurrences of
1825     /// `var` in the arm body, which will have type `T`.
1826     fn declare_binding(
1827         &mut self,
1828         source_info: SourceInfo,
1829         visibility_scope: SourceScope,
1830         mutability: Mutability,
1831         name: Name,
1832         mode: BindingMode,
1833         var_id: HirId,
1834         var_ty: Ty<'tcx>,
1835         user_ty: UserTypeProjections,
1836         has_guard: ArmHasGuard,
1837         opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1838         pat_span: Span,
1839     ) {
1840         debug!(
1841             "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1842              visibility_scope={:?}, source_info={:?})",
1843             var_id, name, mode, var_ty, visibility_scope, source_info
1844         );
1845
1846         let tcx = self.hir.tcx();
1847         let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
1848         let binding_mode = match mode {
1849             BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1850             BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1851         };
1852         debug!("declare_binding: user_ty={:?}", user_ty);
1853         let local = LocalDecl::<'tcx> {
1854             mutability,
1855             ty: var_ty,
1856             user_ty,
1857             source_info,
1858             internal: false,
1859             is_block_tail: None,
1860             local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1861                 binding_mode,
1862                 // hypothetically, `visit_bindings` could try to unzip
1863                 // an outermost hir::Ty as we descend, matching up
1864                 // idents in pat; but complex w/ unclear UI payoff.
1865                 // Instead, just abandon providing diagnostic info.
1866                 opt_ty_info: None,
1867                 opt_match_place,
1868                 pat_span,
1869             }))),
1870         };
1871         let for_arm_body = self.local_decls.push(local);
1872         self.var_debug_info.push(VarDebugInfo {
1873             name,
1874             source_info: debug_source_info,
1875             place: for_arm_body.into(),
1876         });
1877         let locals = if has_guard.0 {
1878             let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1879                 // This variable isn't mutated but has a name, so has to be
1880                 // immutable to avoid the unused mut lint.
1881                 mutability: Mutability::Not,
1882                 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
1883                 user_ty: UserTypeProjections::none(),
1884                 source_info,
1885                 internal: false,
1886                 is_block_tail: None,
1887                 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1888             });
1889             self.var_debug_info.push(VarDebugInfo {
1890                 name,
1891                 source_info: debug_source_info,
1892                 place: ref_for_guard.into(),
1893             });
1894             LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
1895         } else {
1896             LocalsForNode::One(for_arm_body)
1897         };
1898         debug!("declare_binding: vars={:?}", locals);
1899         self.var_indices.insert(var_id, locals);
1900     }
1901 }