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