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