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::thir::{self, *};
13 use rustc_data_structures::{
14 fx::{FxHashSet, FxIndexMap},
15 stack::ensure_sufficient_stack,
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;
24 use rustc_target::abi::VariantIdx;
25 use smallvec::{smallvec, SmallVec};
27 // helper functions, broken out by category:
32 use std::borrow::Borrow;
33 use std::convert::TryFrom;
36 impl<'a, 'tcx> Builder<'a, 'tcx> {
37 /// Generates MIR for a `match` expression.
39 /// The MIR that we generate for a match looks like this.
44 /// [ 1. Evaluate Scrutinee (expression being matched on) ]
45 /// [ (fake read of scrutinee) ]
47 /// [ 2. Decision tree -- check discriminants ] <--------+
49 /// | (once a specific arm is chosen) |
51 /// [pre_binding_block] [otherwise_block]
53 /// [ 3. Create "guard bindings" for arm ] |
54 /// [ (create fake borrows) ] |
56 /// [ 4. Execute guard code ] |
57 /// [ (read fake borrows) ] --(guard is false)-----------+
59 /// | (guard results in true)
61 /// [ 5. Create real bindings and execute arm ]
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.
70 /// We generate MIR in the following steps:
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]).
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:
85 /// * From each prebinding block to the next prebinding block.
86 /// * From each otherwise block to the next prebinding block.
89 destination: Place<'tcx>,
90 destination_scope: Option<region::Scope>,
92 mut block: BasicBlock,
93 scrutinee: ExprRef<'tcx>,
96 let scrutinee_span = scrutinee.span();
98 unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,));
100 let mut arm_candidates = self.create_match_candidates(scrutinee_place, &arms);
102 let match_has_guard = arms.iter().any(|arm| arm.guard.is_some());
104 arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::<Vec<_>>();
106 let fake_borrow_temps =
107 self.lower_match_tree(block, scrutinee_span, match_has_guard, &mut candidates);
109 self.lower_match_arms(
115 self.source_info(span),
120 /// Evaluate the scrutinee and add the fake read of it.
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.
135 // HACK(eddyb) Work around the above issue by adding a dummy inspection
136 // of `scrutinee_place`, specifically by applying `ReadForMatch`.
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
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);
147 block.and(scrutinee_place)
150 /// Create the initial `Candidate`s for a `match` expression.
151 fn create_match_candidates<'pat>(
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*.
160 let arm_has_guard = arm.guard.is_some();
161 let arm_candidate = Candidate::new(scrutinee, &arm.pattern, arm_has_guard);
167 /// Create the decision tree for the match expression, starting from `block`.
169 /// Modifies `candidates` to store the bindings and type ascriptions for
172 /// Returns the places that need fake borrows because we bind or test them.
173 fn lower_match_tree<'pat>(
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
183 let mut fake_borrows = if match_has_guard { Some(FxHashSet::default()) } else { None };
185 let mut otherwise = None;
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);
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
195 let source_info = self.source_info(scrutinee_span);
196 self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
199 // Link each leaf candidate to the `pre_binding_block` of the next one.
200 let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None;
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;
207 previous_candidate = Some(leaf_candidate);
211 if let Some(ref borrows) = fake_borrows {
212 self.calculate_fake_borrows(borrows, scrutinee_span)
218 /// Binds the variables and ascribes types for a given `match` arm or
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
224 crate fn bind_pattern(
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>,
234 if candidate.subcandidates.is_empty() {
235 // Avoid generating another `BasicBlock` when we only have one
237 self.bind_and_guard_matched_candidate(
247 // It's helpful to avoid scheduling drops multiple times to save
248 // drop elaboration from having to clean up the extra drops.
250 // If we are in a `let` then we only schedule drops for the first
253 // If we're in a `match` arm then we could have a case like so:
255 // Ok(x) | Err(x) if return => { /* ... */ }
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.
269 &mut |leaf_candidate, parent_bindings| {
270 if let Some(arm_scope) = arm_scope {
271 self.clear_top_scope(arm_scope);
273 let binding_end = self.bind_and_guard_matched_candidate(
282 if arm_scope.is_none() {
283 schedule_drops = false;
285 self.cfg.goto(binding_end, outer_source_info, target_block);
287 |inner_candidate, parent_bindings| {
288 parent_bindings.push((inner_candidate.bindings, inner_candidate.ascriptions));
289 inner_candidate.subcandidates.into_iter()
292 parent_bindings.pop();
300 pub(super) fn expr_into_pattern(
302 mut block: BasicBlock,
303 irrefutable_pat: Pat<'tcx>,
304 initializer: ExprRef<'tcx>,
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, .. } => {
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);
313 unpack!(block = self.into(place, Some(region_scope), block, initializer));
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);
322 // Optimize the case of `let x: T = ...` to write directly
323 // into `x` and then require that `T == typeof(x)`.
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
330 PatKind::AscribeUserType {
334 box PatKind::Binding {
335 mode: BindingMode::ByValue,
343 thir::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
345 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
347 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard, true);
348 unpack!(block = self.into(place, Some(region_scope), block, initializer));
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);
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,
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
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
381 ty::Variance::Invariant,
390 let place = unpack!(block = self.as_place(block, initializer));
391 self.place_into_pattern(block, irrefutable_pat, place, true)
396 crate fn place_into_pattern(
399 irrefutable_pat: Pat<'tcx>,
400 initializer: Place<'tcx>,
401 set_match_place: bool,
403 let mut candidate = Candidate::new(initializer, &irrefutable_pat, false);
405 let fake_borrow_temps =
406 self.lower_match_tree(block, irrefutable_pat.span, false, &mut [&mut candidate]);
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.
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);
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
422 *match_place = Some(initializer);
424 bug!("Let binding to non-user variable.")
427 // All of the subcandidates should bind the same locals, so we
428 // only visit the first one.
429 candidate_ref.subcandidates.get(0)
431 candidate_ref = next;
436 self.source_info(irrefutable_pat.span),
440 irrefutable_pat.span,
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
451 crate fn declare_bindings(
453 mut visibility_scope: Option<SourceScope>,
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(
462 UserTypeProjections::none(),
463 &mut |this, mutability, name, mode, var, span, ty, user_ty| {
464 if visibility_scope.is_none() {
466 Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
468 let source_info = SourceInfo { span, scope: this.source_scope };
469 let visibility_scope = visibility_scope.unwrap();
470 this.declare_binding(
480 opt_match_place.map(|(x, y)| (x.cloned(), y)),
488 crate fn storage_live_binding(
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);
501 self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
503 Place::from(local_id)
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);
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(
518 pattern_user_ty: UserTypeProjections,
531 "visit_primary_bindings: pattern={:?} pattern_user_ty={:?}",
532 pattern, pattern_user_ty
534 match *pattern.kind {
546 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
548 if let Some(subpattern) = subpattern.as_ref() {
549 self.visit_primary_bindings(subpattern, pattern_user_ty, f);
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);
560 for subpattern in slice {
561 self.visit_primary_bindings(
563 pattern_user_ty.clone().subslice(from, to),
567 for subpattern in suffix {
568 self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
572 PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
574 PatKind::Deref { ref subpattern } => {
575 self.visit_primary_bindings(subpattern, pattern_user_ty.deref(), f);
578 PatKind::AscribeUserType {
580 ascription: thir::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
582 // This corresponds to something like
585 // let A::<'a>(_): A<'static> = ...;
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 {
592 user_ty: user_ty.user_ty,
593 inferred_ty: subpattern.ty,
595 let projection = UserTypeProjection {
596 base: self.canonical_user_type_annotations.push(annotation),
599 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
600 self.visit_primary_bindings(subpattern, subpattern_user_ty, f)
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);
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);
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);
632 pub(super) struct Candidate<'pat, 'tcx> {
633 /// `Span` of the original pattern that gave rise to this candidate
636 /// This `Candidate` has a guard.
639 /// All of these must be satisfied...
640 match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
642 /// ...these bindings established...
643 bindings: Vec<Binding<'tcx>>,
645 /// ...and these types asserted...
646 ascriptions: Vec<Ascription<'tcx>>,
648 /// ... and if this is non-empty, one of these subcandidates also has to match ...
649 subcandidates: Vec<Candidate<'pat, 'tcx>>,
651 /// ...and the guard must be evaluated, if false branch to Block...
652 otherwise_block: Option<BasicBlock>,
654 /// ...and the blocks for add false edges between candidates
655 pre_binding_block: Option<BasicBlock>,
656 next_candidate_pre_binding_block: Option<BasicBlock>,
659 impl<'tcx, 'pat> Candidate<'pat, 'tcx> {
660 fn new(place: Place<'tcx>, pattern: &'pat Pat<'tcx>, has_guard: bool) -> Self {
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,
674 /// Visit the leaf candidates (those with no subcandidates) contained in
676 fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
680 &mut move |c, _| visit_leaf(c),
681 move |c, _| c.subcandidates.iter_mut(),
687 /// A depth-first traversal of the `Candidate` and all of its recursive
689 fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>(
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),
696 C: Borrow<Candidate<'pat, 'tcx>>,
697 I: Iterator<Item = C>,
699 if candidate.borrow().subcandidates.is_empty() {
700 visit_leaf(candidate, context)
702 for child in get_children(candidate, context) {
703 traverse_candidate(child, context, visit_leaf, get_children, complete_children);
705 complete_children(context)
709 #[derive(Clone, Debug)]
710 struct Binding<'tcx> {
716 mutability: Mutability,
717 binding_mode: BindingMode,
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> {
727 user_ty: PatTyProj<'tcx>,
728 variance: ty::Variance,
731 #[derive(Clone, Debug)]
732 crate struct MatchPair<'pat, 'tcx> {
736 // ... must match this pattern.
737 pattern: &'pat Pat<'tcx>,
740 #[derive(Clone, Debug, PartialEq)]
741 enum TestKind<'tcx> {
742 /// Test the branches of enum.
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>,
751 /// Test what value an `integer`, `bool` or `char` has.
753 /// The type of the value that we're testing.
755 /// The (ordered) set of values that we test for.
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.
761 /// For `bool` we always generate two edges, one for `true` and one for
763 options: FxIndexMap<&'tcx ty::Const<'tcx>, u128>,
766 /// Test for equality with value, possibly after an unsizing coercion to
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`.
776 /// Test whether the value falls within an inclusive or exclusive range
777 Range(PatRange<'tcx>),
779 /// Test length of the slice is equal to len
780 Len { len: u64, op: BinOp },
784 crate struct Test<'tcx> {
786 kind: TestKind<'tcx>,
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);
794 ///////////////////////////////////////////////////////////////////////////
795 // Main matching algorithm
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.
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.
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.
818 /// If `fake_borrows` is Some, then places which need fake borrows
819 /// will be added to it.
821 /// For an example of a case where we set `otherwise_block`, even for an
822 /// exhaustive match consider:
826 /// (true, true) => (),
827 /// (_, false) => (),
828 /// (false, true) => (),
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>(
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>>>,
846 "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
847 span, candidates, start_block, otherwise_block,
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);
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();
864 for candidate in candidates {
865 candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate));
867 self.match_simplified_candidates(
871 &mut *new_candidates,
875 self.match_simplified_candidates(
886 fn match_simplified_candidates(
889 start_block: BasicBlock,
890 otherwise_block: &mut Option<BasicBlock>,
891 candidates: &mut [&mut Candidate<'_, 'tcx>],
892 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
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);
901 let block = if !matched_candidates.is_empty() {
902 let otherwise_block =
903 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
905 if let Some(last_otherwise_block) = otherwise_block {
908 // Any remaining candidates are unreachable.
909 if unmatched_candidates.is_empty() {
912 self.cfg.start_new_block()
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);
926 *otherwise_block = Some(block);
931 // Test for the remaining candidates.
932 self.test_candidates_with_or(
934 unmatched_candidates,
941 /// Link up matched candidates. For example, if we have something like
946 /// Some(x) if cond => ...
948 /// Some(x) if cond => ...
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.
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
961 fn select_matched_candidates(
963 matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
964 start_block: BasicBlock,
965 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
966 ) -> Option<BasicBlock> {
968 !matched_candidates.is_empty(),
969 "select_matched_candidates called with no candidates",
972 matched_candidates.iter().all(|c| c.subcandidates.is_empty()),
973 "subcandidates should be empty in select_matched_candidates",
976 // Insert a borrows of prefixes of places that are bound and are
977 // behind a dereference projection.
979 // These borrows are taken to avoid situations like the following:
982 // _ if { x = &[0]; false } => (),
983 // y => (), // Out of bounds array access!
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,
992 if let Some(fake_borrows) = fake_borrows {
993 for Binding { source, .. } in
994 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
997 source.projection.iter().rposition(|elem| elem == ProjectionElem::Deref)
999 let proj_base = &source.projection[..i];
1001 fake_borrows.insert(Place {
1002 local: source.local,
1003 projection: self.hir.tcx().intern_place_elems(proj_base),
1009 let fully_matched_with_guard = matched_candidates
1011 .position(|c| !c.has_guard)
1012 .unwrap_or(matched_candidates.len() - 1);
1014 let (reachable_candidates, unreachable_candidates) =
1015 matched_candidates.split_at_mut(fully_matched_with_guard + 1);
1017 let mut next_prebinding = start_block;
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);
1032 "match_candidates: add pre_binding_blocks for unreachable {:?}",
1033 unreachable_candidates,
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());
1040 reachable_candidates.last_mut().unwrap().otherwise_block
1043 /// Tests a candidate where there are only or-patterns left to test, or
1044 /// forwards to [Builder::test_candidates].
1046 /// Given a pattern `(P | Q, R | S)` we (in principle) generate a CFG like
1054 /// +----------------------------------------+------------------------------------+
1057 /// [ P matches ] [ Q matches ] [ otherwise ]
1060 /// [ match R, S ] [ match R, S ] |
1062 /// +--------------+------------+ +--------------+------------+ |
1065 /// [ R matches ] [ S matches ] [otherwise ] [ R matches ] [ S matches ] [otherwise ] |
1067 /// +--------------+------------|------------+--------------+ | |
1069 /// | +----------------------------------------+--------+
1072 /// [ Success ] [ Failure ]
1075 /// In practice there are some complications:
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
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:
1086 /// +---------------+------------+
1088 /// [ P matches ] [ Q matches ] [ otherwise ]
1090 /// +---------------+ |
1096 fn test_candidates_with_or(
1099 candidates: &mut [&mut Candidate<'_, 'tcx>],
1101 otherwise_block: &mut Option<BasicBlock>,
1102 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1104 let (first_candidate, remaining_candidates) = candidates.split_first_mut().unwrap();
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 { .. } => (),
1111 self.test_candidates(span, candidates, block, otherwise_block, fake_borrows);
1116 let match_pairs = mem::take(&mut first_candidate.match_pairs);
1117 first_candidate.pre_binding_block = Some(block);
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;
1125 first_candidate.visit_leaves(|leaf_candidate| {
1126 self.test_or_pattern(
1136 bug!("Or-patterns should have been sorted to the end");
1140 let remainder_start = otherwise.unwrap_or_else(|| self.cfg.start_new_block());
1142 self.match_candidates(
1146 remaining_candidates,
1151 fn test_or_pattern<'pat>(
1153 candidate: &mut Candidate<'pat, 'tcx>,
1154 otherwise: &mut Option<BasicBlock>,
1155 pats: &'pat [Pat<'tcx>],
1158 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
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
1169 self.match_candidates(
1171 candidate.pre_binding_block.unwrap(),
1173 &mut or_candidate_refs,
1176 candidate.subcandidates = or_candidates;
1177 self.merge_trivial_subcandidates(candidate, self.source_info(or_span));
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(
1184 candidate: &mut Candidate<'_, 'tcx>,
1185 source_info: SourceInfo,
1187 if candidate.subcandidates.is_empty() || candidate.has_guard {
1188 // FIXME(or_patterns; matthewjasper) Don't give up if we have a guard.
1192 let mut can_merge = true;
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);
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();
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);
1210 candidate.pre_binding_block = Some(any_matches);
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.
1222 /// *Note:* taking the first match pair is somewhat arbitrary, and
1223 /// we might do better here by choosing more carefully what to
1226 /// For example, consider the following possible match-pairs:
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
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).
1243 /// But there may also be candidates that the test just doesn't
1244 /// apply to. The classical example involves wildcards:
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)
1256 /// In that case, after we test on `x`, there are 2 overlapping candidate
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
1262 /// Here, the traditional "decision tree" method would generate 2
1263 /// separate code-paths for the 2 separate cases.
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:
1271 /// match (var0, var1, var2, var3, ..) {
1272 /// (true, _, _, false, true, ...) => false,
1273 /// (_, true, true, false, _, ...) => false,
1274 /// (false, _, false, false, _, ...) => false,
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.
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:
1290 /// "foo" if foo_guard => ...,
1291 /// "bar" if bar_guard => ...,
1292 /// "baz" if baz_guard => ...,
1297 /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
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
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.
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).
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.
1323 /// In addition to avoiding exponential-time blowups, this algorithm
1324 /// also has nice property that each guard and arm is only generated
1326 fn test_candidates<'pat, 'b, 'c>(
1329 mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1331 otherwise_block: &mut Option<BasicBlock>,
1332 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
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;
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
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) {
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) {
1361 // Insert a Shallow borrow of any places that is switched on.
1362 if let Some(fb) = fake_borrows {
1363 fb.insert(match_place);
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);
1374 let total_candidate_count = candidates.len();
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);
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());
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
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 };
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
1411 let target_blocks: Vec<_> = target_candidates
1413 .map(|mut candidates| {
1414 if !candidates.is_empty() {
1415 let candidate_start = this.cfg.start_new_block();
1416 this.match_candidates(
1425 *remainder_start.get_or_insert_with(|| this.cfg.start_new_block())
1430 if !candidates.is_empty() {
1431 let remainder_start = remainder_start.unwrap_or_else(|| this.cfg.start_new_block());
1432 this.match_candidates(
1444 self.perform_test(block, match_place, &test, make_target_blocks);
1447 /// Determine the fake borrows that are needed from a set of places that
1448 /// have to be stable across match guards.
1450 /// Returns a list of places that need a fake borrow and the temporary
1451 /// that's used to store the fake borrow.
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:
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>(
1471 fake_borrows: &'b FxHashSet<Place<'tcx>>,
1473 ) -> Vec<(Place<'tcx>, Local)> {
1474 let tcx = self.hir.tcx();
1476 debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1478 let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
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 {
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 });
1494 all_fake_borrows.push(place.as_ref());
1497 // Deduplicate and ensure a deterministic order.
1498 all_fake_borrows.sort();
1499 all_fake_borrows.dedup();
1501 debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
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),
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));
1515 (matched_place, fake_borrow_temp)
1521 ///////////////////////////////////////////////////////////////////////////
1522 // Pat binding - used for `let` and function parameters as well.
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.
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>(
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,
1543 debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1545 debug_assert!(candidate.match_pairs.is_empty());
1547 let candidate_source_info = self.source_info(candidate.span);
1549 let mut block = candidate.pre_binding_block.unwrap();
1551 if candidate.next_candidate_pre_binding_block.is_some() {
1552 let fresh_block = self.cfg.start_new_block();
1556 candidate.next_candidate_pre_binding_block,
1557 candidate_source_info,
1559 block = fresh_block;
1566 .flat_map(|(_, ascriptions)| ascriptions)
1567 .chain(&candidate.ascriptions),
1570 // rust-lang/rust#27282: The `autoref` business deserves some
1571 // explanation here.
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.
1583 // So an input like:
1586 // let place = Foo::new();
1587 // match place { foo if inspect(foo)
1588 // => feed(foo), ... }
1591 // will be treated as if it were really something like:
1594 // let place = Foo::new();
1595 // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1596 // => { let tmp2 = place; feed(tmp2) }, ... }
1598 // And an input like:
1601 // let place = Foo::new();
1602 // match place { ref mut foo if inspect(foo)
1603 // => feed(foo), ... }
1606 // will be treated as if it were really something like:
1609 // let place = Foo::new();
1610 // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1611 // => { let tmp2 = &mut place; feed(tmp2) }, ... }
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.)
1624 // Implementation notes (under assumption `autoref` is true).
1626 // To encode the distinction above, we must inject the
1627 // temporaries `tmp1` and `tmp2`.
1629 // There are two cases of interest: binding by-value, and binding by-ref.
1631 // 1. Binding by-value: Things are simple.
1633 // * Establishing `tmp1` creates a reference into the
1634 // matched place. This code is emitted by
1635 // bind_matched_candidate_for_guard.
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.
1643 // 2. Binding by-reference: Things are tricky.
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
1654 .flat_map(|(bindings, _)| bindings)
1655 .chain(&candidate.bindings);
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(),
1661 debug!("entering guard building context: {:?}", guard_frame);
1662 self.guard_context.push(guard_frame);
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);
1671 let (guard_span, (post_guard_block, otherwise_post_guard_block)) = match guard {
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))
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(
1687 pat.span.to(arm_span.unwrap()),
1690 Some((Some(&scrutinee_place), scrutinee.span())),
1692 let post_guard_block = self.bind_pattern(
1693 self.source_info(pat.span),
1701 let otherwise_post_guard_block = otherwise_candidate.pre_binding_block.unwrap();
1702 (scrutinee_span, (post_guard_block, otherwise_post_guard_block))
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);
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));
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);
1720 let outside_scope = self.cfg.start_new_block();
1721 self.exit_top_scope(otherwise_post_guard_block, outside_scope, source_info);
1725 candidate.next_candidate_pre_binding_block,
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
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:
1741 // (mut x, 1) | (2, mut x) if { true } => { ... }
1742 // ... // ^^^^^^^ (this is `arm_block`)
1746 // would yield a `arm_block` something like:
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
1754 // and that is clearly not correct.
1755 let by_value_bindings = parent_bindings
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));
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);
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(
1780 .flat_map(|(bindings, _)| bindings)
1781 .chain(&candidate.bindings),
1787 /// Append `AscribeUserType` statements onto the end of `block`
1788 /// for each ascription
1789 fn ascribe_types<'b>(
1792 ascriptions: impl IntoIterator<Item = &'b Ascription<'tcx>>,
1796 for ascription in ascriptions {
1797 let source_info = self.source_info(ascription.span);
1800 "adding user ascription at span {:?} of place {:?} and {:?}",
1801 source_info.span, ascription.source, ascription.user_ty,
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,
1813 kind: StatementKind::AscribeUserType(
1814 box (ascription.source, user_ty),
1815 ascription.variance,
1822 fn bind_matched_candidate_for_guard<'b>(
1825 schedule_drops: bool,
1826 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1830 debug!("bind_matched_candidate_for_guard(block={:?})", block);
1832 // Assign each of the bindings. Since we are binding for a
1833 // guard expression, this will never trigger moves out of the
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);
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
1844 let ref_for_guard = self.storage_live_binding(
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);
1856 BindingMode::ByRef(borrow_kind) => {
1857 let value_for_arm = self.storage_live_binding(
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);
1874 fn bind_matched_candidate_for_arm_body<'b>(
1877 schedule_drops: bool,
1878 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1882 debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
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(
1896 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
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)
1904 self.cfg.push_assign(block, source_info, local, rvalue);
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`.
1915 source_info: SourceInfo,
1916 visibility_scope: SourceScope,
1917 mutability: Mutability,
1922 user_ty: UserTypeProjections,
1923 has_guard: ArmHasGuard,
1924 opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
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
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),
1939 debug!("declare_binding: user_ty={:?}", user_ty);
1940 let local = LocalDecl::<'tcx> {
1943 user_ty: if user_ty.is_empty() { None } else { Some(box user_ty) },
1946 is_block_tail: None,
1947 local_info: Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
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.
1960 let for_arm_body = self.local_decls.push(local);
1961 self.var_debug_info.push(VarDebugInfo {
1963 source_info: debug_source_info,
1964 place: for_arm_body.into(),
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),
1975 is_block_tail: None,
1976 local_info: Some(box LocalInfo::User(ClearCrossCrate::Set(
1977 BindingForm::RefForGuard,
1980 self.var_debug_info.push(VarDebugInfo {
1982 source_info: debug_source_info,
1983 place: ref_for_guard.into(),
1985 LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
1987 LocalsForNode::One(for_arm_body)
1989 debug!("declare_binding: vars={:?}", locals);
1990 self.var_indices.insert(var_id, locals);