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, &mut 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 candidates: &mut [&mut Candidate<'pat, 'tcx>],
185 ) -> Vec<(Place<'tcx>, Local)> {
186 // The set of places that we are creating fake borrows of. If there are
187 // no match guards then we don't need any fake borrows, so don't track
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(scrutinee_span, block, &mut otherwise, candidates, &mut fake_borrows);
197 if let Some(otherwise_block) = otherwise {
198 let source_info = self.source_info(scrutinee_span);
199 self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
202 let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None;
204 for candidate in candidates {
205 candidate.visit_leaves(|leaf_candidate| {
206 if let Some(ref mut prev) = previous_candidate {
207 prev.next_candidate_pre_binding_block = leaf_candidate.pre_binding_block;
209 previous_candidate = Some(leaf_candidate);
213 if let Some(ref borrows) = fake_borrows {
214 self.calculate_fake_borrows(borrows, scrutinee_span)
220 /// Lower the bindings, guards and arm bodies of a `match` expression.
222 /// The decision tree should have already been created
223 /// (by [Builder::lower_match_tree]).
225 /// `outer_source_info` is the SourceInfo for the whole match.
228 destination: &Place<'tcx>,
229 scrutinee_place: Place<'tcx>,
230 scrutinee_span: Span,
231 arm_candidates: Vec<(&'_ Arm<'tcx>, Candidate<'_, 'tcx>)>,
232 outer_source_info: SourceInfo,
233 fake_borrow_temps: Vec<(Place<'tcx>, Local)>,
235 let match_scope = self.scopes.topmost();
237 let arm_end_blocks: Vec<_> = arm_candidates
239 .map(|(arm, candidate)| {
240 debug!("lowering arm {:?}\ncanidate = {:?}", arm, candidate);
242 let arm_source_info = self.source_info(arm.span);
243 let arm_scope = (arm.scope, arm_source_info);
244 self.in_scope(arm_scope, arm.lint_level, |this| {
245 let body = this.hir.mirror(arm.body.clone());
246 let scope = this.declare_bindings(
250 ArmHasGuard(arm.guard.is_some()),
251 Some((Some(&scrutinee_place), scrutinee_span)),
254 let arm_block = this.bind_pattern(
257 arm.guard.as_ref().map(|g| (g, match_scope)),
263 if let Some(source_scope) = scope {
264 this.source_scope = source_scope;
267 this.into(destination, arm_block, body)
272 // all the arm blocks will rejoin here
273 let end_block = self.cfg.start_new_block();
275 for arm_block in arm_end_blocks {
276 self.cfg.goto(unpack!(arm_block), outer_source_info, end_block);
279 self.source_scope = outer_source_info.scope;
284 /// Binds the variables and ascribes types for a given `match` arm.
286 /// Also check if the guard matches, if it's provided.
289 outer_source_info: SourceInfo,
290 candidate: Candidate<'_, 'tcx>,
291 guard: Option<(&Guard<'tcx>, region::Scope)>,
292 fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
293 scrutinee_span: Span,
294 arm_scope: Option<region::Scope>,
296 if candidate.subcandidates.is_empty() {
297 // Avoid generating another `BasicBlock` when we only have one
299 self.bind_and_guard_matched_candidate(
308 let target_block = self.cfg.start_new_block();
309 let mut schedule_drops = true;
310 // We keep a stack of all of the bindings and type asciptions
311 // from the the parent candidates that we visit, that also need to
312 // be bound for each candidate.
316 &mut |leaf_candidate, parent_bindings| {
317 if let Some(arm_scope) = arm_scope {
318 // Avoid scheduling drops multiple times by unscheduling drops.
319 self.clear_top_scope(arm_scope);
321 let binding_end = self.bind_and_guard_matched_candidate(
329 if arm_scope.is_none() {
330 // If we aren't in a match, then our bindings may not be
331 // the only thing in the top scope, so only schedule
332 // them to drop for the first pattern instead.
333 schedule_drops = false;
335 self.cfg.goto(binding_end, outer_source_info, target_block);
337 |inner_candidate, parent_bindings| {
338 parent_bindings.push((inner_candidate.bindings, inner_candidate.ascriptions));
339 inner_candidate.subcandidates.into_iter()
342 parent_bindings.pop();
350 pub(super) fn expr_into_pattern(
352 mut block: BasicBlock,
353 irrefutable_pat: Pat<'tcx>,
354 initializer: ExprRef<'tcx>,
356 match *irrefutable_pat.kind {
357 // Optimize the case of `let x = ...` to write directly into `x`
358 PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
360 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
361 unpack!(block = self.into(&place, block, initializer));
363 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
364 let source_info = self.source_info(irrefutable_pat.span);
365 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet, place);
367 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
371 // Optimize the case of `let x: T = ...` to write directly
372 // into `x` and then require that `T == typeof(x)`.
374 // Weirdly, this is needed to prevent the
375 // `intrinsic-move-val.rs` test case from crashing. That
376 // test works with uninitialized values in a rather
377 // dubious way, so it may be that the test is kind of
379 PatKind::AscribeUserType {
383 box PatKind::Binding {
384 mode: BindingMode::ByValue,
392 hair::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
395 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
396 unpack!(block = self.into(&place, block, initializer));
398 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
399 let pattern_source_info = self.source_info(irrefutable_pat.span);
400 let cause_let = FakeReadCause::ForLet;
401 self.cfg.push_fake_read(block, pattern_source_info, cause_let, place.clone());
403 let ty_source_info = self.source_info(user_ty_span);
404 let user_ty = pat_ascription_ty.user_ty(
405 &mut self.canonical_user_type_annotations,
406 place.ty(&self.local_decls, self.hir.tcx()).ty,
412 source_info: ty_source_info,
413 kind: StatementKind::AscribeUserType(
414 box (place, user_ty),
415 // We always use invariant as the variance here. This is because the
416 // variance field from the ascription refers to the variance to use
417 // when applying the type to the value being matched, but this
418 // ascription applies rather to the type of the binding. e.g., in this
425 // We are creating an ascription that defines the type of `x` to be
426 // exactly `T` (i.e., with invariance). The variance field, in
427 // contrast, is intended to be used to relate `T` to the type of
429 ty::Variance::Invariant,
434 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
439 let place = unpack!(block = self.as_place(block, initializer));
440 self.place_into_pattern(block, irrefutable_pat, &place, true)
445 crate fn place_into_pattern(
448 irrefutable_pat: Pat<'tcx>,
449 initializer: &Place<'tcx>,
450 set_match_place: bool,
452 // create a dummy candidate
453 let mut candidate = Candidate {
454 span: irrefutable_pat.span,
456 needs_otherwise_block: false,
457 match_pairs: smallvec![MatchPair::new(*initializer, &irrefutable_pat)],
461 // since we don't call `match_candidates`, next fields are unused
462 otherwise_block: None,
463 pre_binding_block: None,
464 next_candidate_pre_binding_block: None,
465 subcandidates: vec![],
468 let fake_borrow_temps =
469 self.lower_match_tree(block, irrefutable_pat.span, false, &mut [&mut candidate]);
471 // for matches and function arguments, the place that is being matched
472 // can be set when creating the variables. But the place for
473 // let PATTERN = ... might not even exist until we do the assignment.
474 // so we set it here instead
476 let mut candidate_ref = &candidate;
477 while let Some(next) = {
478 for binding in &candidate_ref.bindings {
479 let local = self.var_local_id(binding.var_id, OutsideGuard);
481 if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
482 VarBindingForm { opt_match_place: Some((ref mut match_place, _)), .. },
483 ))) = self.local_decls[local].local_info
485 *match_place = Some(*initializer);
487 bug!("Let binding to non-user variable.")
490 candidate_ref.subcandidates.get(0)
492 candidate_ref = next;
497 self.source_info(irrefutable_pat.span),
501 irrefutable_pat.span,
507 /// Declares the bindings of the given patterns and returns the visibility
508 /// scope for the bindings in these patterns, if such a scope had to be
509 /// created. NOTE: Declaring the bindings should always be done in their
511 crate fn declare_bindings(
513 mut visibility_scope: Option<SourceScope>,
516 has_guard: ArmHasGuard,
517 opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
518 ) -> Option<SourceScope> {
519 debug!("declare_bindings: pattern={:?}", pattern);
522 UserTypeProjections::none(),
523 &mut |this, mutability, name, mode, var, span, ty, user_ty| {
524 if visibility_scope.is_none() {
526 Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
528 let source_info = SourceInfo { span, scope: this.source_scope };
529 let visibility_scope = visibility_scope.unwrap();
530 this.declare_binding(
540 opt_match_place.map(|(x, y)| (x.cloned(), y)),
548 crate fn storage_live_binding(
555 let local_id = self.var_local_id(var, for_guard);
556 let source_info = self.source_info(span);
557 self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
558 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
559 self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
560 Place::from(local_id)
563 crate fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
564 let local_id = self.var_local_id(var, for_guard);
565 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
566 self.schedule_drop(span, region_scope, local_id, DropKind::Value);
569 pub(super) fn visit_bindings(
572 pattern_user_ty: UserTypeProjections,
584 debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
585 match *pattern.kind {
586 PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, .. } => {
587 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
588 if let Some(subpattern) = subpattern.as_ref() {
589 self.visit_bindings(subpattern, pattern_user_ty, f);
593 PatKind::Array { ref prefix, ref slice, ref suffix }
594 | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
595 let from = u32::try_from(prefix.len()).unwrap();
596 let to = u32::try_from(suffix.len()).unwrap();
597 for subpattern in prefix {
598 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
600 for subpattern in slice {
601 self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
603 for subpattern in suffix {
604 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
608 PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
610 PatKind::Deref { ref subpattern } => {
611 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
614 PatKind::AscribeUserType {
616 ascription: hair::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
618 // This corresponds to something like
621 // let A::<'a>(_): A<'static> = ...;
624 // Note that the variance doesn't apply here, as we are tracking the effect
625 // of `user_ty` on any bindings contained with subpattern.
626 let annotation = CanonicalUserTypeAnnotation {
628 user_ty: user_ty.user_ty,
629 inferred_ty: subpattern.ty,
631 let projection = UserTypeProjection {
632 base: self.canonical_user_type_annotations.push(annotation),
635 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
636 self.visit_bindings(subpattern, subpattern_user_ty, f)
639 PatKind::Leaf { ref subpatterns } => {
640 for subpattern in subpatterns {
641 let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
642 debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
643 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
647 PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
648 for subpattern in subpatterns {
649 let subpattern_user_ty =
650 pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
651 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
654 PatKind::Or { ref pats } => {
655 self.visit_bindings(&pats[0], pattern_user_ty.clone(), f);
662 crate struct Candidate<'pat, 'tcx> {
663 /// `Span` of the original pattern that gave rise to this candidate
666 /// This `Candidate` has a guard.
669 /// This `Candidate` needs and otherwise block, either because it has a
670 /// guard or it has subcandidates.
671 needs_otherwise_block: bool,
673 /// All of these must be satisfied...
674 match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
676 /// ...these bindings established...
677 bindings: Vec<Binding<'tcx>>,
679 /// ...and these types asserted...
680 ascriptions: Vec<Ascription<'tcx>>,
682 /// ... and if this is non-empty, one of these subcandidates also has to match ...
683 subcandidates: Vec<Candidate<'pat, 'tcx>>,
685 /// ...and the guard must be evaluated, if false branch to Block...
686 otherwise_block: Option<BasicBlock>,
688 /// ...and the blocks for add false edges between candidates
689 pre_binding_block: Option<BasicBlock>,
690 next_candidate_pre_binding_block: Option<BasicBlock>,
693 impl Candidate<'_, '_> {
694 /// Visit the leaf candidates (those with no subcandidates) contained in
696 fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
700 &mut move |c, _| visit_leaf(c),
701 move |c, _| c.subcandidates.iter_mut(),
707 /// A depth-first traversal of the `Candidate` and all of its recursive
709 fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>(
712 visit_leaf: &mut impl FnMut(C, &mut T),
713 get_children: impl Copy + Fn(C, &mut T) -> I,
714 complete_children: impl Copy + Fn(&mut T),
716 C: Borrow<Candidate<'pat, 'tcx>>,
717 I: Iterator<Item = C>,
719 if candidate.borrow().subcandidates.is_empty() {
720 visit_leaf(candidate, context)
722 for child in get_children(candidate, context) {
723 traverse_candidate(child, context, visit_leaf, get_children, complete_children);
725 complete_children(context)
729 #[derive(Clone, Debug)]
730 struct Binding<'tcx> {
736 mutability: Mutability,
737 binding_mode: BindingMode,
740 /// Indicates that the type of `source` must be a subtype of the
741 /// user-given type `user_ty`; this is basically a no-op but can
742 /// influence region inference.
743 #[derive(Clone, Debug)]
744 struct Ascription<'tcx> {
747 user_ty: PatTyProj<'tcx>,
748 variance: ty::Variance,
751 #[derive(Clone, Debug)]
752 crate struct MatchPair<'pat, 'tcx> {
756 // ... must match this pattern.
757 pattern: &'pat Pat<'tcx>,
760 #[derive(Clone, Debug, PartialEq)]
761 enum TestKind<'tcx> {
762 /// Test the branches of enum.
764 /// The enum being tested
765 adt_def: &'tcx ty::AdtDef,
766 /// The set of variants that we should create a branch for. We also
767 /// create an additional "otherwise" case.
768 variants: BitSet<VariantIdx>,
771 /// Test what value an `integer`, `bool` or `char` has.
773 /// The type of the value that we're testing.
775 /// The (ordered) set of values that we test for.
777 /// For integers and `char`s we create a branch to each of the values in
778 /// `options`, as well as an "otherwise" branch for all other values, even
779 /// in the (rare) case that options is exhaustive.
781 /// For `bool` we always generate two edges, one for `true` and one for
784 /// Reverse map used to ensure that the values in `options` are unique.
785 indices: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
788 /// Test for equality with value, possibly after an unsizing coercion to
791 value: &'tcx ty::Const<'tcx>,
792 // Integer types are handled by `SwitchInt`, and constants with ADT
793 // types are converted back into patterns, so this can only be `&str`,
794 // `&[T]`, `f32` or `f64`.
798 /// Test whether the value falls within an inclusive or exclusive range
799 Range(PatRange<'tcx>),
801 /// Test length of the slice is equal to len
802 Len { len: u64, op: BinOp },
806 crate struct Test<'tcx> {
808 kind: TestKind<'tcx>,
811 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
812 /// a match arm has a guard expression attached to it.
813 #[derive(Copy, Clone, Debug)]
814 crate struct ArmHasGuard(crate bool);
816 ///////////////////////////////////////////////////////////////////////////
817 // Main matching algorithm
819 impl<'a, 'tcx> Builder<'a, 'tcx> {
820 /// The main match algorithm. It begins with a set of candidates
821 /// `candidates` and has the job of generating code to determine
822 /// which of these candidates, if any, is the correct one. The
823 /// candidates are sorted such that the first item in the list
824 /// has the highest priority. When a candidate is found to match
825 /// the value, we will set and generate a branch to the appropriate
826 /// prebinding block.
828 /// If we find that *NONE* of the candidates apply, we branch to the
829 /// `otherwise_block`, setting it to `Some` if required. In principle, this
830 /// means that the input list was not exhaustive, though at present we
831 /// sometimes are not smart enough to recognize all exhaustive inputs.
833 /// It might be surprising that the input can be inexhaustive.
834 /// Indeed, initially, it is not, because all matches are
835 /// exhaustive in Rust. But during processing we sometimes divide
836 /// up the list of candidates and recurse with a non-exhaustive
837 /// list. This is important to keep the size of the generated code
838 /// under control. See `test_candidates` for more details.
840 /// If `fake_borrows` is Some, then places which need fake borrows
841 /// will be added to it.
842 fn match_candidates<'pat>(
845 start_block: BasicBlock,
846 otherwise_block: &mut Option<BasicBlock>,
847 candidates: &mut [&mut Candidate<'pat, 'tcx>],
848 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
851 "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
852 span, candidates, start_block, otherwise_block,
855 // Start by simplifying candidates. Once this process is complete, all
856 // the match pairs which remain require some form of test, whether it
857 // be a switch or pattern comparison.
858 let mut split_or_candidate = false;
859 for candidate in &mut *candidates {
860 split_or_candidate |= self.simplify_candidate(candidate);
863 if split_or_candidate {
864 // At least one of the candidates has been split into subcandidates.
865 // We need to change the candidate list to include those.
866 let mut new_candidates = Vec::new();
868 for candidate in candidates {
869 candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate));
871 self.match_simplified_candidates(
875 &mut *new_candidates,
879 self.match_simplified_candidates(
889 fn match_simplified_candidates(
892 start_block: BasicBlock,
893 otherwise_block: &mut Option<BasicBlock>,
894 candidates: &mut [&mut Candidate<_, 'tcx>],
895 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
897 // The candidates are sorted by priority. Check to see whether the
898 // higher priority candidates (and hence at the front of the slice)
899 // have satisfied all their match pairs.
900 let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
901 debug!("match_candidates: {:?} candidates fully matched", fully_matched);
902 let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
904 let block = if !matched_candidates.is_empty() {
905 let otherwise_block =
906 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
908 if let Some(last_otherwise_block) = otherwise_block {
911 // Any remaining candidates are unreachable.
912 if unmatched_candidates.is_empty() {
915 self.cfg.start_new_block()
921 // If there are no candidates that still need testing, we're
922 // done. Since all matches are exhaustive, execution should
923 // never reach this point.
924 if unmatched_candidates.is_empty() {
925 let source_info = self.source_info(span);
926 if let Some(otherwise) = *otherwise_block {
927 self.cfg.goto(block, source_info, otherwise);
929 *otherwise_block = Some(block);
934 // Test for the remaining candidates.
935 self.test_candidates_with_or(
937 unmatched_candidates,
944 /// Link up matched candidates. For example, if we have something like
948 /// Some(x) if cond => ...
950 /// Some(x) if cond => ...
953 /// We generate real edges from:
954 /// * `start_block` to the `prebinding_block` of the first pattern,
955 /// * the otherwise block of the first pattern to the second pattern,
956 /// * the otherwise block of the third pattern to the a block with an
957 /// Unreachable terminator.
959 /// As well as that we add fake edges from the otherwise blocks to the
960 /// prebinding block of the next candidate in the original set of
962 fn select_matched_candidates(
964 matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
965 start_block: BasicBlock,
966 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
967 ) -> Option<BasicBlock> {
969 !matched_candidates.is_empty(),
970 "select_matched_candidates called with no candidates",
973 matched_candidates.iter().all(|c| c.subcandidates.is_empty()),
974 "subcandidates should be empty in select_matched_candidates",
977 // Insert a borrows of prefixes of places that are bound and are
978 // behind a dereference projection.
980 // These borrows are taken to avoid situations like the following:
983 // _ if { x = &[0]; false } => (),
984 // y => (), // Out of bounds array access!
988 // // y is bound by reference in the guard and then by copy in the
989 // // arm, so y is 2 in the arm!
990 // y if { y == 1 && (x = &2) == () } => y,
993 if let Some(fake_borrows) = fake_borrows {
994 for Binding { source, .. } in
995 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
998 source.projection.iter().rposition(|elem| *elem == ProjectionElem::Deref)
1000 let proj_base = &source.projection[..i];
1002 fake_borrows.insert(Place {
1003 local: source.local,
1004 projection: self.hir.tcx().intern_place_elems(proj_base),
1010 let fully_matched_with_guard = matched_candidates
1012 .position(|c| !c.needs_otherwise_block)
1013 .unwrap_or(matched_candidates.len() - 1);
1015 let (reachable_candidates, unreachable_candidates) =
1016 matched_candidates.split_at_mut(fully_matched_with_guard + 1);
1018 let mut next_prebinding = start_block;
1020 for candidate in reachable_candidates.iter_mut() {
1021 assert!(candidate.otherwise_block.is_none());
1022 assert!(candidate.pre_binding_block.is_none());
1023 candidate.pre_binding_block = Some(next_prebinding);
1024 if candidate.needs_otherwise_block {
1025 next_prebinding = self.cfg.start_new_block();
1026 candidate.otherwise_block = Some(next_prebinding);
1031 "match_candidates: add pre_binding_blocks for unreachable {:?}",
1032 unreachable_candidates,
1034 for candidate in unreachable_candidates {
1035 assert!(candidate.pre_binding_block.is_none());
1036 candidate.pre_binding_block = Some(self.cfg.start_new_block());
1039 reachable_candidates.last_mut().unwrap().otherwise_block
1042 fn test_candidates_with_or(
1045 candidates: &mut [&mut Candidate<'_, 'tcx>],
1047 otherwise_block: &mut Option<BasicBlock>,
1048 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1050 let (first_candidate, remaining_candidates) = candidates.split_first_mut().unwrap();
1052 if let PatKind::Or { .. } = *first_candidate.match_pairs[0].pattern.kind {
1053 let match_pairs = mem::take(&mut first_candidate.match_pairs);
1054 first_candidate.needs_otherwise_block = true;
1055 first_candidate.pre_binding_block = Some(block);
1057 // We sort or-patterns to the end in `simplify_candidate`, so all
1058 // the remaining match pairs are or-patterns.
1059 for match_pair in match_pairs {
1060 if let PatKind::Or { ref pats } = *match_pair.pattern.kind {
1061 let or_span = match_pair.pattern.span;
1062 let place = &match_pair.place;
1064 first_candidate.visit_leaves(|leaf_candidate| {
1065 self.test_or_pattern(leaf_candidate, pats, or_span, place, fake_borrows);
1068 bug!("Or patterns should have been sorted to the end");
1071 let remainder_start =
1072 first_candidate.otherwise_block.unwrap_or_else(|| self.cfg.start_new_block());
1073 self.match_candidates(
1077 remaining_candidates,
1081 self.test_candidates(span, candidates, block, otherwise_block, fake_borrows)
1085 fn test_or_pattern<'pat>(
1087 candidate: &mut Candidate<'pat, 'tcx>,
1088 pats: &'pat [Pat<'tcx>],
1090 place: &Place<'tcx>,
1091 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1093 debug!("test_or_pattern:\ncandidate={:#?}\npats={:#?}", candidate, pats);
1094 let mut or_candidates: Vec<_> = pats
1097 let new_match_pair = smallvec![MatchPair { pattern: pat, place: place.clone() }];
1100 has_guard: candidate.has_guard,
1101 needs_otherwise_block: candidate.needs_otherwise_block,
1102 match_pairs: new_match_pair,
1103 bindings: Vec::new(),
1104 ascriptions: Vec::new(),
1105 otherwise_block: None,
1106 pre_binding_block: None,
1107 next_candidate_pre_binding_block: None,
1108 subcandidates: Vec::new(),
1112 let mut or_candidate_refs: Vec<_> = or_candidates.iter_mut().collect();
1113 self.match_candidates(
1115 candidate.pre_binding_block.unwrap(),
1116 &mut candidate.otherwise_block,
1117 &mut or_candidate_refs,
1120 candidate.subcandidates = or_candidates;
1121 self.merge_trivial_subcandidates(candidate, self.source_info(or_span));
1124 /// Try to merge all of the subcandidates of the given candidate into one.
1125 /// This avoids exponentially large CFGs in cases like `(1 | 2, 3 | 4, ...)`.
1126 fn merge_trivial_subcandidates(
1128 candidate: &mut Candidate<'_, 'tcx>,
1129 source_info: SourceInfo,
1131 if candidate.subcandidates.is_empty() {
1134 let mut can_merge = !candidate.has_guard;
1136 // Not `Iterator::all` because we don't want to short-circuit.
1137 for subcandidate in &mut candidate.subcandidates {
1138 self.merge_trivial_subcandidates(subcandidate, source_info);
1140 // FIXME(or_patterns; matthewjasper) Try to be more aggressive here.
1141 can_merge &= subcandidate.subcandidates.is_empty()
1142 && subcandidate.bindings.is_empty()
1143 && subcandidate.ascriptions.is_empty();
1147 let any_matches = self.cfg.start_new_block();
1148 for subcandidate in mem::take(&mut candidate.subcandidates) {
1149 let or_block = subcandidate.pre_binding_block.unwrap();
1150 self.cfg.goto(or_block, source_info, any_matches);
1152 candidate.pre_binding_block = Some(any_matches);
1156 /// This is the most subtle part of the matching algorithm. At
1157 /// this point, the input candidates have been fully simplified,
1158 /// and so we know that all remaining match-pairs require some
1159 /// sort of test. To decide what test to do, we take the highest
1160 /// priority candidate (last one in the list) and extract the
1161 /// first match-pair from the list. From this we decide what kind
1162 /// of test is needed using `test`, defined in the `test` module.
1164 /// *Note:* taking the first match pair is somewhat arbitrary, and
1165 /// we might do better here by choosing more carefully what to
1168 /// For example, consider the following possible match-pairs:
1170 /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
1171 /// 2. `x @ 22` -- we will do a `SwitchInt`
1172 /// 3. `x @ 3..5` -- we will do a range test
1175 /// Once we know what sort of test we are going to perform, this
1176 /// Tests may also help us with other candidates. So we walk over
1177 /// the candidates (from high to low priority) and check. This
1178 /// gives us, for each outcome of the test, a transformed list of
1179 /// candidates. For example, if we are testing the current
1180 /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
1181 /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
1182 /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
1183 /// simpler (and, in fact, irrefutable).
1185 /// But there may also be candidates that the test just doesn't
1186 /// apply to. The classical example involves wildcards:
1189 /// # let (x, y, z) = (true, true, true);
1190 /// match (x, y, z) {
1191 /// (true, _, true) => true, // (0)
1192 /// (_, true, _) => true, // (1)
1193 /// (false, false, _) => false, // (2)
1194 /// (true, _, false) => false, // (3)
1198 /// In that case, after we test on `x`, there are 2 overlapping candidate
1201 /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1202 /// - If the outcome is that `x` is false, candidates 1 and 2
1204 /// Here, the traditional "decision tree" method would generate 2
1205 /// separate code-paths for the 2 separate cases.
1207 /// In some cases, this duplication can create an exponential amount of
1208 /// code. This is most easily seen by noticing that this method terminates
1209 /// with precisely the reachable arms being reachable - but that problem
1210 /// is trivially NP-complete:
1213 /// match (var0, var1, var2, var3, ..) {
1214 /// (true, _, _, false, true, ...) => false,
1215 /// (_, true, true, false, _, ...) => false,
1216 /// (false, _, false, false, _, ...) => false,
1222 /// Here the last arm is reachable only if there is an assignment to
1223 /// the variables that does not match any of the literals. Therefore,
1224 /// compilation would take an exponential amount of time in some cases.
1226 /// That kind of exponential worst-case might not occur in practice, but
1227 /// our simplistic treatment of constants and guards would make it occur
1228 /// in very common situations - for example #29740:
1232 /// "foo" if foo_guard => ...,
1233 /// "bar" if bar_guard => ...,
1234 /// "baz" if baz_guard => ...,
1239 /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1241 /// It might seem that we would end up with 2 disjoint candidate
1242 /// sets, consisting of the first candidate or the other 3, but our
1243 /// algorithm doesn't reason about "foo" being distinct from the other
1244 /// constants; it considers the latter arms to potentially match after
1245 /// both outcomes, which obviously leads to an exponential amount
1248 /// To avoid these kinds of problems, our algorithm tries to ensure
1249 /// the amount of generated tests is linear. When we do a k-way test,
1250 /// we return an additional "unmatched" set alongside the obvious `k`
1251 /// sets. When we encounter a candidate that would be present in more
1252 /// than one of the sets, we put it and all candidates below it into the
1253 /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1255 /// After we perform our test, we branch into the appropriate candidate
1256 /// set and recurse with `match_candidates`. These sub-matches are
1257 /// obviously inexhaustive - as we discarded our otherwise set - so
1258 /// we set their continuation to do `match_candidates` on the
1259 /// "unmatched" set (which is again inexhaustive).
1261 /// If you apply this to the above test, you basically wind up
1262 /// with an if-else-if chain, testing each candidate in turn,
1263 /// which is precisely what we want.
1265 /// In addition to avoiding exponential-time blowups, this algorithm
1266 /// also has nice property that each guard and arm is only generated
1268 fn test_candidates<'pat, 'b, 'c>(
1271 mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1273 otherwise_block: &mut Option<BasicBlock>,
1274 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1276 // extract the match-pair from the highest priority candidate
1277 let match_pair = &candidates.first().unwrap().match_pairs[0];
1278 let mut test = self.test(match_pair);
1279 let match_place = match_pair.place;
1281 // most of the time, the test to perform is simply a function
1282 // of the main candidate; but for a test like SwitchInt, we
1283 // may want to add cases based on the candidates that are
1286 TestKind::SwitchInt { switch_ty, ref mut options, ref mut indices } => {
1287 for candidate in candidates.iter() {
1288 if !self.add_cases_to_switch(
1299 TestKind::Switch { adt_def: _, ref mut variants } => {
1300 for candidate in candidates.iter() {
1301 if !self.add_variants_to_switch(&match_place, candidate, variants) {
1309 // Insert a Shallow borrow of any places that is switched on.
1310 fake_borrows.as_mut().map(|fb| fb.insert(match_place.clone()));
1312 // perform the test, branching to one of N blocks. For each of
1313 // those N possible outcomes, create a (initially empty)
1314 // vector of candidates. Those are the candidates that still
1315 // apply if the test has that particular outcome.
1316 debug!("match_candidates: test={:?} match_pair={:?}", test, match_pair);
1317 let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1318 target_candidates.resize_with(test.targets(), Default::default);
1320 let total_candidate_count = candidates.len();
1322 // Sort the candidates into the appropriate vector in
1323 // `target_candidates`. Note that at some point we may
1324 // encounter a candidate where the test is not relevant; at
1325 // that point, we stop sorting.
1326 while let Some(candidate) = candidates.first_mut() {
1327 if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1328 let (candidate, rest) = candidates.split_first_mut().unwrap();
1329 target_candidates[idx].push(candidate);
1335 // at least the first candidate ought to be tested
1336 assert!(total_candidate_count > candidates.len());
1337 debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1338 debug!("untested_candidates: {}", candidates.len());
1340 // HACK(matthewjasper) This is a closure so that we can let the test
1341 // create its blocks before the rest of the match. This currently
1342 // improves the speed of llvm when optimizing long string literal
1344 let make_target_blocks = move |this: &mut Self| -> Vec<BasicBlock> {
1345 // The block that we should branch to if none of the
1346 // `target_candidates` match. This is either the block where we
1347 // start matching the untested candidates if there are any,
1348 // otherwise it's the `otherwise_block`.
1349 let remainder_start = &mut None;
1350 let remainder_start =
1351 if candidates.is_empty() { &mut *otherwise_block } else { remainder_start };
1353 // For each outcome of test, process the candidates that still
1354 // apply. Collect a list of blocks where control flow will
1355 // branch if one of the `target_candidate` sets is not
1357 let target_blocks: Vec<_> = target_candidates
1359 .map(|mut candidates| {
1360 if candidates.len() != 0 {
1361 let candidate_start = this.cfg.start_new_block();
1362 this.match_candidates(
1371 *remainder_start.get_or_insert_with(|| this.cfg.start_new_block())
1376 if !candidates.is_empty() {
1377 let remainder_start = remainder_start.unwrap_or_else(|| this.cfg.start_new_block());
1378 this.match_candidates(
1390 self.perform_test(block, &match_place, &test, make_target_blocks);
1393 /// Determine the fake borrows that are needed from a set of places that
1394 /// have to be stable across match guards.
1396 /// Returns a list of places that need a fake borrow and the temporary
1397 /// that's used to store the fake borrow.
1399 /// Match exhaustiveness checking is not able to handle the case where the
1400 /// place being matched on is mutated in the guards. We add "fake borrows"
1401 /// to the guards that prevent any mutation of the place being matched.
1402 /// There are a some subtleties:
1404 /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
1405 /// reference, the borrow isn't even tracked. As such we have to add fake
1406 /// borrows of any prefixes of a place
1407 /// 2. We don't want `match x { _ => (), }` to conflict with mutable
1408 /// borrows of `x`, so we only add fake borrows for places which are
1409 /// bound or tested by the match.
1410 /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
1411 /// so we use a special BorrowKind for them.
1412 /// 4. The fake borrows may be of places in inactive variants, so it would
1413 /// be UB to generate code for them. They therefore have to be removed
1414 /// by a MIR pass run after borrow checking.
1415 fn calculate_fake_borrows<'b>(
1417 fake_borrows: &'b FxHashSet<Place<'tcx>>,
1419 ) -> Vec<(Place<'tcx>, Local)> {
1420 let tcx = self.hir.tcx();
1422 debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1424 let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1426 // Insert a Shallow borrow of the prefixes of any fake borrows.
1427 for place in fake_borrows {
1428 let mut cursor = place.projection.as_ref();
1429 while let [proj_base @ .., elem] = cursor {
1432 if let ProjectionElem::Deref = elem {
1433 // Insert a shallow borrow after a deref. For other
1434 // projections the borrow of prefix_cursor will
1435 // conflict with any mutation of base.
1436 all_fake_borrows.push(PlaceRef { local: place.local, projection: proj_base });
1440 all_fake_borrows.push(place.as_ref());
1443 // Deduplicate and ensure a deterministic order.
1444 all_fake_borrows.sort();
1445 all_fake_borrows.dedup();
1447 debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1451 .map(|matched_place_ref| {
1452 let matched_place = Place {
1453 local: matched_place_ref.local,
1454 projection: tcx.intern_place_elems(matched_place_ref.projection),
1456 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1457 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1458 let fake_borrow_temp =
1459 self.local_decls.push(LocalDecl::new_temp(fake_borrow_ty, temp_span));
1461 (matched_place, fake_borrow_temp)
1467 ///////////////////////////////////////////////////////////////////////////
1468 // Pat binding - used for `let` and function parameters as well.
1470 impl<'a, 'tcx> Builder<'a, 'tcx> {
1471 /// Initializes each of the bindings from the candidate by
1472 /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1473 /// any, and then branches to the arm. Returns the block for the case where
1474 /// the guard fails.
1476 /// Note: we do not check earlier that if there is a guard,
1477 /// there cannot be move bindings. We avoid a use-after-move by only
1478 /// moving the binding once the guard has evaluated to true (see below).
1479 fn bind_and_guard_matched_candidate<'pat>(
1481 candidate: Candidate<'pat, 'tcx>,
1482 parent_bindings: &[(Vec<Binding<'tcx>>, Vec<Ascription<'tcx>>)],
1483 guard: Option<(&Guard<'tcx>, region::Scope)>,
1484 fake_borrows: &Vec<(Place<'tcx>, Local)>,
1485 scrutinee_span: Span,
1486 schedule_drops: bool,
1488 debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1490 debug_assert!(candidate.match_pairs.is_empty());
1492 let candidate_source_info = self.source_info(candidate.span);
1494 let mut block = candidate.pre_binding_block.unwrap();
1496 if candidate.next_candidate_pre_binding_block.is_some() {
1497 let fresh_block = self.cfg.start_new_block();
1501 candidate.next_candidate_pre_binding_block,
1502 candidate_source_info,
1504 block = fresh_block;
1511 .flat_map(|(_, ascriptions)| ascriptions)
1512 .chain(&candidate.ascriptions),
1515 // rust-lang/rust#27282: The `autoref` business deserves some
1516 // explanation here.
1518 // The intent of the `autoref` flag is that when it is true,
1519 // then any pattern bindings of type T will map to a `&T`
1520 // within the context of the guard expression, but will
1521 // continue to map to a `T` in the context of the arm body. To
1522 // avoid surfacing this distinction in the user source code
1523 // (which would be a severe change to the language and require
1524 // far more revision to the compiler), when `autoref` is true,
1525 // then any occurrence of the identifier in the guard
1526 // expression will automatically get a deref op applied to it.
1528 // So an input like:
1531 // let place = Foo::new();
1532 // match place { foo if inspect(foo)
1533 // => feed(foo), ... }
1536 // will be treated as if it were really something like:
1539 // let place = Foo::new();
1540 // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1541 // => { let tmp2 = place; feed(tmp2) }, ... }
1543 // And an input like:
1546 // let place = Foo::new();
1547 // match place { ref mut foo if inspect(foo)
1548 // => feed(foo), ... }
1551 // will be treated as if it were really something like:
1554 // let place = Foo::new();
1555 // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1556 // => { let tmp2 = &mut place; feed(tmp2) }, ... }
1559 // In short, any pattern binding will always look like *some*
1560 // kind of `&T` within the guard at least in terms of how the
1561 // MIR-borrowck views it, and this will ensure that guard
1562 // expressions cannot mutate their the match inputs via such
1563 // bindings. (It also ensures that guard expressions can at
1564 // most *copy* values from such bindings; non-Copy things
1565 // cannot be moved via pattern bindings in guard expressions.)
1569 // Implementation notes (under assumption `autoref` is true).
1571 // To encode the distinction above, we must inject the
1572 // temporaries `tmp1` and `tmp2`.
1574 // There are two cases of interest: binding by-value, and binding by-ref.
1576 // 1. Binding by-value: Things are simple.
1578 // * Establishing `tmp1` creates a reference into the
1579 // matched place. This code is emitted by
1580 // bind_matched_candidate_for_guard.
1582 // * `tmp2` is only initialized "lazily", after we have
1583 // checked the guard. Thus, the code that can trigger
1584 // moves out of the candidate can only fire after the
1585 // guard evaluated to true. This initialization code is
1586 // emitted by bind_matched_candidate_for_arm.
1588 // 2. Binding by-reference: Things are tricky.
1590 // * Here, the guard expression wants a `&&` or `&&mut`
1591 // into the original input. This means we need to borrow
1592 // the reference that we create for the arm.
1593 // * So we eagerly create the reference for the arm and then take a
1594 // reference to that.
1595 if let Some((guard, region_scope)) = guard {
1596 let tcx = self.hir.tcx();
1597 let bindings = parent_bindings
1599 .flat_map(|(bindings, _)| bindings)
1600 .chain(&candidate.bindings);
1602 self.bind_matched_candidate_for_guard(block, bindings.clone());
1603 let guard_frame = GuardFrame {
1604 locals: bindings.map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode)).collect(),
1606 debug!("entering guard building context: {:?}", guard_frame);
1607 self.guard_context.push(guard_frame);
1609 let re_erased = tcx.lifetimes.re_erased;
1610 let scrutinee_source_info = self.source_info(scrutinee_span);
1611 for (place, temp) in fake_borrows {
1612 let borrow = Rvalue::Ref(re_erased, BorrowKind::Shallow, *place);
1613 self.cfg.push_assign(block, scrutinee_source_info, &Place::from(*temp), borrow);
1616 // the block to branch to if the guard fails; if there is no
1617 // guard, this block is simply unreachable
1618 let guard = match guard {
1619 Guard::If(e) => self.hir.mirror(e.clone()),
1621 let source_info = self.source_info(guard.span);
1622 let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1623 let (post_guard_block, otherwise_post_guard_block) =
1624 self.test_bool(block, guard, source_info);
1625 let guard_frame = self.guard_context.pop().unwrap();
1626 debug!("Exiting guard building context with locals: {:?}", guard_frame);
1628 for &(_, temp) in fake_borrows {
1629 let cause = FakeReadCause::ForMatchGuard;
1630 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
1633 let otherwise_block = candidate.otherwise_block.unwrap_or_else(|| {
1634 let unreachable = self.cfg.start_new_block();
1635 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
1638 let outside_scope = self.cfg.start_new_block();
1642 otherwise_post_guard_block,
1648 candidate.next_candidate_pre_binding_block,
1652 // We want to ensure that the matched candidates are bound
1653 // after we have confirmed this candidate *and* any
1654 // associated guard; Binding them on `block` is too soon,
1655 // because that would be before we've checked the result
1658 // But binding them on the arm is *too late*, because
1659 // then all of the candidates for a single arm would be
1660 // bound in the same place, that would cause a case like:
1664 // (mut x, 1) | (2, mut x) if { true } => { ... }
1665 // ... // ^^^^^^^ (this is `arm_block`)
1669 // would yield a `arm_block` something like:
1672 // StorageLive(_4); // _4 is `x`
1673 // _4 = &mut (_1.0: i32); // this is handling `(mut x, 1)` case
1674 // _4 = &mut (_1.1: i32); // this is handling `(2, mut x)` case
1677 // and that is clearly not correct.
1678 let by_value_bindings =
1681 .flat_map(|(bindings, _)| bindings)
1682 .chain(&candidate.bindings)
1684 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1686 // Read all of the by reference bindings to ensure that the
1687 // place they refer to can't be modified by the guard.
1688 for binding in by_value_bindings.clone() {
1689 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1690 let cause = FakeReadCause::ForGuardBinding;
1691 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
1693 assert!(schedule_drops, "patterns with guards must schedule drops");
1694 self.bind_matched_candidate_for_arm_body(post_guard_block, true, by_value_bindings);
1698 // (Here, it is not too early to bind the matched
1699 // candidate on `block`, because there is no guard result
1700 // that we have to inspect before we bind them.)
1701 self.bind_matched_candidate_for_arm_body(
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 schedule_drops: bool,
1797 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1801 debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1803 let re_erased = self.hir.tcx().lifetimes.re_erased;
1804 // Assign each of the bindings. This may trigger moves out of the candidate.
1805 for binding in bindings {
1806 let source_info = self.source_info(binding.span);
1808 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1810 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1812 let rvalue = match binding.binding_mode {
1813 BindingMode::ByValue => {
1814 Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1816 BindingMode::ByRef(borrow_kind) => {
1817 Rvalue::Ref(re_erased, borrow_kind, binding.source)
1820 self.cfg.push_assign(block, source_info, &local, rvalue);
1824 /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1825 /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1826 /// first local is a binding for occurrences of `var` in the guard, which
1827 /// will have type `&T`. The second local is a binding for occurrences of
1828 /// `var` in the arm body, which will have type `T`.
1831 source_info: SourceInfo,
1832 visibility_scope: SourceScope,
1833 mutability: Mutability,
1838 user_ty: UserTypeProjections,
1839 has_guard: ArmHasGuard,
1840 opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1844 "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1845 visibility_scope={:?}, source_info={:?})",
1846 var_id, name, mode, var_ty, visibility_scope, source_info
1849 let tcx = self.hir.tcx();
1850 let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
1851 let binding_mode = match mode {
1852 BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1853 BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1855 debug!("declare_binding: user_ty={:?}", user_ty);
1856 let local = LocalDecl::<'tcx> {
1862 is_block_tail: None,
1863 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1865 // hypothetically, `visit_bindings` could try to unzip
1866 // an outermost hir::Ty as we descend, matching up
1867 // idents in pat; but complex w/ unclear UI payoff.
1868 // Instead, just abandon providing diagnostic info.
1874 let for_arm_body = self.local_decls.push(local);
1875 self.var_debug_info.push(VarDebugInfo {
1877 source_info: debug_source_info,
1878 place: for_arm_body.into(),
1880 let locals = if has_guard.0 {
1881 let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1882 // This variable isn't mutated but has a name, so has to be
1883 // immutable to avoid the unused mut lint.
1884 mutability: Mutability::Not,
1885 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
1886 user_ty: UserTypeProjections::none(),
1889 is_block_tail: None,
1890 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1892 self.var_debug_info.push(VarDebugInfo {
1894 source_info: debug_source_info,
1895 place: ref_for_guard.into(),
1897 LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
1899 LocalsForNode::One(for_arm_body)
1901 debug!("declare_binding: vars={:?}", locals);
1902 self.var_indices.insert(var_id, locals);