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.
5 //! This also includes code for pattern bindings in `let` statements and
6 //! function parameters.
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;
15 use rustc::ty::layout::VariantIdx;
16 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty};
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use rustc_index::bit_set::BitSet;
21 use smallvec::{smallvec, SmallVec};
22 use syntax::ast::Name;
24 // helper functions, broken out by category:
29 use itertools::Itertools;
30 use std::convert::TryFrom;
32 impl<'a, 'tcx> Builder<'a, 'tcx> {
33 /// Generates MIR for a `match` expression.
35 /// The MIR that we generate for a match looks like this.
40 /// [ 1. Evaluate Scrutinee (expression being matched on) ]
41 /// [ (fake read of scrutinee) ]
43 /// [ 2. Decision tree -- check discriminants ] <--------+
45 /// | (once a specific arm is chosen) |
47 /// [pre_binding_block] [otherwise_block]
49 /// [ 3. Create "guard bindings" for arm ] |
50 /// [ (create fake borrows) ] |
52 /// [ 4. Execute guard code ] |
53 /// [ (read fake borrows) ] --(guard is false)-----------+
55 /// | (guard results in true)
57 /// [ 5. Create real bindings and execute arm ]
62 /// All of the different arms have been stacked on top of each other to
63 /// simplify the diagram. For an arm with no guard the blocks marked 3 and
64 /// 4 and the fake borrows are omitted.
66 /// We generate MIR in the following steps:
68 /// 1. Evaluate the scrutinee and add the fake read of it ([Builder::lower_scrutinee]).
69 /// 2. Create the prebinding and otherwise blocks ([Builder::create_match_candidates]).
70 /// 3. Create the decision tree ([Builder::lower_match_tree]).
71 /// 4. 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 /// 5. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
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:
82 /// * From each prebinding block to the next prebinding block.
83 /// * From each otherwise block to the next prebinding block.
86 destination: &Place<'tcx>,
88 mut block: BasicBlock,
89 scrutinee: ExprRef<'tcx>,
92 let scrutinee_span = scrutinee.span();
94 unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,));
96 let mut arm_candidates = self.create_match_candidates(&scrutinee_place, &arms);
98 let match_has_guard = arms.iter().any(|arm| arm.guard.is_some());
100 arm_candidates.iter_mut().flat_map(|(_, candidates)| candidates).collect::<Vec<_>>();
102 let fake_borrow_temps =
103 self.lower_match_tree(block, scrutinee_span, match_has_guard, candidates);
105 self.lower_match_arms(
110 self.source_info(span),
115 /// Evaluate the scrutinee and add the fake read of it.
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.
130 // HACK(eddyb) Work around the above issue by adding a dummy inspection
131 // of `scrutinee_place`, specifically by applying `ReadForMatch`.
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
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());
142 block.and(scrutinee_place)
145 /// Create the initial `Candidate`s for a `match` expression.
146 fn create_match_candidates<'pat>(
148 scrutinee: &Place<'tcx>,
149 arms: &'pat [Arm<'tcx>],
150 ) -> Vec<(&'pat Arm<'tcx>, Vec<Candidate<'pat, 'tcx>>)> {
151 let candidate_count = arms.iter().map(|c| c.top_pats_hack().len()).sum::<usize>();
152 let pre_binding_blocks: Vec<_> =
153 (0..candidate_count).map(|_| self.cfg.start_new_block()).collect();
155 let mut candidate_pre_binding_blocks = pre_binding_blocks.iter();
156 let mut next_candidate_pre_binding_blocks = pre_binding_blocks.iter().skip(1);
158 // Assemble a list of candidates: there is one candidate per pattern,
159 // which means there may be more than one candidate *per arm*.
162 let arm_has_guard = arm.guard.is_some();
163 let arm_candidates: Vec<_> = arm
166 .zip(candidate_pre_binding_blocks.by_ref())
167 .map(|(pattern, pre_binding_block)| Candidate {
169 match_pairs: smallvec![MatchPair::new(scrutinee.clone(), pattern)],
172 otherwise_block: if arm_has_guard {
173 Some(self.cfg.start_new_block())
177 pre_binding_block: *pre_binding_block,
178 next_candidate_pre_binding_block: next_candidate_pre_binding_blocks
183 (arm, arm_candidates)
188 /// Create the decision tree for the match expression, starting from `block`.
190 /// Modifies `candidates` to store the bindings and type ascriptions for
193 /// Returns the places that need fake borrows because we bind or test them.
194 fn lower_match_tree<'pat>(
197 scrutinee_span: Span,
198 match_has_guard: bool,
199 mut candidates: Vec<&mut Candidate<'pat, 'tcx>>,
200 ) -> Vec<(Place<'tcx>, Local)> {
201 // The set of places that we are creating fake borrows of. If there are
202 // no match guards then we don't need any fake borrows, so don't track
204 let mut fake_borrows = if match_has_guard { Some(FxHashSet::default()) } else { None };
206 // This will generate code to test scrutinee_place and
207 // branch to the appropriate arm block
208 self.match_candidates(
216 if let Some(ref borrows) = fake_borrows {
217 self.calculate_fake_borrows(borrows, scrutinee_span)
223 /// Lower the bindings, guards and arm bodies of a `match` expression.
225 /// The decision tree should have already been created
226 /// (by [Builder::lower_match_tree]).
228 /// `outer_source_info` is the SourceInfo for the whole match.
231 destination: &Place<'tcx>,
232 scrutinee_place: Place<'tcx>,
233 scrutinee_span: Span,
234 arm_candidates: Vec<(&'_ Arm<'tcx>, Vec<Candidate<'_, 'tcx>>)>,
235 outer_source_info: SourceInfo,
236 fake_borrow_temps: Vec<(Place<'tcx>, Local)>,
238 let match_scope = self.scopes.topmost();
240 let arm_end_blocks: Vec<_> = arm_candidates
242 .map(|(arm, candidates)| {
243 debug!("lowering arm {:?}\ncanidates = {:?}", arm, candidates);
245 let arm_source_info = self.source_info(arm.span);
246 let arm_scope = (arm.scope, arm_source_info);
247 self.in_scope(arm_scope, arm.lint_level, |this| {
248 let body = this.hir.mirror(arm.body.clone());
249 let scope = this.declare_bindings(
252 &arm.top_pats_hack()[0],
253 ArmHasGuard(arm.guard.is_some()),
254 Some((Some(&scrutinee_place), scrutinee_span)),
257 let arm_block = this.bind_pattern(
260 arm.guard.as_ref().map(|g| (g, match_scope)),
266 if let Some(source_scope) = scope {
267 this.source_scope = source_scope;
270 this.into(destination, arm_block, body)
275 // all the arm blocks will rejoin here
276 let end_block = self.cfg.start_new_block();
278 for arm_block in arm_end_blocks {
279 self.cfg.goto(unpack!(arm_block), outer_source_info, end_block);
282 self.source_scope = outer_source_info.scope;
287 /// Binds the variables and ascribes types for a given `match` arm.
289 /// Also check if the guard matches, if it's provided.
292 outer_source_info: SourceInfo,
293 mut candidates: Vec<Candidate<'_, 'tcx>>,
294 guard: Option<(&Guard<'tcx>, region::Scope)>,
295 fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
296 scrutinee_span: Span,
297 arm_scope: region::Scope,
299 if candidates.len() == 1 {
300 // Avoid generating another `BasicBlock` when we only have one
302 self.bind_and_guard_matched_candidate(
303 candidates.pop().unwrap(),
309 let arm_block = self.cfg.start_new_block();
310 for candidate in candidates {
311 // Avoid scheduling drops multiple times.
312 self.clear_top_scope(arm_scope);
313 let binding_end = self.bind_and_guard_matched_candidate(
319 self.cfg.goto(binding_end, outer_source_info, arm_block);
325 pub(super) fn expr_into_pattern(
327 mut block: BasicBlock,
328 irrefutable_pat: Pat<'tcx>,
329 initializer: ExprRef<'tcx>,
331 match *irrefutable_pat.kind {
332 // Optimize the case of `let x = ...` to write directly into `x`
333 PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
335 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
336 unpack!(block = self.into(&place, block, initializer));
338 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
339 let source_info = self.source_info(irrefutable_pat.span);
340 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet, place);
342 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
346 // Optimize the case of `let x: T = ...` to write directly
347 // into `x` and then require that `T == typeof(x)`.
349 // Weirdly, this is needed to prevent the
350 // `intrinsic-move-val.rs` test case from crashing. That
351 // test works with uninitialized values in a rather
352 // dubious way, so it may be that the test is kind of
354 PatKind::AscribeUserType {
358 box PatKind::Binding {
359 mode: BindingMode::ByValue,
367 hair::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
370 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
371 unpack!(block = self.into(&place, block, initializer));
373 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
374 let pattern_source_info = self.source_info(irrefutable_pat.span);
375 let cause_let = FakeReadCause::ForLet;
376 self.cfg.push_fake_read(block, pattern_source_info, cause_let, place.clone());
378 let ty_source_info = self.source_info(user_ty_span);
379 let user_ty = pat_ascription_ty.user_ty(
380 &mut self.canonical_user_type_annotations,
381 place.ty(&self.local_decls, self.hir.tcx()).ty,
387 source_info: ty_source_info,
388 kind: StatementKind::AscribeUserType(
389 box (place, user_ty),
390 // We always use invariant as the variance here. This is because the
391 // variance field from the ascription refers to the variance to use
392 // when applying the type to the value being matched, but this
393 // ascription applies rather to the type of the binding. e.g., in this
400 // We are creating an ascription that defines the type of `x` to be
401 // exactly `T` (i.e., with invariance). The variance field, in
402 // contrast, is intended to be used to relate `T` to the type of
404 ty::Variance::Invariant,
409 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
414 let place = unpack!(block = self.as_place(block, initializer));
415 self.place_into_pattern(block, irrefutable_pat, &place, true)
420 pub fn place_into_pattern(
423 irrefutable_pat: Pat<'tcx>,
424 initializer: &Place<'tcx>,
425 set_match_place: bool,
427 // create a dummy candidate
428 let mut candidate = Candidate {
429 span: irrefutable_pat.span,
430 match_pairs: smallvec![MatchPair::new(initializer.clone(), &irrefutable_pat)],
434 // since we don't call `match_candidates`, next fields are unused
435 otherwise_block: None,
436 pre_binding_block: block,
437 next_candidate_pre_binding_block: None,
440 // Simplify the candidate. Since the pattern is irrefutable, this should
441 // always convert all match-pairs into bindings.
442 self.simplify_candidate(&mut candidate);
444 if !candidate.match_pairs.is_empty() {
445 // ICE if no other errors have been emitted. This used to be a hard error that wouldn't
446 // be reached because `hair::pattern::check_match::check_match` wouldn't have let the
447 // compiler continue. In our tests this is only ever hit by
448 // `ui/consts/const-match-check.rs` with `--cfg eval1`, and that file already generates
449 // a different error before hand.
450 self.hir.tcx().sess.delay_span_bug(
451 candidate.match_pairs[0].pattern.span,
453 "match pairs {:?} remaining after simplifying irrefutable pattern",
454 candidate.match_pairs,
459 // for matches and function arguments, the place that is being matched
460 // can be set when creating the variables. But the place for
461 // let PATTERN = ... might not even exist until we do the assignment.
462 // so we set it here instead
464 for binding in &candidate.bindings {
465 let local = self.var_local_id(binding.var_id, OutsideGuard);
467 if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
468 opt_match_place: Some((ref mut match_place, _)),
470 }))) = self.local_decls[local].local_info
472 *match_place = Some(initializer.clone());
474 bug!("Let binding to non-user variable.")
479 self.ascribe_types(block, &candidate.ascriptions);
481 // now apply the bindings, which will also declare the variables
482 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
487 /// Declares the bindings of the given patterns and returns the visibility
488 /// scope for the bindings in these patterns, if such a scope had to be
489 /// created. NOTE: Declaring the bindings should always be done in their
491 pub fn declare_bindings(
493 mut visibility_scope: Option<SourceScope>,
496 has_guard: ArmHasGuard,
497 opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
498 ) -> Option<SourceScope> {
499 debug!("declare_bindings: pattern={:?}", pattern);
502 UserTypeProjections::none(),
503 &mut |this, mutability, name, mode, var, span, ty, user_ty| {
504 if visibility_scope.is_none() {
506 Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
508 let source_info = SourceInfo { span, scope: this.source_scope };
509 let visibility_scope = visibility_scope.unwrap();
510 this.declare_binding(
520 opt_match_place.map(|(x, y)| (x.cloned(), y)),
528 pub fn storage_live_binding(
535 let local_id = self.var_local_id(var, for_guard);
536 let source_info = self.source_info(span);
537 self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
538 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
539 self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
540 Place::from(local_id)
543 pub fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
544 let local_id = self.var_local_id(var, for_guard);
545 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
546 self.schedule_drop(span, region_scope, local_id, DropKind::Value);
549 pub(super) fn visit_bindings(
552 pattern_user_ty: UserTypeProjections,
564 debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
565 match *pattern.kind {
566 PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, .. } => {
567 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
568 if let Some(subpattern) = subpattern.as_ref() {
569 self.visit_bindings(subpattern, pattern_user_ty, f);
573 PatKind::Array { ref prefix, ref slice, ref suffix }
574 | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
575 let from = u32::try_from(prefix.len()).unwrap();
576 let to = u32::try_from(suffix.len()).unwrap();
577 for subpattern in prefix {
578 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
580 for subpattern in slice {
581 self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
583 for subpattern in suffix {
584 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
588 PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
590 PatKind::Deref { ref subpattern } => {
591 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
594 PatKind::AscribeUserType {
596 ascription: hair::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
598 // This corresponds to something like
601 // let A::<'a>(_): A<'static> = ...;
604 // Note that the variance doesn't apply here, as we are tracking the effect
605 // of `user_ty` on any bindings contained with subpattern.
606 let annotation = CanonicalUserTypeAnnotation {
608 user_ty: user_ty.user_ty,
609 inferred_ty: subpattern.ty,
611 let projection = UserTypeProjection {
612 base: self.canonical_user_type_annotations.push(annotation),
615 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
616 self.visit_bindings(subpattern, subpattern_user_ty, f)
619 PatKind::Leaf { ref subpatterns } => {
620 for subpattern in subpatterns {
621 let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
622 debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
623 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
627 PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
628 for subpattern in subpatterns {
629 let subpattern_user_ty =
630 pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
631 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
634 PatKind::Or { ref pats } => {
636 self.visit_bindings(&pat, pattern_user_ty.clone(), f);
644 pub struct Candidate<'pat, 'tcx> {
645 // span of the original pattern that gave rise to this candidate
648 // all of these must be satisfied...
649 match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
651 // ...these bindings established...
652 bindings: Vec<Binding<'tcx>>,
654 // ...and these types asserted...
655 ascriptions: Vec<Ascription<'tcx>>,
657 // ...and the guard must be evaluated, if false branch to Block...
658 otherwise_block: Option<BasicBlock>,
660 // ...and the blocks for add false edges between candidates
661 pre_binding_block: BasicBlock,
662 next_candidate_pre_binding_block: Option<BasicBlock>,
665 #[derive(Clone, Debug)]
666 struct Binding<'tcx> {
672 mutability: Mutability,
673 binding_mode: BindingMode,
676 /// Indicates that the type of `source` must be a subtype of the
677 /// user-given type `user_ty`; this is basically a no-op but can
678 /// influence region inference.
679 #[derive(Clone, Debug)]
680 struct Ascription<'tcx> {
683 user_ty: PatTyProj<'tcx>,
684 variance: ty::Variance,
687 #[derive(Clone, Debug)]
688 pub struct MatchPair<'pat, 'tcx> {
692 // ... must match this pattern.
693 pattern: &'pat Pat<'tcx>,
696 #[derive(Clone, Debug, PartialEq)]
697 enum TestKind<'tcx> {
698 /// Test the branches of enum.
700 /// The enum being tested
701 adt_def: &'tcx ty::AdtDef,
702 /// The set of variants that we should create a branch for. We also
703 /// create an additional "otherwise" case.
704 variants: BitSet<VariantIdx>,
707 /// Test what value an `integer`, `bool` or `char` has.
709 /// The type of the value that we're testing.
711 /// The (ordered) set of values that we test for.
713 /// For integers and `char`s we create a branch to each of the values in
714 /// `options`, as well as an "otherwise" branch for all other values, even
715 /// in the (rare) case that options is exhaustive.
717 /// For `bool` we always generate two edges, one for `true` and one for
720 /// Reverse map used to ensure that the values in `options` are unique.
721 indices: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
724 /// Test for equality with value, possibly after an unsizing coercion to
727 value: &'tcx ty::Const<'tcx>,
728 // Integer types are handled by `SwitchInt`, and constants with ADT
729 // types are converted back into patterns, so this can only be `&str`,
730 // `&[T]`, `f32` or `f64`.
734 /// Test whether the value falls within an inclusive or exclusive range
735 Range(PatRange<'tcx>),
737 /// Test length of the slice is equal to len
738 Len { len: u64, op: BinOp },
742 pub struct Test<'tcx> {
744 kind: TestKind<'tcx>,
747 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
748 /// a match arm has a guard expression attached to it.
749 #[derive(Copy, Clone, Debug)]
750 pub(crate) struct ArmHasGuard(pub bool);
752 ///////////////////////////////////////////////////////////////////////////
753 // Main matching algorithm
755 impl<'a, 'tcx> Builder<'a, 'tcx> {
756 /// The main match algorithm. It begins with a set of candidates
757 /// `candidates` and has the job of generating code to determine
758 /// which of these candidates, if any, is the correct one. The
759 /// candidates are sorted such that the first item in the list
760 /// has the highest priority. When a candidate is found to match
761 /// the value, we will generate a branch to the appropriate
762 /// prebinding block.
764 /// If we find that *NONE* of the candidates apply, we branch to the
765 /// `otherwise_block`. In principle, this means that the input list was not
766 /// exhaustive, though at present we sometimes are not smart enough to
767 /// recognize all exhaustive inputs.
769 /// It might be surprising that the input can be inexhaustive.
770 /// Indeed, initially, it is not, because all matches are
771 /// exhaustive in Rust. But during processing we sometimes divide
772 /// up the list of candidates and recurse with a non-exhaustive
773 /// list. This is important to keep the size of the generated code
774 /// under control. See `test_candidates` for more details.
776 /// If `fake_borrows` is Some, then places which need fake borrows
777 /// will be added to it.
778 fn match_candidates<'pat>(
781 start_block: &mut Option<BasicBlock>,
782 otherwise_block: Option<BasicBlock>,
783 candidates: &mut [&mut Candidate<'pat, 'tcx>],
784 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
787 "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
788 span, candidates, start_block, otherwise_block,
791 // Start by simplifying candidates. Once this process is complete, all
792 // the match pairs which remain require some form of test, whether it
793 // be a switch or pattern comparison.
794 for candidate in &mut *candidates {
795 self.simplify_candidate(candidate);
798 // The candidates are sorted by priority. Check to see whether the
799 // higher priority candidates (and hence at the front of the slice)
800 // have satisfied all their match pairs.
801 let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
802 debug!("match_candidates: {:?} candidates fully matched", fully_matched);
803 let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
805 let block: BasicBlock = if !matched_candidates.is_empty() {
806 let otherwise_block =
807 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
809 if let Some(last_otherwise_block) = otherwise_block {
812 // Any remaining candidates are unreachable.
813 if unmatched_candidates.is_empty() {
816 self.cfg.start_new_block()
819 *start_block.get_or_insert_with(|| self.cfg.start_new_block())
822 // If there are no candidates that still need testing, we're
823 // done. Since all matches are exhaustive, execution should
824 // never reach this point.
825 if unmatched_candidates.is_empty() {
826 let source_info = self.source_info(span);
827 match otherwise_block {
828 Some(otherwise) => self.cfg.goto(block, source_info, otherwise),
829 None => self.cfg.terminate(block, source_info, TerminatorKind::Unreachable),
834 // Test for the remaining candidates.
835 self.test_candidates(span, unmatched_candidates, block, otherwise_block, fake_borrows);
838 /// Link up matched candidates. For example, if we have something like
842 /// Some(x) if cond => ...
844 /// Some(x) if cond => ...
847 /// We generate real edges from:
848 /// * `start_block` to the `prebinding_block` of the first pattern,
849 /// * the otherwise block of the first pattern to the second pattern,
850 /// * the otherwise block of the third pattern to the a block with an
851 /// Unreachable terminator.
853 /// As well as that we add fake edges from the otherwise blocks to the
854 /// prebinding block of the next candidate in the original set of
856 fn select_matched_candidates(
858 matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
859 start_block: &mut Option<BasicBlock>,
860 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
861 ) -> Option<BasicBlock> {
863 !matched_candidates.is_empty(),
864 "select_matched_candidates called with no candidates",
867 // Insert a borrows of prefixes of places that are bound and are
868 // behind a dereference projection.
870 // These borrows are taken to avoid situations like the following:
873 // _ if { x = &[0]; false } => (),
874 // y => (), // Out of bounds array access!
878 // // y is bound by reference in the guard and then by copy in the
879 // // arm, so y is 2 in the arm!
880 // y if { y == 1 && (x = &2) == () } => y,
883 if let Some(fake_borrows) = fake_borrows {
884 for Binding { source, .. } in
885 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
888 source.projection.iter().rposition(|elem| *elem == ProjectionElem::Deref)
890 let proj_base = &source.projection[..i];
892 fake_borrows.insert(Place {
893 local: source.local.clone(),
894 projection: self.hir.tcx().intern_place_elems(proj_base),
900 let fully_matched_with_guard = matched_candidates
902 .position(|c| c.otherwise_block.is_none())
903 .unwrap_or(matched_candidates.len() - 1);
905 let (reachable_candidates, unreachable_candidates) =
906 matched_candidates.split_at_mut(fully_matched_with_guard + 1);
908 let first_candidate = &reachable_candidates[0];
909 let first_prebinding_block = first_candidate.pre_binding_block;
911 // `goto -> first_prebinding_block` from the `start_block` if there is one.
912 if let Some(start_block) = *start_block {
913 let source_info = self.source_info(first_candidate.span);
914 self.cfg.goto(start_block, source_info, first_prebinding_block);
916 *start_block = Some(first_prebinding_block);
919 for (first_candidate, second_candidate) in reachable_candidates.iter().tuple_windows() {
920 let source_info = self.source_info(first_candidate.span);
921 if let Some(otherwise_block) = first_candidate.otherwise_block {
924 second_candidate.pre_binding_block,
925 first_candidate.next_candidate_pre_binding_block,
929 bug!("candidate other than the last has no guard");
933 debug!("match_candidates: add false edges for unreachable {:?}", unreachable_candidates);
934 for candidate in unreachable_candidates {
935 if let Some(otherwise) = candidate.otherwise_block {
936 let source_info = self.source_info(candidate.span);
937 let unreachable = self.cfg.start_new_block();
941 candidate.next_candidate_pre_binding_block,
944 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
948 let last_candidate = reachable_candidates.last().unwrap();
949 if let Some(otherwise) = last_candidate.otherwise_block {
950 let source_info = self.source_info(last_candidate.span);
951 let block = self.cfg.start_new_block();
955 last_candidate.next_candidate_pre_binding_block,
964 /// This is the most subtle part of the matching algorithm. At
965 /// this point, the input candidates have been fully simplified,
966 /// and so we know that all remaining match-pairs require some
967 /// sort of test. To decide what test to do, we take the highest
968 /// priority candidate (last one in the list) and extract the
969 /// first match-pair from the list. From this we decide what kind
970 /// of test is needed using `test`, defined in the `test` module.
972 /// *Note:* taking the first match pair is somewhat arbitrary, and
973 /// we might do better here by choosing more carefully what to
976 /// For example, consider the following possible match-pairs:
978 /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
979 /// 2. `x @ 22` -- we will do a `SwitchInt`
980 /// 3. `x @ 3..5` -- we will do a range test
983 /// Once we know what sort of test we are going to perform, this
984 /// Tests may also help us with other candidates. So we walk over
985 /// the candidates (from high to low priority) and check. This
986 /// gives us, for each outcome of the test, a transformed list of
987 /// candidates. For example, if we are testing the current
988 /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
989 /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
990 /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
991 /// simpler (and, in fact, irrefutable).
993 /// But there may also be candidates that the test just doesn't
994 /// apply to. The classical example involves wildcards:
997 /// # let (x, y, z) = (true, true, true);
998 /// match (x, y, z) {
999 /// (true, _, true) => true, // (0)
1000 /// (_, true, _) => true, // (1)
1001 /// (false, false, _) => false, // (2)
1002 /// (true, _, false) => false, // (3)
1006 /// In that case, after we test on `x`, there are 2 overlapping candidate
1009 /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1010 /// - If the outcome is that `x` is false, candidates 1 and 2
1012 /// Here, the traditional "decision tree" method would generate 2
1013 /// separate code-paths for the 2 separate cases.
1015 /// In some cases, this duplication can create an exponential amount of
1016 /// code. This is most easily seen by noticing that this method terminates
1017 /// with precisely the reachable arms being reachable - but that problem
1018 /// is trivially NP-complete:
1021 /// match (var0, var1, var2, var3, ..) {
1022 /// (true, _, _, false, true, ...) => false,
1023 /// (_, true, true, false, _, ...) => false,
1024 /// (false, _, false, false, _, ...) => false,
1030 /// Here the last arm is reachable only if there is an assignment to
1031 /// the variables that does not match any of the literals. Therefore,
1032 /// compilation would take an exponential amount of time in some cases.
1034 /// That kind of exponential worst-case might not occur in practice, but
1035 /// our simplistic treatment of constants and guards would make it occur
1036 /// in very common situations - for example #29740:
1040 /// "foo" if foo_guard => ...,
1041 /// "bar" if bar_guard => ...,
1042 /// "baz" if baz_guard => ...,
1047 /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1049 /// It might seem that we would end up with 2 disjoint candidate
1050 /// sets, consisting of the first candidate or the other 3, but our
1051 /// algorithm doesn't reason about "foo" being distinct from the other
1052 /// constants; it considers the latter arms to potentially match after
1053 /// both outcomes, which obviously leads to an exponential amount
1056 /// To avoid these kinds of problems, our algorithm tries to ensure
1057 /// the amount of generated tests is linear. When we do a k-way test,
1058 /// we return an additional "unmatched" set alongside the obvious `k`
1059 /// sets. When we encounter a candidate that would be present in more
1060 /// than one of the sets, we put it and all candidates below it into the
1061 /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1063 /// After we perform our test, we branch into the appropriate candidate
1064 /// set and recurse with `match_candidates`. These sub-matches are
1065 /// obviously inexhaustive - as we discarded our otherwise set - so
1066 /// we set their continuation to do `match_candidates` on the
1067 /// "unmatched" set (which is again inexhaustive).
1069 /// If you apply this to the above test, you basically wind up
1070 /// with an if-else-if chain, testing each candidate in turn,
1071 /// which is precisely what we want.
1073 /// In addition to avoiding exponential-time blowups, this algorithm
1074 /// also has nice property that each guard and arm is only generated
1076 fn test_candidates<'pat, 'b, 'c>(
1079 mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1081 mut otherwise_block: Option<BasicBlock>,
1082 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1084 // extract the match-pair from the highest priority candidate
1085 let match_pair = &candidates.first().unwrap().match_pairs[0];
1086 let mut test = self.test(match_pair);
1087 let match_place = match_pair.place.clone();
1089 // most of the time, the test to perform is simply a function
1090 // of the main candidate; but for a test like SwitchInt, we
1091 // may want to add cases based on the candidates that are
1094 TestKind::SwitchInt { switch_ty, ref mut options, ref mut indices } => {
1095 for candidate in candidates.iter() {
1096 if !self.add_cases_to_switch(
1107 TestKind::Switch { adt_def: _, ref mut variants } => {
1108 for candidate in candidates.iter() {
1109 if !self.add_variants_to_switch(&match_place, candidate, variants) {
1117 // Insert a Shallow borrow of any places that is switched on.
1118 fake_borrows.as_mut().map(|fb| fb.insert(match_place.clone()));
1120 // perform the test, branching to one of N blocks. For each of
1121 // those N possible outcomes, create a (initially empty)
1122 // vector of candidates. Those are the candidates that still
1123 // apply if the test has that particular outcome.
1124 debug!("match_candidates: test={:?} match_pair={:?}", test, match_pair);
1125 let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1126 target_candidates.resize_with(test.targets(), Default::default);
1128 let total_candidate_count = candidates.len();
1130 // Sort the candidates into the appropriate vector in
1131 // `target_candidates`. Note that at some point we may
1132 // encounter a candidate where the test is not relevant; at
1133 // that point, we stop sorting.
1134 while let Some(candidate) = candidates.first_mut() {
1135 if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1136 let (candidate, rest) = candidates.split_first_mut().unwrap();
1137 target_candidates[idx].push(candidate);
1143 // at least the first candidate ought to be tested
1144 assert!(total_candidate_count > candidates.len());
1145 debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1146 debug!("untested_candidates: {}", candidates.len());
1148 // HACK(matthewjasper) This is a closure so that we can let the test
1149 // create its blocks before the rest of the match. This currently
1150 // improves the speed of llvm when optimizing long string literal
1152 let make_target_blocks = move |this: &mut Self| -> Vec<BasicBlock> {
1153 // For each outcome of test, process the candidates that still
1154 // apply. Collect a list of blocks where control flow will
1155 // branch if one of the `target_candidate` sets is not
1157 if !candidates.is_empty() {
1158 let remainder_start = &mut None;
1159 this.match_candidates(
1166 otherwise_block = Some(remainder_start.unwrap());
1171 .map(|mut candidates| {
1172 if candidates.len() != 0 {
1173 let candidate_start = &mut None;
1174 this.match_candidates(
1181 candidate_start.unwrap()
1183 *otherwise_block.get_or_insert_with(|| {
1184 let unreachable = this.cfg.start_new_block();
1185 let source_info = this.source_info(span);
1189 TerminatorKind::Unreachable,
1198 self.perform_test(block, &match_place, &test, make_target_blocks);
1201 /// Determine the fake borrows that are needed from a set of places that
1202 /// have to be stable across match guards.
1204 /// Returns a list of places that need a fake borrow and the temporary
1205 /// that's used to store the fake borrow.
1207 /// Match exhaustiveness checking is not able to handle the case where the
1208 /// place being matched on is mutated in the guards. We add "fake borrows"
1209 /// to the guards that prevent any mutation of the place being matched.
1210 /// There are a some subtleties:
1212 /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
1213 /// reference, the borrow isn't even tracked. As such we have to add fake
1214 /// borrows of any prefixes of a place
1215 /// 2. We don't want `match x { _ => (), }` to conflict with mutable
1216 /// borrows of `x`, so we only add fake borrows for places which are
1217 /// bound or tested by the match.
1218 /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
1219 /// so we use a special BorrowKind for them.
1220 /// 4. The fake borrows may be of places in inactive variants, so it would
1221 /// be UB to generate code for them. They therefore have to be removed
1222 /// by a MIR pass run after borrow checking.
1223 fn calculate_fake_borrows<'b>(
1225 fake_borrows: &'b FxHashSet<Place<'tcx>>,
1227 ) -> Vec<(Place<'tcx>, Local)> {
1228 let tcx = self.hir.tcx();
1230 debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1232 let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1234 // Insert a Shallow borrow of the prefixes of any fake borrows.
1235 for place in fake_borrows {
1236 let mut cursor = place.projection.as_ref();
1237 while let [proj_base @ .., elem] = cursor {
1240 if let ProjectionElem::Deref = elem {
1241 // Insert a shallow borrow after a deref. For other
1242 // projections the borrow of prefix_cursor will
1243 // conflict with any mutation of base.
1244 all_fake_borrows.push(PlaceRef { local: &place.local, projection: proj_base });
1248 all_fake_borrows.push(place.as_ref());
1251 // Deduplicate and ensure a deterministic order.
1252 all_fake_borrows.sort();
1253 all_fake_borrows.dedup();
1255 debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1259 .map(|matched_place_ref| {
1260 let matched_place = Place {
1261 local: matched_place_ref.local.clone(),
1262 projection: tcx.intern_place_elems(matched_place_ref.projection),
1264 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1265 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1266 let fake_borrow_temp =
1267 self.local_decls.push(LocalDecl::new_temp(fake_borrow_ty, temp_span));
1269 (matched_place, fake_borrow_temp)
1275 ///////////////////////////////////////////////////////////////////////////
1276 // Pat binding - used for `let` and function parameters as well.
1278 impl<'a, 'tcx> Builder<'a, 'tcx> {
1279 /// Initializes each of the bindings from the candidate by
1280 /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1281 /// any, and then branches to the arm. Returns the block for the case where
1282 /// the guard fails.
1284 /// Note: we do not check earlier that if there is a guard,
1285 /// there cannot be move bindings. We avoid a use-after-move by only
1286 /// moving the binding once the guard has evaluated to true (see below).
1287 fn bind_and_guard_matched_candidate<'pat>(
1289 candidate: Candidate<'pat, 'tcx>,
1290 guard: Option<(&Guard<'tcx>, region::Scope)>,
1291 fake_borrows: &Vec<(Place<'tcx>, Local)>,
1292 scrutinee_span: Span,
1294 debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1296 debug_assert!(candidate.match_pairs.is_empty());
1298 let candidate_source_info = self.source_info(candidate.span);
1300 let mut block = candidate.pre_binding_block;
1302 // If we are adding our own statements, then we need a fresh block.
1303 let create_fresh_block = candidate.next_candidate_pre_binding_block.is_some()
1304 || !candidate.bindings.is_empty()
1305 || !candidate.ascriptions.is_empty()
1308 if create_fresh_block {
1309 let fresh_block = self.cfg.start_new_block();
1313 candidate.next_candidate_pre_binding_block,
1314 candidate_source_info,
1316 block = fresh_block;
1317 self.ascribe_types(block, &candidate.ascriptions);
1322 // rust-lang/rust#27282: The `autoref` business deserves some
1323 // explanation here.
1325 // The intent of the `autoref` flag is that when it is true,
1326 // then any pattern bindings of type T will map to a `&T`
1327 // within the context of the guard expression, but will
1328 // continue to map to a `T` in the context of the arm body. To
1329 // avoid surfacing this distinction in the user source code
1330 // (which would be a severe change to the language and require
1331 // far more revision to the compiler), when `autoref` is true,
1332 // then any occurrence of the identifier in the guard
1333 // expression will automatically get a deref op applied to it.
1335 // So an input like:
1338 // let place = Foo::new();
1339 // match place { foo if inspect(foo)
1340 // => feed(foo), ... }
1343 // will be treated as if it were really something like:
1346 // let place = Foo::new();
1347 // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1348 // => { let tmp2 = place; feed(tmp2) }, ... }
1350 // And an input like:
1353 // let place = Foo::new();
1354 // match place { ref mut foo if inspect(foo)
1355 // => feed(foo), ... }
1358 // will be treated as if it were really something like:
1361 // let place = Foo::new();
1362 // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1363 // => { let tmp2 = &mut place; feed(tmp2) }, ... }
1366 // In short, any pattern binding will always look like *some*
1367 // kind of `&T` within the guard at least in terms of how the
1368 // MIR-borrowck views it, and this will ensure that guard
1369 // expressions cannot mutate their the match inputs via such
1370 // bindings. (It also ensures that guard expressions can at
1371 // most *copy* values from such bindings; non-Copy things
1372 // cannot be moved via pattern bindings in guard expressions.)
1376 // Implementation notes (under assumption `autoref` is true).
1378 // To encode the distinction above, we must inject the
1379 // temporaries `tmp1` and `tmp2`.
1381 // There are two cases of interest: binding by-value, and binding by-ref.
1383 // 1. Binding by-value: Things are simple.
1385 // * Establishing `tmp1` creates a reference into the
1386 // matched place. This code is emitted by
1387 // bind_matched_candidate_for_guard.
1389 // * `tmp2` is only initialized "lazily", after we have
1390 // checked the guard. Thus, the code that can trigger
1391 // moves out of the candidate can only fire after the
1392 // guard evaluated to true. This initialization code is
1393 // emitted by bind_matched_candidate_for_arm.
1395 // 2. Binding by-reference: Things are tricky.
1397 // * Here, the guard expression wants a `&&` or `&&mut`
1398 // into the original input. This means we need to borrow
1399 // the reference that we create for the arm.
1400 // * So we eagerly create the reference for the arm and then take a
1401 // reference to that.
1402 if let Some((guard, region_scope)) = guard {
1403 let tcx = self.hir.tcx();
1405 self.bind_matched_candidate_for_guard(block, &candidate.bindings);
1406 let guard_frame = GuardFrame {
1410 .map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode))
1413 debug!("entering guard building context: {:?}", guard_frame);
1414 self.guard_context.push(guard_frame);
1416 let re_erased = tcx.lifetimes.re_erased;
1417 let scrutinee_source_info = self.source_info(scrutinee_span);
1418 for (place, temp) in fake_borrows {
1419 let borrow = Rvalue::Ref(re_erased, BorrowKind::Shallow, place.clone());
1420 self.cfg.push_assign(block, scrutinee_source_info, &Place::from(*temp), borrow);
1423 // the block to branch to if the guard fails; if there is no
1424 // guard, this block is simply unreachable
1425 let guard = match guard {
1426 Guard::If(e) => self.hir.mirror(e.clone()),
1428 let source_info = self.source_info(guard.span);
1429 let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1430 let (post_guard_block, otherwise_post_guard_block) =
1431 self.test_bool(block, guard, source_info);
1432 let guard_frame = self.guard_context.pop().unwrap();
1433 debug!("Exiting guard building context with locals: {:?}", guard_frame);
1435 for &(_, temp) in fake_borrows {
1436 let cause = FakeReadCause::ForMatchGuard;
1437 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
1443 otherwise_post_guard_block,
1444 candidate.otherwise_block.unwrap(),
1447 // We want to ensure that the matched candidates are bound
1448 // after we have confirmed this candidate *and* any
1449 // associated guard; Binding them on `block` is too soon,
1450 // because that would be before we've checked the result
1453 // But binding them on the arm is *too late*, because
1454 // then all of the candidates for a single arm would be
1455 // bound in the same place, that would cause a case like:
1459 // (mut x, 1) | (2, mut x) if { true } => { ... }
1460 // ... // ^^^^^^^ (this is `arm_block`)
1464 // would yield a `arm_block` something like:
1467 // StorageLive(_4); // _4 is `x`
1468 // _4 = &mut (_1.0: i32); // this is handling `(mut x, 1)` case
1469 // _4 = &mut (_1.1: i32); // this is handling `(2, mut x)` case
1472 // and that is clearly not correct.
1473 let by_value_bindings = candidate.bindings.iter().filter(|binding| {
1474 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1476 // Read all of the by reference bindings to ensure that the
1477 // place they refer to can't be modified by the guard.
1478 for binding in by_value_bindings.clone() {
1479 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1480 let cause = FakeReadCause::ForGuardBinding;
1481 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
1483 self.bind_matched_candidate_for_arm_body(post_guard_block, by_value_bindings);
1487 assert!(candidate.otherwise_block.is_none());
1488 // (Here, it is not too early to bind the matched
1489 // candidate on `block`, because there is no guard result
1490 // that we have to inspect before we bind them.)
1491 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1496 /// Append `AscribeUserType` statements onto the end of `block`
1497 /// for each ascription
1498 fn ascribe_types(&mut self, block: BasicBlock, ascriptions: &[Ascription<'tcx>]) {
1499 for ascription in ascriptions {
1500 let source_info = self.source_info(ascription.span);
1503 "adding user ascription at span {:?} of place {:?} and {:?}",
1504 source_info.span, ascription.source, ascription.user_ty,
1507 let user_ty = ascription.user_ty.clone().user_ty(
1508 &mut self.canonical_user_type_annotations,
1509 ascription.source.ty(&self.local_decls, self.hir.tcx()).ty,
1516 kind: StatementKind::AscribeUserType(
1517 box (ascription.source.clone(), user_ty),
1518 ascription.variance,
1525 fn bind_matched_candidate_for_guard(&mut self, block: BasicBlock, bindings: &[Binding<'tcx>]) {
1526 debug!("bind_matched_candidate_for_guard(block={:?}, bindings={:?})", block, bindings);
1528 // Assign each of the bindings. Since we are binding for a
1529 // guard expression, this will never trigger moves out of the
1531 let re_erased = self.hir.tcx().lifetimes.re_erased;
1532 for binding in bindings {
1533 let source_info = self.source_info(binding.span);
1535 // For each pattern ident P of type T, `ref_for_guard` is
1536 // a reference R: &T pointing to the location matched by
1537 // the pattern, and every occurrence of P within a guard
1540 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1541 match binding.binding_mode {
1542 BindingMode::ByValue => {
1543 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source.clone());
1544 self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1546 BindingMode::ByRef(borrow_kind) => {
1547 let value_for_arm = self.storage_live_binding(
1554 let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source.clone());
1555 self.cfg.push_assign(block, source_info, &value_for_arm, rvalue);
1556 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1557 self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1563 fn bind_matched_candidate_for_arm_body<'b>(
1566 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1570 debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1572 let re_erased = self.hir.tcx().lifetimes.re_erased;
1573 // Assign each of the bindings. This may trigger moves out of the candidate.
1574 for binding in bindings {
1575 let source_info = self.source_info(binding.span);
1577 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1578 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1579 let rvalue = match binding.binding_mode {
1580 BindingMode::ByValue => {
1581 Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1583 BindingMode::ByRef(borrow_kind) => {
1584 Rvalue::Ref(re_erased, borrow_kind, binding.source.clone())
1587 self.cfg.push_assign(block, source_info, &local, rvalue);
1591 /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1592 /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1593 /// first local is a binding for occurrences of `var` in the guard, which
1594 /// will have type `&T`. The second local is a binding for occurrences of
1595 /// `var` in the arm body, which will have type `T`.
1598 source_info: SourceInfo,
1599 visibility_scope: SourceScope,
1600 mutability: Mutability,
1605 user_ty: UserTypeProjections,
1606 has_guard: ArmHasGuard,
1607 opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1611 "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1612 visibility_scope={:?}, source_info={:?})",
1613 var_id, name, mode, var_ty, visibility_scope, source_info
1616 let tcx = self.hir.tcx();
1617 let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
1618 let binding_mode = match mode {
1619 BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1620 BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1622 debug!("declare_binding: user_ty={:?}", user_ty);
1623 let local = LocalDecl::<'tcx> {
1629 is_block_tail: None,
1630 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1632 // hypothetically, `visit_bindings` could try to unzip
1633 // an outermost hir::Ty as we descend, matching up
1634 // idents in pat; but complex w/ unclear UI payoff.
1635 // Instead, just abandon providing diagnostic info.
1641 let for_arm_body = self.local_decls.push(local);
1642 self.var_debug_info.push(VarDebugInfo {
1644 source_info: debug_source_info,
1645 place: for_arm_body.into(),
1647 let locals = if has_guard.0 {
1648 let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1649 // This variable isn't mutated but has a name, so has to be
1650 // immutable to avoid the unused mut lint.
1651 mutability: Mutability::Not,
1652 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
1653 user_ty: UserTypeProjections::none(),
1656 is_block_tail: None,
1657 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1659 self.var_debug_info.push(VarDebugInfo {
1661 source_info: debug_source_info,
1662 place: ref_for_guard.into(),
1664 LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
1666 LocalsForNode::One(for_arm_body)
1668 debug!("declare_binding: vars={:?}", locals);
1669 self.var_indices.insert(var_id, locals);