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 std::borrow::Borrow;
30 use std::convert::TryFrom;
33 impl<'a, 'tcx> Builder<'a, 'tcx> {
34 /// Generates MIR for a `match` expression.
36 /// The MIR that we generate for a match looks like this.
41 /// [ 1. Evaluate Scrutinee (expression being matched on) ]
42 /// [ (fake read of scrutinee) ]
44 /// [ 2. Decision tree -- check discriminants ] <--------+
46 /// | (once a specific arm is chosen) |
48 /// [pre_binding_block] [otherwise_block]
50 /// [ 3. Create "guard bindings" for arm ] |
51 /// [ (create fake borrows) ] |
53 /// [ 4. Execute guard code ] |
54 /// [ (read fake borrows) ] --(guard is false)-----------+
56 /// | (guard results in true)
58 /// [ 5. Create real bindings and execute arm ]
63 /// All of the different arms have been stacked on top of each other to
64 /// simplify the diagram. For an arm with no guard the blocks marked 3 and
65 /// 4 and the fake borrows are omitted.
67 /// We generate MIR in the following steps:
69 /// 1. Evaluate the scrutinee and add the fake read of it ([Builder::lower_scrutinee]).
70 /// 2. Create the decision tree ([Builder::lower_match_tree]).
71 /// 3. Determine the fake borrows that are needed from the places that were
72 /// matched against and create the required temporaries for them
73 /// ([Builder::calculate_fake_borrows]).
74 /// 4. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
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().map(|(_, candidate)| candidate).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>, Candidate<'pat, 'tcx>)> {
151 // Assemble a list of candidates: there is one candidate per pattern,
152 // which means there may be more than one candidate *per arm*.
155 let arm_has_guard = arm.guard.is_some();
156 let arm_candidate = Candidate {
157 span: arm.pattern.span,
158 match_pairs: smallvec![MatchPair::new(*scrutinee, &arm.pattern),],
161 has_guard: arm_has_guard,
162 needs_otherwise_block: arm_has_guard,
163 otherwise_block: None,
164 pre_binding_block: None,
165 next_candidate_pre_binding_block: None,
166 subcandidates: vec![],
173 /// Create the decision tree for the match expression, starting from `block`.
175 /// Modifies `candidates` to store the bindings and type ascriptions for
178 /// Returns the places that need fake borrows because we bind or test them.
179 fn lower_match_tree<'pat>(
182 scrutinee_span: Span,
183 match_has_guard: bool,
184 mut candidates: Vec<&mut Candidate<'pat, 'tcx>>,
185 ) -> Vec<(Place<'tcx>, Local)> {
186 // The set of places that we are creating fake borrows of. If there are
187 // no match guards then we don't need any fake borrows, so don't track
189 let mut fake_borrows = if match_has_guard { Some(FxHashSet::default()) } else { None };
191 let mut otherwise = None;
193 // This will generate code to test scrutinee_place and
194 // branch to the appropriate arm block
195 self.match_candidates(
203 if let Some(otherwise_block) = otherwise {
204 let source_info = self.source_info(scrutinee_span);
205 self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
208 let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None;
210 for candidate in candidates.into_iter() {
211 candidate.visit_leaves(|leaf_candidate| {
212 if let Some(ref mut prev) = previous_candidate {
213 prev.next_candidate_pre_binding_block = leaf_candidate.pre_binding_block;
215 previous_candidate = Some(leaf_candidate);
219 if let Some(ref borrows) = fake_borrows {
220 self.calculate_fake_borrows(borrows, scrutinee_span)
226 /// Lower the bindings, guards and arm bodies of a `match` expression.
228 /// The decision tree should have already been created
229 /// (by [Builder::lower_match_tree]).
231 /// `outer_source_info` is the SourceInfo for the whole match.
234 destination: &Place<'tcx>,
235 scrutinee_place: Place<'tcx>,
236 scrutinee_span: Span,
237 arm_candidates: Vec<(&'_ Arm<'tcx>, Candidate<'_, 'tcx>)>,
238 outer_source_info: SourceInfo,
239 fake_borrow_temps: Vec<(Place<'tcx>, Local)>,
241 let match_scope = self.scopes.topmost();
243 let arm_end_blocks: Vec<_> = arm_candidates
245 .map(|(arm, candidate)| {
246 debug!("lowering arm {:?}\ncanidate = {:?}", arm, candidate);
248 let arm_source_info = self.source_info(arm.span);
249 let arm_scope = (arm.scope, arm_source_info);
250 self.in_scope(arm_scope, arm.lint_level, |this| {
251 let body = this.hir.mirror(arm.body.clone());
252 let scope = this.declare_bindings(
256 ArmHasGuard(arm.guard.is_some()),
257 Some((Some(&scrutinee_place), scrutinee_span)),
260 let arm_block = this.bind_pattern(
263 arm.guard.as_ref().map(|g| (g, match_scope)),
269 if let Some(source_scope) = scope {
270 this.source_scope = source_scope;
273 this.into(destination, arm_block, body)
278 // all the arm blocks will rejoin here
279 let end_block = self.cfg.start_new_block();
281 for arm_block in arm_end_blocks {
282 self.cfg.goto(unpack!(arm_block), outer_source_info, end_block);
285 self.source_scope = outer_source_info.scope;
290 /// Binds the variables and ascribes types for a given `match` arm.
292 /// Also check if the guard matches, if it's provided.
295 outer_source_info: SourceInfo,
296 candidate: Candidate<'_, 'tcx>,
297 guard: Option<(&Guard<'tcx>, region::Scope)>,
298 fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
299 scrutinee_span: Span,
300 arm_scope: region::Scope,
302 if candidate.subcandidates.is_empty() {
303 // Avoid generating another `BasicBlock` when we only have one
305 self.bind_and_guard_matched_candidate(
313 let target_block = self.cfg.start_new_block();
315 // We keep a stack of all of the bindings and type asciptions
316 // from the the parent candidates that we visit, that also need to
317 // be bound for each candidate.
321 &mut |leaf_candidate, parent_bindings| {
322 self.clear_top_scope(arm_scope);
323 let binding_end = self.bind_and_guard_matched_candidate(
330 self.cfg.goto(binding_end, outer_source_info, target_block);
332 |inner_candidate, parent_bindings| {
333 parent_bindings.push((inner_candidate.bindings, inner_candidate.ascriptions));
334 inner_candidate.subcandidates.into_iter()
337 parent_bindings.pop();
345 pub(super) fn expr_into_pattern(
347 mut block: BasicBlock,
348 irrefutable_pat: Pat<'tcx>,
349 initializer: ExprRef<'tcx>,
351 match *irrefutable_pat.kind {
352 // Optimize the case of `let x = ...` to write directly into `x`
353 PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
355 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
356 unpack!(block = self.into(&place, block, initializer));
358 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
359 let source_info = self.source_info(irrefutable_pat.span);
360 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet, place);
362 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
366 // Optimize the case of `let x: T = ...` to write directly
367 // into `x` and then require that `T == typeof(x)`.
369 // Weirdly, this is needed to prevent the
370 // `intrinsic-move-val.rs` test case from crashing. That
371 // test works with uninitialized values in a rather
372 // dubious way, so it may be that the test is kind of
374 PatKind::AscribeUserType {
378 box PatKind::Binding {
379 mode: BindingMode::ByValue,
387 hair::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
390 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
391 unpack!(block = self.into(&place, block, initializer));
393 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
394 let pattern_source_info = self.source_info(irrefutable_pat.span);
395 let cause_let = FakeReadCause::ForLet;
396 self.cfg.push_fake_read(block, pattern_source_info, cause_let, place.clone());
398 let ty_source_info = self.source_info(user_ty_span);
399 let user_ty = pat_ascription_ty.user_ty(
400 &mut self.canonical_user_type_annotations,
401 place.ty(&self.local_decls, self.hir.tcx()).ty,
407 source_info: ty_source_info,
408 kind: StatementKind::AscribeUserType(
409 box (place, user_ty),
410 // We always use invariant as the variance here. This is because the
411 // variance field from the ascription refers to the variance to use
412 // when applying the type to the value being matched, but this
413 // ascription applies rather to the type of the binding. e.g., in this
420 // We are creating an ascription that defines the type of `x` to be
421 // exactly `T` (i.e., with invariance). The variance field, in
422 // contrast, is intended to be used to relate `T` to the type of
424 ty::Variance::Invariant,
429 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
434 let place = unpack!(block = self.as_place(block, initializer));
435 self.place_into_pattern(block, irrefutable_pat, &place, true)
440 crate fn place_into_pattern(
443 irrefutable_pat: Pat<'tcx>,
444 initializer: &Place<'tcx>,
445 set_match_place: bool,
447 // create a dummy candidate
448 let mut candidate = Candidate {
449 span: irrefutable_pat.span,
451 needs_otherwise_block: false,
452 match_pairs: smallvec![MatchPair::new(*initializer, &irrefutable_pat)],
456 // since we don't call `match_candidates`, next fields are unused
457 otherwise_block: None,
458 pre_binding_block: None,
459 next_candidate_pre_binding_block: None,
460 subcandidates: vec![],
463 // Simplify the candidate. Since the pattern is irrefutable, this should
464 // always convert all match-pairs into bindings.
465 self.simplify_candidate(&mut candidate);
467 if !candidate.match_pairs.is_empty() {
468 // ICE if no other errors have been emitted. This used to be a hard error that wouldn't
469 // be reached because `hair::pattern::check_match::check_match` wouldn't have let the
470 // compiler continue. In our tests this is only ever hit by
471 // `ui/consts/const-match-check.rs` with `--cfg eval1`, and that file already generates
472 // a different error before hand.
473 self.hir.tcx().sess.delay_span_bug(
474 candidate.match_pairs[0].pattern.span,
476 "match pairs {:?} remaining after simplifying irrefutable pattern",
477 candidate.match_pairs,
482 // for matches and function arguments, the place that is being matched
483 // can be set when creating the variables. But the place for
484 // let PATTERN = ... might not even exist until we do the assignment.
485 // so we set it here instead
487 for binding in &candidate.bindings {
488 let local = self.var_local_id(binding.var_id, OutsideGuard);
490 if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
491 opt_match_place: Some((ref mut match_place, _)),
493 }))) = self.local_decls[local].local_info
495 *match_place = Some(*initializer);
497 bug!("Let binding to non-user variable.")
502 self.ascribe_types(block, &candidate.ascriptions);
504 // now apply the bindings, which will also declare the variables
505 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
510 /// Declares the bindings of the given patterns and returns the visibility
511 /// scope for the bindings in these patterns, if such a scope had to be
512 /// created. NOTE: Declaring the bindings should always be done in their
514 crate fn declare_bindings(
516 mut visibility_scope: Option<SourceScope>,
519 has_guard: ArmHasGuard,
520 opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
521 ) -> Option<SourceScope> {
522 debug!("declare_bindings: pattern={:?}", pattern);
525 UserTypeProjections::none(),
526 &mut |this, mutability, name, mode, var, span, ty, user_ty| {
527 if visibility_scope.is_none() {
529 Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
531 let source_info = SourceInfo { span, scope: this.source_scope };
532 let visibility_scope = visibility_scope.unwrap();
533 this.declare_binding(
543 opt_match_place.map(|(x, y)| (x.cloned(), y)),
551 crate fn storage_live_binding(
558 let local_id = self.var_local_id(var, for_guard);
559 let source_info = self.source_info(span);
560 self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
561 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
562 self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
563 Place::from(local_id)
566 crate fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
567 let local_id = self.var_local_id(var, for_guard);
568 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
569 self.schedule_drop(span, region_scope, local_id, DropKind::Value);
572 pub(super) fn visit_bindings(
575 pattern_user_ty: UserTypeProjections,
587 debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
588 match *pattern.kind {
589 PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, .. } => {
590 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
591 if let Some(subpattern) = subpattern.as_ref() {
592 self.visit_bindings(subpattern, pattern_user_ty, f);
596 PatKind::Array { ref prefix, ref slice, ref suffix }
597 | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
598 let from = u32::try_from(prefix.len()).unwrap();
599 let to = u32::try_from(suffix.len()).unwrap();
600 for subpattern in prefix {
601 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
603 for subpattern in slice {
604 self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
606 for subpattern in suffix {
607 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
611 PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
613 PatKind::Deref { ref subpattern } => {
614 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
617 PatKind::AscribeUserType {
619 ascription: hair::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
621 // This corresponds to something like
624 // let A::<'a>(_): A<'static> = ...;
627 // Note that the variance doesn't apply here, as we are tracking the effect
628 // of `user_ty` on any bindings contained with subpattern.
629 let annotation = CanonicalUserTypeAnnotation {
631 user_ty: user_ty.user_ty,
632 inferred_ty: subpattern.ty,
634 let projection = UserTypeProjection {
635 base: self.canonical_user_type_annotations.push(annotation),
638 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
639 self.visit_bindings(subpattern, subpattern_user_ty, f)
642 PatKind::Leaf { ref subpatterns } => {
643 for subpattern in subpatterns {
644 let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
645 debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
646 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
650 PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
651 for subpattern in subpatterns {
652 let subpattern_user_ty =
653 pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
654 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
657 PatKind::Or { ref pats } => {
658 self.visit_bindings(&pats[0], pattern_user_ty.clone(), f);
665 crate struct Candidate<'pat, 'tcx> {
666 /// `Span` of the original pattern that gave rise to this candidate
669 /// This `Candidate` has a guard.
672 /// This `Candidate` needs and otherwise block, either because it has a
673 /// guard or it has subcandidates.
674 needs_otherwise_block: bool,
676 /// All of these must be satisfied...
677 match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
679 /// ...these bindings established...
680 bindings: Vec<Binding<'tcx>>,
682 /// ...and these types asserted...
683 ascriptions: Vec<Ascription<'tcx>>,
685 /// ... and if this is non-empty, one of these subcandidates also has to match ...
686 subcandidates: Vec<Candidate<'pat, 'tcx>>,
688 /// ...and the guard must be evaluated, if false branch to Block...
689 otherwise_block: Option<BasicBlock>,
691 /// ...and the blocks for add false edges between candidates
692 pre_binding_block: Option<BasicBlock>,
693 next_candidate_pre_binding_block: Option<BasicBlock>,
696 impl Candidate<'_, '_> {
697 /// Visit the leaf candidates (those with no subcandidates) contained in
699 fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
703 &mut move |c, _| visit_leaf(c),
704 move |c, _| c.subcandidates.iter_mut(),
710 /// A depth-first traversal of the `Candidate` and all of its recursive
712 fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>(
715 visit_leaf: &mut impl FnMut(C, &mut T),
716 get_children: impl Copy + Fn(C, &mut T) -> I,
717 complete_children: impl Copy + Fn(&mut T),
719 C: Borrow<Candidate<'pat, 'tcx>>,
720 I: Iterator<Item = C>,
722 if candidate.borrow().subcandidates.is_empty() {
723 visit_leaf(candidate, context)
725 for child in get_children(candidate, context) {
726 traverse_candidate(child, context, visit_leaf, get_children, complete_children);
728 complete_children(context)
732 #[derive(Clone, Debug)]
733 struct Binding<'tcx> {
739 mutability: Mutability,
740 binding_mode: BindingMode,
743 /// Indicates that the type of `source` must be a subtype of the
744 /// user-given type `user_ty`; this is basically a no-op but can
745 /// influence region inference.
746 #[derive(Clone, Debug)]
747 struct Ascription<'tcx> {
750 user_ty: PatTyProj<'tcx>,
751 variance: ty::Variance,
754 #[derive(Clone, Debug)]
755 crate struct MatchPair<'pat, 'tcx> {
759 // ... must match this pattern.
760 pattern: &'pat Pat<'tcx>,
763 #[derive(Clone, Debug, PartialEq)]
764 enum TestKind<'tcx> {
765 /// Test the branches of enum.
767 /// The enum being tested
768 adt_def: &'tcx ty::AdtDef,
769 /// The set of variants that we should create a branch for. We also
770 /// create an additional "otherwise" case.
771 variants: BitSet<VariantIdx>,
774 /// Test what value an `integer`, `bool` or `char` has.
776 /// The type of the value that we're testing.
778 /// The (ordered) set of values that we test for.
780 /// For integers and `char`s we create a branch to each of the values in
781 /// `options`, as well as an "otherwise" branch for all other values, even
782 /// in the (rare) case that options is exhaustive.
784 /// For `bool` we always generate two edges, one for `true` and one for
787 /// Reverse map used to ensure that the values in `options` are unique.
788 indices: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
791 /// Test for equality with value, possibly after an unsizing coercion to
794 value: &'tcx ty::Const<'tcx>,
795 // Integer types are handled by `SwitchInt`, and constants with ADT
796 // types are converted back into patterns, so this can only be `&str`,
797 // `&[T]`, `f32` or `f64`.
801 /// Test whether the value falls within an inclusive or exclusive range
802 Range(PatRange<'tcx>),
804 /// Test length of the slice is equal to len
805 Len { len: u64, op: BinOp },
809 crate struct Test<'tcx> {
811 kind: TestKind<'tcx>,
814 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
815 /// a match arm has a guard expression attached to it.
816 #[derive(Copy, Clone, Debug)]
817 crate struct ArmHasGuard(crate bool);
819 ///////////////////////////////////////////////////////////////////////////
820 // Main matching algorithm
822 impl<'a, 'tcx> Builder<'a, 'tcx> {
823 /// The main match algorithm. It begins with a set of candidates
824 /// `candidates` and has the job of generating code to determine
825 /// which of these candidates, if any, is the correct one. The
826 /// candidates are sorted such that the first item in the list
827 /// has the highest priority. When a candidate is found to match
828 /// the value, we will set and generate a branch to the appropriate
829 /// prebinding block.
831 /// If we find that *NONE* of the candidates apply, we branch to the
832 /// `otherwise_block`, setting it to `Some` if required. In principle, this
833 /// means that the input list was not exhaustive, though at present we
834 /// sometimes are not smart enough to recognize all exhaustive inputs.
836 /// It might be surprising that the input can be inexhaustive.
837 /// Indeed, initially, it is not, because all matches are
838 /// exhaustive in Rust. But during processing we sometimes divide
839 /// up the list of candidates and recurse with a non-exhaustive
840 /// list. This is important to keep the size of the generated code
841 /// under control. See `test_candidates` for more details.
843 /// If `fake_borrows` is Some, then places which need fake borrows
844 /// will be added to it.
845 fn match_candidates<'pat>(
848 start_block: BasicBlock,
849 otherwise_block: &mut Option<BasicBlock>,
850 candidates: &mut [&mut Candidate<'pat, 'tcx>],
851 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
854 "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
855 span, candidates, start_block, otherwise_block,
858 // Start by simplifying candidates. Once this process is complete, all
859 // the match pairs which remain require some form of test, whether it
860 // be a switch or pattern comparison.
861 let mut split_or_candidate = false;
862 for candidate in &mut *candidates {
863 split_or_candidate |= self.simplify_candidate(candidate);
866 if split_or_candidate {
867 // At least one of the candidates has been split into subcandidates.
868 // We need to change the candidate list to include those.
869 let mut new_candidates = Vec::new();
871 for candidate in candidates {
872 candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate));
874 self.match_simplified_candidates(
878 &mut *new_candidates,
882 self.match_simplified_candidates(
892 fn match_simplified_candidates(
895 start_block: BasicBlock,
896 otherwise_block: &mut Option<BasicBlock>,
897 candidates: &mut [&mut Candidate<_, 'tcx>],
898 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
900 // The candidates are sorted by priority. Check to see whether the
901 // higher priority candidates (and hence at the front of the slice)
902 // have satisfied all their match pairs.
903 let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
904 debug!("match_candidates: {:?} candidates fully matched", fully_matched);
905 let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
907 let block = if !matched_candidates.is_empty() {
908 let otherwise_block =
909 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
911 if let Some(last_otherwise_block) = otherwise_block {
914 // Any remaining candidates are unreachable.
915 if unmatched_candidates.is_empty() {
918 self.cfg.start_new_block()
924 // If there are no candidates that still need testing, we're
925 // done. Since all matches are exhaustive, execution should
926 // never reach this point.
927 if unmatched_candidates.is_empty() {
928 let source_info = self.source_info(span);
929 if let Some(otherwise) = *otherwise_block {
930 self.cfg.goto(block, source_info, otherwise);
932 *otherwise_block = Some(block);
937 // Test for the remaining candidates.
938 self.test_candidates_with_or(
940 unmatched_candidates,
947 /// Link up matched candidates. For example, if we have something like
951 /// Some(x) if cond => ...
953 /// Some(x) if cond => ...
956 /// We generate real edges from:
957 /// * `start_block` to the `prebinding_block` of the first pattern,
958 /// * the otherwise block of the first pattern to the second pattern,
959 /// * the otherwise block of the third pattern to the a block with an
960 /// Unreachable terminator.
962 /// As well as that we add fake edges from the otherwise blocks to the
963 /// prebinding block of the next candidate in the original set of
965 fn select_matched_candidates(
967 matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
968 start_block: BasicBlock,
969 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
970 ) -> Option<BasicBlock> {
972 !matched_candidates.is_empty(),
973 "select_matched_candidates called with no candidates",
976 matched_candidates.iter().all(|c| c.subcandidates.is_empty()),
977 "subcandidates should be empty in select_matched_candidates",
980 // Insert a borrows of prefixes of places that are bound and are
981 // behind a dereference projection.
983 // These borrows are taken to avoid situations like the following:
986 // _ if { x = &[0]; false } => (),
987 // y => (), // Out of bounds array access!
991 // // y is bound by reference in the guard and then by copy in the
992 // // arm, so y is 2 in the arm!
993 // y if { y == 1 && (x = &2) == () } => y,
996 if let Some(fake_borrows) = fake_borrows {
997 for Binding { source, .. } in
998 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
1001 source.projection.iter().rposition(|elem| *elem == ProjectionElem::Deref)
1003 let proj_base = &source.projection[..i];
1005 fake_borrows.insert(Place {
1006 local: source.local,
1007 projection: self.hir.tcx().intern_place_elems(proj_base),
1013 let fully_matched_with_guard = matched_candidates
1015 .position(|c| !c.needs_otherwise_block)
1016 .unwrap_or(matched_candidates.len() - 1);
1018 let (reachable_candidates, unreachable_candidates) =
1019 matched_candidates.split_at_mut(fully_matched_with_guard + 1);
1021 let mut next_prebinding = start_block;
1023 for candidate in reachable_candidates.iter_mut() {
1024 assert!(candidate.otherwise_block.is_none());
1025 assert!(candidate.pre_binding_block.is_none());
1026 candidate.pre_binding_block = Some(next_prebinding);
1027 if candidate.needs_otherwise_block {
1028 next_prebinding = self.cfg.start_new_block();
1029 candidate.otherwise_block = Some(next_prebinding);
1034 "match_candidates: add pre_binding_blocks for unreachable {:?}",
1035 unreachable_candidates,
1037 for candidate in unreachable_candidates {
1038 assert!(candidate.pre_binding_block.is_none());
1039 candidate.pre_binding_block = Some(self.cfg.start_new_block());
1042 reachable_candidates.last_mut().unwrap().otherwise_block
1045 fn test_candidates_with_or(
1048 candidates: &mut [&mut Candidate<'_, 'tcx>],
1050 otherwise_block: &mut Option<BasicBlock>,
1051 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1053 let (first_candidate, remaining_candidates) = candidates.split_first_mut().unwrap();
1055 if let PatKind::Or { .. } = *first_candidate.match_pairs[0].pattern.kind {
1056 let match_pairs = mem::take(&mut first_candidate.match_pairs);
1057 first_candidate.needs_otherwise_block = true;
1058 first_candidate.pre_binding_block = Some(block);
1060 // We sort or-patterns to the end in `simplify_candidate`, so all
1061 // the remaining match pairs are or-patterns.
1062 for match_pair in match_pairs {
1063 if let PatKind::Or { ref pats } = *match_pair.pattern.kind {
1064 let or_span = match_pair.pattern.span;
1065 let place = &match_pair.place;
1067 first_candidate.visit_leaves(|leaf_candidate| {
1068 self.test_or_pattern(leaf_candidate, pats, or_span, place, fake_borrows);
1071 bug!("Or patterns should have been sorted to the end");
1074 let remainder_start =
1075 first_candidate.otherwise_block.unwrap_or_else(|| self.cfg.start_new_block());
1076 self.match_candidates(
1080 remaining_candidates,
1084 self.test_candidates(span, candidates, block, otherwise_block, fake_borrows)
1088 fn test_or_pattern<'pat>(
1090 candidate: &mut Candidate<'pat, 'tcx>,
1091 pats: &'pat [Pat<'tcx>],
1093 place: &Place<'tcx>,
1094 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1096 debug!("test_or_pattern:\ncandidate={:#?}\npats={:#?}", candidate, pats);
1097 let mut or_candidates: Vec<_> = pats
1100 let new_match_pair = smallvec![MatchPair { pattern: pat, place: place.clone() }];
1103 has_guard: candidate.has_guard,
1104 needs_otherwise_block: candidate.needs_otherwise_block,
1105 match_pairs: new_match_pair,
1106 bindings: Vec::new(),
1107 ascriptions: Vec::new(),
1108 otherwise_block: None,
1109 pre_binding_block: None,
1110 next_candidate_pre_binding_block: None,
1111 subcandidates: Vec::new(),
1115 let mut or_candidate_refs: Vec<_> = or_candidates.iter_mut().collect();
1116 self.match_candidates(
1118 candidate.pre_binding_block.unwrap(),
1119 &mut candidate.otherwise_block,
1120 &mut or_candidate_refs,
1123 candidate.subcandidates = or_candidates;
1124 self.merge_trivial_subcandidates(candidate, self.source_info(or_span));
1127 /// Try to merge all of the subcandidates of the given candidate into one.
1128 /// This avoids exponentially large CFGs in cases like `(1 | 2, 3 | 4, ...)`.
1129 fn merge_trivial_subcandidates(
1131 candidate: &mut Candidate<'_, 'tcx>,
1132 source_info: SourceInfo,
1134 if candidate.subcandidates.is_empty() {
1137 let mut can_merge = !candidate.has_guard;
1139 // Not `Iterator::all` because we don't want to short-circuit.
1140 for subcandidate in &mut candidate.subcandidates {
1141 self.merge_trivial_subcandidates(subcandidate, source_info);
1143 // FIXME(or_patterns; matthewjasper) Try to be more aggressive here.
1144 can_merge &= subcandidate.subcandidates.is_empty()
1145 && subcandidate.bindings.is_empty()
1146 && subcandidate.ascriptions.is_empty();
1150 let any_matches = self.cfg.start_new_block();
1151 for subcandidate in mem::take(&mut candidate.subcandidates) {
1152 let or_block = subcandidate.pre_binding_block.unwrap();
1153 self.cfg.goto(or_block, source_info, any_matches);
1155 candidate.pre_binding_block = Some(any_matches);
1159 /// This is the most subtle part of the matching algorithm. At
1160 /// this point, the input candidates have been fully simplified,
1161 /// and so we know that all remaining match-pairs require some
1162 /// sort of test. To decide what test to do, we take the highest
1163 /// priority candidate (last one in the list) and extract the
1164 /// first match-pair from the list. From this we decide what kind
1165 /// of test is needed using `test`, defined in the `test` module.
1167 /// *Note:* taking the first match pair is somewhat arbitrary, and
1168 /// we might do better here by choosing more carefully what to
1171 /// For example, consider the following possible match-pairs:
1173 /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
1174 /// 2. `x @ 22` -- we will do a `SwitchInt`
1175 /// 3. `x @ 3..5` -- we will do a range test
1178 /// Once we know what sort of test we are going to perform, this
1179 /// Tests may also help us with other candidates. So we walk over
1180 /// the candidates (from high to low priority) and check. This
1181 /// gives us, for each outcome of the test, a transformed list of
1182 /// candidates. For example, if we are testing the current
1183 /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
1184 /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
1185 /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
1186 /// simpler (and, in fact, irrefutable).
1188 /// But there may also be candidates that the test just doesn't
1189 /// apply to. The classical example involves wildcards:
1192 /// # let (x, y, z) = (true, true, true);
1193 /// match (x, y, z) {
1194 /// (true, _, true) => true, // (0)
1195 /// (_, true, _) => true, // (1)
1196 /// (false, false, _) => false, // (2)
1197 /// (true, _, false) => false, // (3)
1201 /// In that case, after we test on `x`, there are 2 overlapping candidate
1204 /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1205 /// - If the outcome is that `x` is false, candidates 1 and 2
1207 /// Here, the traditional "decision tree" method would generate 2
1208 /// separate code-paths for the 2 separate cases.
1210 /// In some cases, this duplication can create an exponential amount of
1211 /// code. This is most easily seen by noticing that this method terminates
1212 /// with precisely the reachable arms being reachable - but that problem
1213 /// is trivially NP-complete:
1216 /// match (var0, var1, var2, var3, ..) {
1217 /// (true, _, _, false, true, ...) => false,
1218 /// (_, true, true, false, _, ...) => false,
1219 /// (false, _, false, false, _, ...) => false,
1225 /// Here the last arm is reachable only if there is an assignment to
1226 /// the variables that does not match any of the literals. Therefore,
1227 /// compilation would take an exponential amount of time in some cases.
1229 /// That kind of exponential worst-case might not occur in practice, but
1230 /// our simplistic treatment of constants and guards would make it occur
1231 /// in very common situations - for example #29740:
1235 /// "foo" if foo_guard => ...,
1236 /// "bar" if bar_guard => ...,
1237 /// "baz" if baz_guard => ...,
1242 /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1244 /// It might seem that we would end up with 2 disjoint candidate
1245 /// sets, consisting of the first candidate or the other 3, but our
1246 /// algorithm doesn't reason about "foo" being distinct from the other
1247 /// constants; it considers the latter arms to potentially match after
1248 /// both outcomes, which obviously leads to an exponential amount
1251 /// To avoid these kinds of problems, our algorithm tries to ensure
1252 /// the amount of generated tests is linear. When we do a k-way test,
1253 /// we return an additional "unmatched" set alongside the obvious `k`
1254 /// sets. When we encounter a candidate that would be present in more
1255 /// than one of the sets, we put it and all candidates below it into the
1256 /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1258 /// After we perform our test, we branch into the appropriate candidate
1259 /// set and recurse with `match_candidates`. These sub-matches are
1260 /// obviously inexhaustive - as we discarded our otherwise set - so
1261 /// we set their continuation to do `match_candidates` on the
1262 /// "unmatched" set (which is again inexhaustive).
1264 /// If you apply this to the above test, you basically wind up
1265 /// with an if-else-if chain, testing each candidate in turn,
1266 /// which is precisely what we want.
1268 /// In addition to avoiding exponential-time blowups, this algorithm
1269 /// also has nice property that each guard and arm is only generated
1271 fn test_candidates<'pat, 'b, 'c>(
1274 mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1276 otherwise_block: &mut Option<BasicBlock>,
1277 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1279 // extract the match-pair from the highest priority candidate
1280 let match_pair = &candidates.first().unwrap().match_pairs[0];
1281 let mut test = self.test(match_pair);
1282 let match_place = match_pair.place;
1284 // most of the time, the test to perform is simply a function
1285 // of the main candidate; but for a test like SwitchInt, we
1286 // may want to add cases based on the candidates that are
1289 TestKind::SwitchInt { switch_ty, ref mut options, ref mut indices } => {
1290 for candidate in candidates.iter() {
1291 if !self.add_cases_to_switch(
1302 TestKind::Switch { adt_def: _, ref mut variants } => {
1303 for candidate in candidates.iter() {
1304 if !self.add_variants_to_switch(&match_place, candidate, variants) {
1312 // Insert a Shallow borrow of any places that is switched on.
1313 fake_borrows.as_mut().map(|fb| fb.insert(match_place.clone()));
1315 // perform the test, branching to one of N blocks. For each of
1316 // those N possible outcomes, create a (initially empty)
1317 // vector of candidates. Those are the candidates that still
1318 // apply if the test has that particular outcome.
1319 debug!("match_candidates: test={:?} match_pair={:?}", test, match_pair);
1320 let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1321 target_candidates.resize_with(test.targets(), Default::default);
1323 let total_candidate_count = candidates.len();
1325 // Sort the candidates into the appropriate vector in
1326 // `target_candidates`. Note that at some point we may
1327 // encounter a candidate where the test is not relevant; at
1328 // that point, we stop sorting.
1329 while let Some(candidate) = candidates.first_mut() {
1330 if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1331 let (candidate, rest) = candidates.split_first_mut().unwrap();
1332 target_candidates[idx].push(candidate);
1338 // at least the first candidate ought to be tested
1339 assert!(total_candidate_count > candidates.len());
1340 debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1341 debug!("untested_candidates: {}", candidates.len());
1343 // HACK(matthewjasper) This is a closure so that we can let the test
1344 // create its blocks before the rest of the match. This currently
1345 // improves the speed of llvm when optimizing long string literal
1347 let make_target_blocks = move |this: &mut Self| -> Vec<BasicBlock> {
1348 // The block that we should branch to if none of the
1349 // `target_candidates` match. This is either the block where we
1350 // start matching the untested candidates if there are any,
1351 // otherwise it's the `otherwise_block`.
1352 let remainder_start = &mut None;
1353 let remainder_start =
1354 if candidates.is_empty() { &mut *otherwise_block } else { remainder_start };
1356 // For each outcome of test, process the candidates that still
1357 // apply. Collect a list of blocks where control flow will
1358 // branch if one of the `target_candidate` sets is not
1360 let target_blocks: Vec<_> = target_candidates
1362 .map(|mut candidates| {
1363 if candidates.len() != 0 {
1364 let candidate_start = this.cfg.start_new_block();
1365 this.match_candidates(
1374 *remainder_start.get_or_insert_with(|| this.cfg.start_new_block())
1379 if !candidates.is_empty() {
1380 let remainder_start = remainder_start.unwrap_or_else(|| this.cfg.start_new_block());
1381 this.match_candidates(
1393 self.perform_test(block, &match_place, &test, make_target_blocks);
1396 /// Determine the fake borrows that are needed from a set of places that
1397 /// have to be stable across match guards.
1399 /// Returns a list of places that need a fake borrow and the temporary
1400 /// that's used to store the fake borrow.
1402 /// Match exhaustiveness checking is not able to handle the case where the
1403 /// place being matched on is mutated in the guards. We add "fake borrows"
1404 /// to the guards that prevent any mutation of the place being matched.
1405 /// There are a some subtleties:
1407 /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
1408 /// reference, the borrow isn't even tracked. As such we have to add fake
1409 /// borrows of any prefixes of a place
1410 /// 2. We don't want `match x { _ => (), }` to conflict with mutable
1411 /// borrows of `x`, so we only add fake borrows for places which are
1412 /// bound or tested by the match.
1413 /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
1414 /// so we use a special BorrowKind for them.
1415 /// 4. The fake borrows may be of places in inactive variants, so it would
1416 /// be UB to generate code for them. They therefore have to be removed
1417 /// by a MIR pass run after borrow checking.
1418 fn calculate_fake_borrows<'b>(
1420 fake_borrows: &'b FxHashSet<Place<'tcx>>,
1422 ) -> Vec<(Place<'tcx>, Local)> {
1423 let tcx = self.hir.tcx();
1425 debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1427 let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1429 // Insert a Shallow borrow of the prefixes of any fake borrows.
1430 for place in fake_borrows {
1431 let mut cursor = place.projection.as_ref();
1432 while let [proj_base @ .., elem] = cursor {
1435 if let ProjectionElem::Deref = elem {
1436 // Insert a shallow borrow after a deref. For other
1437 // projections the borrow of prefix_cursor will
1438 // conflict with any mutation of base.
1439 all_fake_borrows.push(PlaceRef { local: place.local, projection: proj_base });
1443 all_fake_borrows.push(place.as_ref());
1446 // Deduplicate and ensure a deterministic order.
1447 all_fake_borrows.sort();
1448 all_fake_borrows.dedup();
1450 debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1454 .map(|matched_place_ref| {
1455 let matched_place = Place {
1456 local: matched_place_ref.local,
1457 projection: tcx.intern_place_elems(matched_place_ref.projection),
1459 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1460 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1461 let fake_borrow_temp =
1462 self.local_decls.push(LocalDecl::new_temp(fake_borrow_ty, temp_span));
1464 (matched_place, fake_borrow_temp)
1470 ///////////////////////////////////////////////////////////////////////////
1471 // Pat binding - used for `let` and function parameters as well.
1473 impl<'a, 'tcx> Builder<'a, 'tcx> {
1474 /// Initializes each of the bindings from the candidate by
1475 /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1476 /// any, and then branches to the arm. Returns the block for the case where
1477 /// the guard fails.
1479 /// Note: we do not check earlier that if there is a guard,
1480 /// there cannot be move bindings. We avoid a use-after-move by only
1481 /// moving the binding once the guard has evaluated to true (see below).
1482 fn bind_and_guard_matched_candidate<'pat>(
1484 candidate: Candidate<'pat, 'tcx>,
1485 parent_bindings: &[(Vec<Binding<'tcx>>, Vec<Ascription<'tcx>>)],
1486 guard: Option<(&Guard<'tcx>, region::Scope)>,
1487 fake_borrows: &Vec<(Place<'tcx>, Local)>,
1488 scrutinee_span: Span,
1490 debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1492 debug_assert!(candidate.match_pairs.is_empty());
1494 let candidate_source_info = self.source_info(candidate.span);
1496 let mut block = candidate.pre_binding_block.unwrap();
1498 if candidate.next_candidate_pre_binding_block.is_some() {
1499 let fresh_block = self.cfg.start_new_block();
1503 candidate.next_candidate_pre_binding_block,
1504 candidate_source_info,
1506 block = fresh_block;
1513 .flat_map(|(_, ascriptions)| ascriptions)
1514 .chain(&candidate.ascriptions),
1517 // rust-lang/rust#27282: The `autoref` business deserves some
1518 // explanation here.
1520 // The intent of the `autoref` flag is that when it is true,
1521 // then any pattern bindings of type T will map to a `&T`
1522 // within the context of the guard expression, but will
1523 // continue to map to a `T` in the context of the arm body. To
1524 // avoid surfacing this distinction in the user source code
1525 // (which would be a severe change to the language and require
1526 // far more revision to the compiler), when `autoref` is true,
1527 // then any occurrence of the identifier in the guard
1528 // expression will automatically get a deref op applied to it.
1530 // So an input like:
1533 // let place = Foo::new();
1534 // match place { foo if inspect(foo)
1535 // => feed(foo), ... }
1538 // will be treated as if it were really something like:
1541 // let place = Foo::new();
1542 // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1543 // => { let tmp2 = place; feed(tmp2) }, ... }
1545 // And an input like:
1548 // let place = Foo::new();
1549 // match place { ref mut foo if inspect(foo)
1550 // => feed(foo), ... }
1553 // will be treated as if it were really something like:
1556 // let place = Foo::new();
1557 // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1558 // => { let tmp2 = &mut place; feed(tmp2) }, ... }
1561 // In short, any pattern binding will always look like *some*
1562 // kind of `&T` within the guard at least in terms of how the
1563 // MIR-borrowck views it, and this will ensure that guard
1564 // expressions cannot mutate their the match inputs via such
1565 // bindings. (It also ensures that guard expressions can at
1566 // most *copy* values from such bindings; non-Copy things
1567 // cannot be moved via pattern bindings in guard expressions.)
1571 // Implementation notes (under assumption `autoref` is true).
1573 // To encode the distinction above, we must inject the
1574 // temporaries `tmp1` and `tmp2`.
1576 // There are two cases of interest: binding by-value, and binding by-ref.
1578 // 1. Binding by-value: Things are simple.
1580 // * Establishing `tmp1` creates a reference into the
1581 // matched place. This code is emitted by
1582 // bind_matched_candidate_for_guard.
1584 // * `tmp2` is only initialized "lazily", after we have
1585 // checked the guard. Thus, the code that can trigger
1586 // moves out of the candidate can only fire after the
1587 // guard evaluated to true. This initialization code is
1588 // emitted by bind_matched_candidate_for_arm.
1590 // 2. Binding by-reference: Things are tricky.
1592 // * Here, the guard expression wants a `&&` or `&&mut`
1593 // into the original input. This means we need to borrow
1594 // the reference that we create for the arm.
1595 // * So we eagerly create the reference for the arm and then take a
1596 // reference to that.
1597 if let Some((guard, region_scope)) = guard {
1598 let tcx = self.hir.tcx();
1599 let bindings = parent_bindings
1601 .flat_map(|(bindings, _)| bindings)
1602 .chain(&candidate.bindings);
1604 self.bind_matched_candidate_for_guard(block, bindings.clone());
1605 let guard_frame = GuardFrame {
1606 locals: bindings.map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode)).collect(),
1608 debug!("entering guard building context: {:?}", guard_frame);
1609 self.guard_context.push(guard_frame);
1611 let re_erased = tcx.lifetimes.re_erased;
1612 let scrutinee_source_info = self.source_info(scrutinee_span);
1613 for (place, temp) in fake_borrows {
1614 let borrow = Rvalue::Ref(re_erased, BorrowKind::Shallow, *place);
1615 self.cfg.push_assign(block, scrutinee_source_info, &Place::from(*temp), borrow);
1618 // the block to branch to if the guard fails; if there is no
1619 // guard, this block is simply unreachable
1620 let guard = match guard {
1621 Guard::If(e) => self.hir.mirror(e.clone()),
1623 let source_info = self.source_info(guard.span);
1624 let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1625 let (post_guard_block, otherwise_post_guard_block) =
1626 self.test_bool(block, guard, source_info);
1627 let guard_frame = self.guard_context.pop().unwrap();
1628 debug!("Exiting guard building context with locals: {:?}", guard_frame);
1630 for &(_, temp) in fake_borrows {
1631 let cause = FakeReadCause::ForMatchGuard;
1632 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
1635 let otherwise_block = candidate.otherwise_block.unwrap_or_else(|| {
1636 let unreachable = self.cfg.start_new_block();
1637 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
1640 let outside_scope = self.cfg.start_new_block();
1644 otherwise_post_guard_block,
1650 candidate.next_candidate_pre_binding_block,
1654 // We want to ensure that the matched candidates are bound
1655 // after we have confirmed this candidate *and* any
1656 // associated guard; Binding them on `block` is too soon,
1657 // because that would be before we've checked the result
1660 // But binding them on the arm is *too late*, because
1661 // then all of the candidates for a single arm would be
1662 // bound in the same place, that would cause a case like:
1666 // (mut x, 1) | (2, mut x) if { true } => { ... }
1667 // ... // ^^^^^^^ (this is `arm_block`)
1671 // would yield a `arm_block` something like:
1674 // StorageLive(_4); // _4 is `x`
1675 // _4 = &mut (_1.0: i32); // this is handling `(mut x, 1)` case
1676 // _4 = &mut (_1.1: i32); // this is handling `(2, mut x)` case
1679 // and that is clearly not correct.
1680 let by_value_bindings =
1683 .flat_map(|(bindings, _)| bindings)
1684 .chain(&candidate.bindings)
1686 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1688 // Read all of the by reference bindings to ensure that the
1689 // place they refer to can't be modified by the guard.
1690 for binding in by_value_bindings.clone() {
1691 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1692 let cause = FakeReadCause::ForGuardBinding;
1693 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
1695 self.bind_matched_candidate_for_arm_body(post_guard_block, by_value_bindings);
1699 // (Here, it is not too early to bind the matched
1700 // candidate on `block`, because there is no guard result
1701 // that we have to inspect before we bind them.)
1702 self.bind_matched_candidate_for_arm_body(
1706 .flat_map(|(bindings, _)| bindings)
1707 .chain(&candidate.bindings),
1713 /// Append `AscribeUserType` statements onto the end of `block`
1714 /// for each ascription
1715 fn ascribe_types<'b>(
1718 ascriptions: impl IntoIterator<Item = &'b Ascription<'tcx>>,
1722 for ascription in ascriptions {
1723 let source_info = self.source_info(ascription.span);
1726 "adding user ascription at span {:?} of place {:?} and {:?}",
1727 source_info.span, ascription.source, ascription.user_ty,
1730 let user_ty = ascription.user_ty.clone().user_ty(
1731 &mut self.canonical_user_type_annotations,
1732 ascription.source.ty(&self.local_decls, self.hir.tcx()).ty,
1739 kind: StatementKind::AscribeUserType(
1740 box (ascription.source, user_ty),
1741 ascription.variance,
1748 fn bind_matched_candidate_for_guard<'b>(
1751 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1755 debug!("bind_matched_candidate_for_guard(block={:?})", block);
1757 // Assign each of the bindings. Since we are binding for a
1758 // guard expression, this will never trigger moves out of the
1760 let re_erased = self.hir.tcx().lifetimes.re_erased;
1761 for binding in bindings {
1762 debug!("bind_matched_candidate_for_guard(binding={:?})", binding);
1763 let source_info = self.source_info(binding.span);
1765 // For each pattern ident P of type T, `ref_for_guard` is
1766 // a reference R: &T pointing to the location matched by
1767 // the pattern, and every occurrence of P within a guard
1770 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1771 match binding.binding_mode {
1772 BindingMode::ByValue => {
1773 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source);
1774 self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1776 BindingMode::ByRef(borrow_kind) => {
1777 let value_for_arm = self.storage_live_binding(
1784 let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source);
1785 self.cfg.push_assign(block, source_info, &value_for_arm, rvalue);
1786 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1787 self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1793 fn bind_matched_candidate_for_arm_body<'b>(
1796 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1800 debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1802 let re_erased = self.hir.tcx().lifetimes.re_erased;
1803 // Assign each of the bindings. This may trigger moves out of the candidate.
1804 for binding in bindings {
1805 let source_info = self.source_info(binding.span);
1807 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1808 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1809 let rvalue = match binding.binding_mode {
1810 BindingMode::ByValue => {
1811 Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1813 BindingMode::ByRef(borrow_kind) => {
1814 Rvalue::Ref(re_erased, borrow_kind, binding.source)
1817 self.cfg.push_assign(block, source_info, &local, rvalue);
1821 /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1822 /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1823 /// first local is a binding for occurrences of `var` in the guard, which
1824 /// will have type `&T`. The second local is a binding for occurrences of
1825 /// `var` in the arm body, which will have type `T`.
1828 source_info: SourceInfo,
1829 visibility_scope: SourceScope,
1830 mutability: Mutability,
1835 user_ty: UserTypeProjections,
1836 has_guard: ArmHasGuard,
1837 opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1841 "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1842 visibility_scope={:?}, source_info={:?})",
1843 var_id, name, mode, var_ty, visibility_scope, source_info
1846 let tcx = self.hir.tcx();
1847 let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
1848 let binding_mode = match mode {
1849 BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1850 BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1852 debug!("declare_binding: user_ty={:?}", user_ty);
1853 let local = LocalDecl::<'tcx> {
1859 is_block_tail: None,
1860 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1862 // hypothetically, `visit_bindings` could try to unzip
1863 // an outermost hir::Ty as we descend, matching up
1864 // idents in pat; but complex w/ unclear UI payoff.
1865 // Instead, just abandon providing diagnostic info.
1871 let for_arm_body = self.local_decls.push(local);
1872 self.var_debug_info.push(VarDebugInfo {
1874 source_info: debug_source_info,
1875 place: for_arm_body.into(),
1877 let locals = if has_guard.0 {
1878 let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1879 // This variable isn't mutated but has a name, so has to be
1880 // immutable to avoid the unused mut lint.
1881 mutability: Mutability::Not,
1882 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
1883 user_ty: UserTypeProjections::none(),
1886 is_block_tail: None,
1887 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1889 self.var_debug_info.push(VarDebugInfo {
1891 source_info: debug_source_info,
1892 place: ref_for_guard.into(),
1894 LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
1896 LocalsForNode::One(for_arm_body)
1898 debug!("declare_binding: vars={:?}", locals);
1899 self.var_indices.insert(var_id, locals);