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::{CachedBlock, 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::hir::HirId;
15 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty};
16 use rustc::ty::layout::VariantIdx;
17 use rustc_data_structures::bit_set::BitSet;
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use syntax::ast::Name;
22 // helper functions, broken out by category:
27 use std::convert::TryFrom;
29 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
30 /// Generates MIR for a `match` expression.
32 /// The MIR that we generate for a match looks like this.
37 /// [ 1. Evaluate Scrutinee (expression being matched on) ]
38 /// [ (fake read of scrutinee) ]
40 /// [ 2. Decision tree -- check discriminants ] <--------+
42 /// | (once a specific arm is chosen) |
44 /// [pre_binding_block] [otherwise_block]
46 /// [ 3. Create "guard bindings" for arm ] |
47 /// [ (create fake borrows) ] |
49 /// [ 4. Execute guard code ] |
50 /// [ (read fake borrows) ] --(guard is false)-----------+
52 /// | (guard results in true)
54 /// [ 5. Create real bindings and execute arm ]
59 /// All of the different arms have been stacked on top of each other to
60 /// simplify the diagram. For an arm with no guard the blocks marked 3 and
61 /// 4 and the fake borrows are omitted.
63 /// We generate MIR in the following steps:
65 /// 1. Evaluate the scrutinee and add the fake read of it.
66 /// 2. Create the prebinding and otherwise blocks.
67 /// 3. Create the decision tree and record the places that we bind or test.
68 /// 4. Determine the fake borrows that are needed from the above places.
69 /// Create the required temporaries for them.
70 /// 5. Create everything else: Create everything else: the guards and the
73 /// ## Fake Reads and borrows
75 /// Match exhaustiveness checking is not able to handle the case where the
76 /// place being matched on is mutated in the guards. There is an AST check
77 /// that tries to stop this but it is buggy and overly restrictive. Instead
78 /// we add "fake borrows" to the guards that prevent any mutation of the
79 /// place being matched. There are a some subtleties:
81 /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
82 /// refence, the borrow isn't even tracked. As such we have to add fake
83 /// borrows of any prefixes of a place
84 /// 2. We don't want `match x { _ => (), }` to conflict with mutable
85 /// borrows of `x`, so we only add fake borrows for places which are
86 /// bound or tested by the match.
87 /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
88 /// so we use a special BorrowKind for them.
89 /// 4. The fake borrows may be of places in inactive variants, so it would
90 /// be UB to generate code for them. They therefore have to be removed
91 /// by a MIR pass run after borrow checking.
95 /// We don't want to have the exact structure of the decision tree be
96 /// visible through borrow checking. False edges ensure that the CFG as
97 /// seen by borrow checking doesn't encode this. False edges are added:
99 /// * From each prebinding block to the next prebinding block.
100 /// * From each otherwise block to the next prebinding block.
103 destination: &Place<'tcx>,
105 mut block: BasicBlock,
106 scrutinee: ExprRef<'tcx>,
107 arms: Vec<Arm<'tcx>>,
109 let tcx = self.hir.tcx();
111 // Step 1. Evaluate the scrutinee and add the fake read of it.
113 let scrutinee_span = scrutinee.span();
114 let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
116 // Matching on a `scrutinee_place` with an uninhabited type doesn't
117 // generate any memory reads by itself, and so if the place "expression"
118 // contains unsafe operations like raw pointer dereferences or union
119 // field projections, we wouldn't know to require an `unsafe` block
120 // around a `match` equivalent to `std::intrinsics::unreachable()`.
121 // See issue #47412 for this hole being discovered in the wild.
123 // HACK(eddyb) Work around the above issue by adding a dummy inspection
124 // of `scrutinee_place`, specifically by applying `ReadForMatch`.
126 // NOTE: ReadForMatch also checks that the scrutinee is initialized.
127 // This is currently needed to not allow matching on an uninitialized,
128 // uninhabited value. If we get never patterns, those will check that
129 // the place is initialized, and so this read would only be used to
132 let source_info = self.source_info(scrutinee_span);
133 self.cfg.push(block, Statement {
135 kind: StatementKind::FakeRead(
136 FakeReadCause::ForMatchedPlace,
137 scrutinee_place.clone(),
141 // Step 2. Create the otherwise and prebinding blocks.
143 // create binding start block for link them by false edges
144 let candidate_count = arms.iter().map(|c| c.patterns.len()).sum::<usize>();
145 let pre_binding_blocks: Vec<_> = (0..=candidate_count)
146 .map(|_| self.cfg.start_new_block())
149 // There's one more pre_binding block than there are candidates so that
150 // every candidate can have a `next_candidate_pre_binding_block`.
151 let outer_source_info = self.source_info(span);
153 *pre_binding_blocks.last().unwrap(),
155 TerminatorKind::Unreachable,
158 let mut match_has_guard = false;
160 let mut candidate_pre_binding_blocks = pre_binding_blocks.iter();
161 let mut next_candidate_pre_binding_blocks = pre_binding_blocks.iter().skip(1);
163 // Assemble a list of candidates: there is one candidate per pattern,
164 // which means there may be more than one candidate *per arm*.
165 let mut arm_candidates: Vec<_> = arms
168 let arm_has_guard = arm.guard.is_some();
169 match_has_guard |= arm_has_guard;
170 let arm_candidates: Vec<_> = arm.patterns
172 .zip(candidate_pre_binding_blocks.by_ref())
173 .zip(next_candidate_pre_binding_blocks.by_ref())
175 |((pattern, pre_binding_block), next_candidate_pre_binding_block)| {
179 MatchPair::new(scrutinee_place.clone(), pattern),
183 otherwise_block: if arm_has_guard {
184 Some(self.cfg.start_new_block())
188 pre_binding_block: *pre_binding_block,
189 next_candidate_pre_binding_block:
190 *next_candidate_pre_binding_block,
195 (arm, arm_candidates)
199 // Step 3. Create the decision tree and record the places that we bind or test.
201 // The set of places that we are creating fake borrows of. If there are
202 // no match guards then we don't need any fake borrows, so don't track
204 let mut fake_borrows = if match_has_guard && tcx.generate_borrow_of_any_match_input() {
205 Some(FxHashSet::default())
210 // These candidates are kept sorted such that the highest priority
211 // candidate comes first in the list. (i.e., same order as in source)
212 // As we gnerate the decision tree,
213 let candidates = &mut arm_candidates
215 .flat_map(|(_, candidates)| candidates)
216 .collect::<Vec<_>>();
218 // this will generate code to test scrutinee_place and
219 // branch to the appropriate arm block
220 let otherwise = self.match_candidates(
227 if !otherwise.is_empty() {
228 // All matches are exhaustive. However, because some matches
229 // only have exponentially-large exhaustive decision trees, we
230 // sometimes generate an inexhaustive decision tree.
232 // In that case, the inexhaustive tips of the decision tree
233 // can't be reached - terminate them with an `unreachable`.
234 let mut otherwise = otherwise;
236 otherwise.dedup(); // variant switches can introduce duplicate target blocks
237 for block in otherwise {
239 .terminate(block, outer_source_info, TerminatorKind::Unreachable);
243 // Step 4. Determine the fake borrows that are needed from the above
244 // places. Create the required temporaries for them.
246 let fake_borrow_temps = if let Some(ref borrows) = fake_borrows {
247 self.calculate_fake_borrows(borrows, scrutinee_span)
252 // Step 5. Create everything else: the guards and the arms.
254 let outer_source_info = self.source_info(span);
255 let arm_end_blocks: Vec<_> = arm_candidates.into_iter().map(|(arm, candidates)| {
256 let mut arm_block = self.cfg.start_new_block();
258 let body = self.hir.mirror(arm.body.clone());
259 let scope = self.declare_bindings(
262 LintLevel::Inherited,
264 ArmHasGuard(arm.guard.is_some()),
265 Some((Some(&scrutinee_place), scrutinee_span)),
268 for candidate in candidates {
269 self.bind_and_guard_matched_candidate(
278 if let Some(source_scope) = scope {
279 self.source_scope = source_scope;
282 unpack!(arm_block = self.into(destination, arm_block, body));
287 // all the arm blocks will rejoin here
288 let end_block = self.cfg.start_new_block();
290 for arm_block in arm_end_blocks {
294 TerminatorKind::Goto { target: end_block },
298 self.source_scope = outer_source_info.scope;
303 pub(super) fn expr_into_pattern(
305 mut block: BasicBlock,
306 irrefutable_pat: Pattern<'tcx>,
307 initializer: ExprRef<'tcx>,
309 match *irrefutable_pat.kind {
310 // Optimize the case of `let x = ...` to write directly into `x`
311 PatternKind::Binding {
312 mode: BindingMode::ByValue,
318 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
319 unpack!(block = self.into(&place, block, initializer));
322 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
323 let source_info = self.source_info(irrefutable_pat.span);
328 kind: StatementKind::FakeRead(FakeReadCause::ForLet, place),
332 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
336 // Optimize the case of `let x: T = ...` to write directly
337 // into `x` and then require that `T == typeof(x)`.
339 // Weirdly, this is needed to prevent the
340 // `intrinsic-move-val.rs` test case from crashing. That
341 // test works with uninitialized values in a rather
342 // dubious way, so it may be that the test is kind of
344 PatternKind::AscribeUserType {
345 subpattern: Pattern {
346 kind: box PatternKind::Binding {
347 mode: BindingMode::ByValue,
354 ascription: hair::pattern::Ascription {
355 user_ty: pat_ascription_ty,
361 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
362 unpack!(block = self.into(&place, block, initializer));
364 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
365 let pattern_source_info = self.source_info(irrefutable_pat.span);
369 source_info: pattern_source_info,
370 kind: StatementKind::FakeRead(FakeReadCause::ForLet, place.clone()),
374 let ty_source_info = self.source_info(user_ty_span);
375 let user_ty = box pat_ascription_ty.user_ty(
376 &mut self.canonical_user_type_annotations,
377 place.ty(&self.local_decls, self.hir.tcx()).ty,
383 source_info: ty_source_info,
384 kind: StatementKind::AscribeUserType(
386 // We always use invariant as the variance here. This is because the
387 // variance field from the ascription refers to the variance to use
388 // when applying the type to the value being matched, but this
389 // ascription applies rather to the type of the binding. e.g., in this
396 // We are creating an ascription that defines the type of `x` to be
397 // exactly `T` (i.e., with invariance). The variance field, in
398 // contrast, is intended to be used to relate `T` to the type of
400 ty::Variance::Invariant,
406 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
411 let place = unpack!(block = self.as_place(block, initializer));
412 self.place_into_pattern(block, irrefutable_pat, &place, true)
417 pub fn place_into_pattern(
420 irrefutable_pat: Pattern<'tcx>,
421 initializer: &Place<'tcx>,
422 set_match_place: bool,
424 // create a dummy candidate
425 let mut candidate = Candidate {
426 span: irrefutable_pat.span,
427 match_pairs: vec![MatchPair::new(initializer.clone(), &irrefutable_pat)],
431 // since we don't call `match_candidates`, next fields are unused
432 otherwise_block: None,
433 pre_binding_block: block,
434 next_candidate_pre_binding_block: block,
437 // Simplify the candidate. Since the pattern is irrefutable, this should
438 // always convert all match-pairs into bindings.
439 self.simplify_candidate(&mut candidate);
441 if !candidate.match_pairs.is_empty() {
442 // ICE if no other errors have been emitted. This used to be a hard error that wouldn't
443 // be reached because `hair::pattern::check_match::check_match` wouldn't have let the
444 // compiler continue. In our tests this is only ever hit by
445 // `ui/consts/const-match-check.rs` with `--cfg eval1`, and that file already generates
446 // a different error before hand.
447 self.hir.tcx().sess.delay_span_bug(
448 candidate.match_pairs[0].pattern.span,
450 "match pairs {:?} remaining after simplifying irrefutable pattern",
451 candidate.match_pairs,
456 // for matches and function arguments, the place that is being matched
457 // can be set when creating the variables. But the place for
458 // let PATTERN = ... might not even exist until we do the assignment.
459 // so we set it here instead
461 for binding in &candidate.bindings {
462 let local = self.var_local_id(binding.var_id, OutsideGuard);
464 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
465 opt_match_place: Some((ref mut match_place, _)),
467 }))) = self.local_decls[local].is_user_variable
469 *match_place = Some(initializer.clone());
471 bug!("Let binding to non-user variable.")
476 self.ascribe_types(block, &candidate.ascriptions);
478 // now apply the bindings, which will also declare the variables
479 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
484 /// Declares the bindings of the given patterns and returns the visibility
485 /// scope for the bindings in these patterns, if such a scope had to be
486 /// created. NOTE: Declaring the bindings should always be done in their
488 pub fn declare_bindings(
490 mut visibility_scope: Option<SourceScope>,
492 lint_level: LintLevel,
493 pattern: &Pattern<'tcx>,
494 has_guard: ArmHasGuard,
495 opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
496 ) -> Option<SourceScope> {
498 !(visibility_scope.is_some() && lint_level.is_explicit()),
499 "can't have both a visibility and a lint scope at the same time"
501 let mut scope = self.source_scope;
502 debug!("declare_bindings: pattern={:?}", pattern);
505 UserTypeProjections::none(),
506 &mut |this, mutability, name, mode, var, span, ty, user_ty| {
507 if visibility_scope.is_none() {
508 // If we have lints, create a new source scope
509 // that marks the lints for the locals. See the comment
510 // on the `source_info` field for why this is needed.
511 if lint_level.is_explicit() {
512 scope = this.new_source_scope(scope_span, lint_level, None);
514 visibility_scope = Some(this.new_source_scope(scope_span,
515 LintLevel::Inherited,
518 let source_info = SourceInfo { span, scope };
519 let visibility_scope = visibility_scope.unwrap();
520 this.declare_binding(
530 opt_match_place.map(|(x, y)| (x.cloned(), y)),
538 pub fn storage_live_binding(
545 let local_id = self.var_local_id(var, for_guard);
546 let source_info = self.source_info(span);
551 kind: StatementKind::StorageLive(local_id),
554 let place = Place::Base(PlaceBase::Local(local_id));
555 let var_ty = self.local_decls[local_id].ty;
556 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
557 self.schedule_drop(span, region_scope, &place, var_ty, DropKind::Storage);
561 pub fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
562 let local_id = self.var_local_id(var, for_guard);
563 let var_ty = self.local_decls[local_id].ty;
564 let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
568 &Place::Base(PlaceBase::Local(local_id)),
571 cached_block: CachedBlock::default(),
576 pub(super) fn visit_bindings(
578 pattern: &Pattern<'tcx>,
579 pattern_user_ty: UserTypeProjections,
591 debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
592 match *pattern.kind {
593 PatternKind::Binding {
602 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
603 if let Some(subpattern) = subpattern.as_ref() {
604 self.visit_bindings(subpattern, pattern_user_ty, f);
613 | PatternKind::Slice {
618 let from = u32::try_from(prefix.len()).unwrap();
619 let to = u32::try_from(suffix.len()).unwrap();
620 for subpattern in prefix {
621 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
623 for subpattern in slice {
624 self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
626 for subpattern in suffix {
627 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
631 PatternKind::Constant { .. } | PatternKind::Range { .. } | PatternKind::Wild => {}
633 PatternKind::Deref { ref subpattern } => {
634 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
637 PatternKind::AscribeUserType {
639 ascription: hair::pattern::Ascription {
645 // This corresponds to something like
648 // let A::<'a>(_): A<'static> = ...;
651 // Note that the variance doesn't apply here, as we are tracking the effect
652 // of `user_ty` on any bindings contained with subpattern.
653 let annotation = CanonicalUserTypeAnnotation {
655 user_ty: user_ty.user_ty,
656 inferred_ty: subpattern.ty,
658 let projection = UserTypeProjection {
659 base: self.canonical_user_type_annotations.push(annotation),
662 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
663 self.visit_bindings(subpattern, subpattern_user_ty, f)
666 PatternKind::Leaf { ref subpatterns } => {
667 for subpattern in subpatterns {
668 let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
669 debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
670 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
674 PatternKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
675 for subpattern in subpatterns {
676 let subpattern_user_ty = pattern_user_ty.clone().variant(
677 adt_def, variant_index, subpattern.field);
678 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
686 pub struct Candidate<'pat, 'tcx: 'pat> {
687 // span of the original pattern that gave rise to this candidate
690 // all of these must be satisfied...
691 match_pairs: Vec<MatchPair<'pat, 'tcx>>,
693 // ...these bindings established...
694 bindings: Vec<Binding<'tcx>>,
696 // ...and these types asserted...
697 ascriptions: Vec<Ascription<'tcx>>,
699 // ...and the guard must be evaluated, if false branch to Block...
700 otherwise_block: Option<BasicBlock>,
702 // ...and the blocks for add false edges between candidates
703 pre_binding_block: BasicBlock,
704 next_candidate_pre_binding_block: BasicBlock,
707 #[derive(Clone, Debug)]
708 struct Binding<'tcx> {
714 mutability: Mutability,
715 binding_mode: BindingMode,
718 /// Indicates that the type of `source` must be a subtype of the
719 /// user-given type `user_ty`; this is basically a no-op but can
720 /// influence region inference.
721 #[derive(Clone, Debug)]
722 struct Ascription<'tcx> {
725 user_ty: PatternTypeProjection<'tcx>,
726 variance: ty::Variance,
729 #[derive(Clone, Debug)]
730 pub struct MatchPair<'pat, 'tcx: 'pat> {
734 // ... must match this pattern.
735 pattern: &'pat Pattern<'tcx>,
738 #[derive(Clone, Debug, PartialEq)]
739 enum TestKind<'tcx> {
740 // test the branches of enum
742 adt_def: &'tcx ty::AdtDef,
743 variants: BitSet<VariantIdx>,
746 // test the branches of enum
750 indices: FxHashMap<ty::Const<'tcx>, usize>,
755 value: ty::Const<'tcx>,
759 // test whether the value falls within an inclusive or exclusive range
760 Range(PatternRange<'tcx>),
762 // test length of the slice is equal to len
770 pub struct Test<'tcx> {
772 kind: TestKind<'tcx>,
775 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
776 /// a match arm has a guard expression attached to it.
777 #[derive(Copy, Clone, Debug)]
778 pub(crate) struct ArmHasGuard(pub bool);
780 ///////////////////////////////////////////////////////////////////////////
781 // Main matching algorithm
783 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
784 /// The main match algorithm. It begins with a set of candidates
785 /// `candidates` and has the job of generating code to determine
786 /// which of these candidates, if any, is the correct one. The
787 /// candidates are sorted such that the first item in the list
788 /// has the highest priority. When a candidate is found to match
789 /// the value, we will generate a branch to the appropriate
790 /// prebinding block.
792 /// The return value is a list of "otherwise" blocks. These are
793 /// points in execution where we found that *NONE* of the
794 /// candidates apply. In principle, this means that the input
795 /// list was not exhaustive, though at present we sometimes are
796 /// not smart enough to recognize all exhaustive inputs.
798 /// It might be surprising that the input can be inexhaustive.
799 /// Indeed, initially, it is not, because all matches are
800 /// exhaustive in Rust. But during processing we sometimes divide
801 /// up the list of candidates and recurse with a non-exhaustive
802 /// list. This is important to keep the size of the generated code
803 /// under control. See `test_candidates` for more details.
805 /// If `fake_borrows` is Some, then places which need fake borrows
806 /// will be added to it.
807 fn match_candidates<'pat>(
810 candidates: &mut [&mut Candidate<'pat, 'tcx>],
811 mut block: BasicBlock,
812 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
813 ) -> Vec<BasicBlock> {
815 "matched_candidate(span={:?}, block={:?}, candidates={:?})",
816 span, block, candidates
819 // Start by simplifying candidates. Once this process is complete, all
820 // the match pairs which remain require some form of test, whether it
821 // be a switch or pattern comparison.
822 for candidate in &mut *candidates {
823 self.simplify_candidate(candidate);
826 // The candidates are sorted by priority. Check to see whether the
827 // higher priority candidates (and hence at the front of the slice)
828 // have satisfied all their match pairs.
829 let fully_matched = candidates
831 .take_while(|c| c.match_pairs.is_empty())
834 "match_candidates: {:?} candidates fully matched",
837 let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
839 if !matched_candidates.is_empty() {
840 block = if let Some(last_otherwise_block) = self.select_matched_candidates(
847 // Any remaining candidates are unreachable.
848 if unmatched_candidates.is_empty() {
851 self.cfg.start_new_block()
856 // If there are no candidates that still need testing, we're
857 // done. Since all matches are exhaustive, execution should
858 // never reach this point.
859 if unmatched_candidates.is_empty() {
863 // Test candidates where possible.
864 let (otherwise, untested_candidates) = self.test_candidates(
866 unmatched_candidates,
871 // If the target candidates were exhaustive, then we are done.
872 // But for borrowck continue build decision tree.
873 if untested_candidates.is_empty() {
877 // Otherwise, let's process those remaining candidates.
878 let join_block = self.join_otherwise_blocks(span, otherwise);
879 self.match_candidates(
887 /// Link up matched candidates. For example, if we have something like
891 /// Some(x) if cond => ...
893 /// Some(x) if cond => ...
896 /// We generate real edges from:
897 /// * `block` to the prebinding_block of the first pattern,
898 /// * the otherwise block of the first pattern to the second pattern,
899 /// * the otherwise block of the third pattern to the a block with an
900 /// Unreachable terminator.
902 /// As well as that we add fake edges from the otherwise blocks to the
903 /// prebinding block of the next candidate in the original set of
905 fn select_matched_candidates(
907 matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
909 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
910 ) -> Option<BasicBlock> {
912 !matched_candidates.is_empty(),
913 "select_matched_candidates called with no candidates",
916 // Insert a borrows of prefixes of places that are bound and are
917 // behind a dereference projection.
919 // These borrows are taken to avoid situations like the following:
922 // _ if { x = &[0]; false } => (),
923 // y => (), // Out of bounds array access!
927 // // y is bound by reference in the guard and then by copy in the
928 // // arm, so y is 2 in the arm!
929 // y if { y == 1 && (x = &2) == () } => y,
932 if let Some(fake_borrows) = fake_borrows {
933 for Binding { source, .. }
934 in matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
936 let mut cursor = source;
937 while let Place::Projection(box Projection { base, elem }) = cursor {
939 if let ProjectionElem::Deref = elem {
940 fake_borrows.insert(cursor.clone());
947 let fully_matched_with_guard = matched_candidates
949 .position(|c| c.otherwise_block.is_none())
950 .unwrap_or(matched_candidates.len() - 1);
952 let (reachable_candidates, unreachable_candidates)
953 = matched_candidates.split_at_mut(fully_matched_with_guard + 1);
955 let first_candidate = &reachable_candidates[0];
957 let candidate_source_info = self.source_info(first_candidate.span);
961 candidate_source_info,
962 TerminatorKind::Goto {
963 target: first_candidate.pre_binding_block,
967 for window in reachable_candidates.windows(2) {
968 if let [first_candidate, second_candidate] = window {
969 let source_info = self.source_info(first_candidate.span);
970 if let Some(otherwise_block) = first_candidate.otherwise_block {
974 TerminatorKind::FalseEdges {
975 real_target: second_candidate.pre_binding_block,
976 imaginary_targets: vec![
977 first_candidate.next_candidate_pre_binding_block
982 bug!("candidate other than the last has no guard");
985 bug!("<[_]>::windows returned incorrectly sized window");
989 debug!("match_candidates: add false edges for unreachable {:?}", unreachable_candidates);
990 for candidate in unreachable_candidates {
991 if let Some(otherwise) = candidate.otherwise_block {
992 let source_info = self.source_info(candidate.span);
993 let unreachable = self.cfg.start_new_block();
997 TerminatorKind::FalseEdges {
998 real_target: unreachable,
999 imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1002 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
1006 let last_candidate = reachable_candidates.last().unwrap();
1008 if let Some(otherwise) = last_candidate.otherwise_block {
1009 let source_info = self.source_info(last_candidate.span);
1010 let block = self.cfg.start_new_block();
1014 TerminatorKind::FalseEdges {
1016 imaginary_targets: vec![last_candidate.next_candidate_pre_binding_block]
1025 fn join_otherwise_blocks(&mut self, span: Span, mut otherwise: Vec<BasicBlock>) -> BasicBlock {
1026 let source_info = self.source_info(span);
1028 otherwise.dedup(); // variant switches can introduce duplicate target blocks
1029 if otherwise.len() == 1 {
1032 let join_block = self.cfg.start_new_block();
1033 for block in otherwise {
1037 TerminatorKind::Goto { target: join_block },
1044 /// This is the most subtle part of the matching algorithm. At
1045 /// this point, the input candidates have been fully simplified,
1046 /// and so we know that all remaining match-pairs require some
1047 /// sort of test. To decide what test to do, we take the highest
1048 /// priority candidate (last one in the list) and extract the
1049 /// first match-pair from the list. From this we decide what kind
1050 /// of test is needed using `test`, defined in the `test` module.
1052 /// *Note:* taking the first match pair is somewhat arbitrary, and
1053 /// we might do better here by choosing more carefully what to
1056 /// For example, consider the following possible match-pairs:
1058 /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
1059 /// 2. `x @ 22` -- we will do a `SwitchInt`
1060 /// 3. `x @ 3..5` -- we will do a range test
1063 /// Once we know what sort of test we are going to perform, this
1064 /// Tests may also help us with other candidates. So we walk over
1065 /// the candidates (from high to low priority) and check. This
1066 /// gives us, for each outcome of the test, a transformed list of
1067 /// candidates. For example, if we are testing the current
1068 /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
1069 /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
1070 /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
1071 /// simpler (and, in fact, irrefutable).
1073 /// But there may also be candidates that the test just doesn't
1074 /// apply to. The classical example involves wildcards:
1077 /// # let (x, y, z) = (true, true, true);
1078 /// match (x, y, z) {
1079 /// (true, _, true) => true, // (0)
1080 /// (_, true, _) => true, // (1)
1081 /// (false, false, _) => false, // (2)
1082 /// (true, _, false) => false, // (3)
1086 /// In that case, after we test on `x`, there are 2 overlapping candidate
1089 /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1090 /// - If the outcome is that `x` is false, candidates 1 and 2
1092 /// Here, the traditional "decision tree" method would generate 2
1093 /// separate code-paths for the 2 separate cases.
1095 /// In some cases, this duplication can create an exponential amount of
1096 /// code. This is most easily seen by noticing that this method terminates
1097 /// with precisely the reachable arms being reachable - but that problem
1098 /// is trivially NP-complete:
1101 /// match (var0, var1, var2, var3, ..) {
1102 /// (true, _, _, false, true, ...) => false,
1103 /// (_, true, true, false, _, ...) => false,
1104 /// (false, _, false, false, _, ...) => false,
1110 /// Here the last arm is reachable only if there is an assignment to
1111 /// the variables that does not match any of the literals. Therefore,
1112 /// compilation would take an exponential amount of time in some cases.
1114 /// That kind of exponential worst-case might not occur in practice, but
1115 /// our simplistic treatment of constants and guards would make it occur
1116 /// in very common situations - for example #29740:
1120 /// "foo" if foo_guard => ...,
1121 /// "bar" if bar_guard => ...,
1122 /// "baz" if baz_guard => ...,
1127 /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1129 /// It might seem that we would end up with 2 disjoint candidate
1130 /// sets, consisting of the first candidate or the other 3, but our
1131 /// algorithm doesn't reason about "foo" being distinct from the other
1132 /// constants; it considers the latter arms to potentially match after
1133 /// both outcomes, which obviously leads to an exponential amount
1136 /// To avoid these kinds of problems, our algorithm tries to ensure
1137 /// the amount of generated tests is linear. When we do a k-way test,
1138 /// we return an additional "unmatched" set alongside the obvious `k`
1139 /// sets. When we encounter a candidate that would be present in more
1140 /// than one of the sets, we put it and all candidates below it into the
1141 /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1143 /// After we perform our test, we branch into the appropriate candidate
1144 /// set and recurse with `match_candidates`. These sub-matches are
1145 /// obviously inexhaustive - as we discarded our otherwise set - so
1146 /// we set their continuation to do `match_candidates` on the
1147 /// "unmatched" set (which is again inexhaustive).
1149 /// If you apply this to the above test, you basically wind up
1150 /// with an if-else-if chain, testing each candidate in turn,
1151 /// which is precisely what we want.
1153 /// In addition to avoiding exponential-time blowups, this algorithm
1154 /// also has nice property that each guard and arm is only generated
1156 fn test_candidates<'pat, 'b, 'c>(
1159 mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1161 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1162 ) -> (Vec<BasicBlock>, &'b mut [&'c mut Candidate<'pat, 'tcx>]) {
1163 // extract the match-pair from the highest priority candidate
1164 let match_pair = &candidates.first().unwrap().match_pairs[0];
1165 let mut test = self.test(match_pair);
1166 let match_place = match_pair.place.clone();
1168 // most of the time, the test to perform is simply a function
1169 // of the main candidate; but for a test like SwitchInt, we
1170 // may want to add cases based on the candidates that are
1173 TestKind::SwitchInt {
1178 for candidate in candidates.iter() {
1179 if !self.add_cases_to_switch(
1194 for candidate in candidates.iter() {
1195 if !self.add_variants_to_switch(&match_place, candidate, variants) {
1203 // Insert a Shallow borrow of any places that is switched on.
1204 fake_borrows.as_mut().map(|fb| {
1205 fb.insert(match_place.clone())
1208 // perform the test, branching to one of N blocks. For each of
1209 // those N possible outcomes, create a (initially empty)
1210 // vector of candidates. Those are the candidates that still
1211 // apply if the test has that particular outcome.
1213 "match_candidates: test={:?} match_pair={:?}",
1216 let target_blocks = self.perform_test(block, &match_place, &test);
1217 let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1218 target_candidates.resize_with(target_blocks.len(), Default::default);
1220 let total_candidate_count = candidates.len();
1222 // Sort the candidates into the appropriate vector in
1223 // `target_candidates`. Note that at some point we may
1224 // encounter a candidate where the test is not relevant; at
1225 // that point, we stop sorting.
1226 while let Some(candidate) = candidates.first_mut() {
1227 if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1228 let (candidate, rest) = candidates.split_first_mut().unwrap();
1229 target_candidates[idx].push(candidate);
1235 // at least the first candidate ought to be tested
1236 assert!(total_candidate_count > candidates.len());
1237 debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1238 debug!("untested_candidates: {}", candidates.len());
1240 // For each outcome of test, process the candidates that still
1241 // apply. Collect a list of blocks where control flow will
1242 // branch if one of the `target_candidate` sets is not
1244 let otherwise: Vec<_> = target_blocks
1246 .zip(target_candidates)
1247 .flat_map(|(target_block, mut target_candidates)| {
1248 self.match_candidates(
1250 &mut *target_candidates,
1257 (otherwise, candidates)
1260 // Determine the fake borrows that are needed to ensure that the place
1261 // will evaluate to the same thing until an arm has been chosen.
1262 fn calculate_fake_borrows<'b>(
1264 fake_borrows: &'b FxHashSet<Place<'tcx>>,
1266 ) -> Vec<(&'b Place<'tcx>, Local)> {
1267 let tcx = self.hir.tcx();
1269 debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1271 let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1273 // Insert a Shallow borrow of the prefixes of any fake borrows.
1274 for place in fake_borrows
1276 let mut prefix_cursor = place;
1277 while let Place::Projection(box Projection { base, elem }) = prefix_cursor {
1278 if let ProjectionElem::Deref = elem {
1279 // Insert a shallow borrow after a deref. For other
1280 // projections the borrow of prefix_cursor will
1281 // conflict with any mutation of base.
1282 all_fake_borrows.push(base);
1284 prefix_cursor = base;
1287 all_fake_borrows.push(place);
1290 // Deduplicate and ensure a deterministic order.
1291 all_fake_borrows.sort();
1292 all_fake_borrows.dedup();
1294 debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1296 all_fake_borrows.into_iter().map(|matched_place| {
1297 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1298 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1299 let fake_borrow_temp = self.local_decls.push(
1300 LocalDecl::new_temp(fake_borrow_ty, temp_span)
1303 (matched_place, fake_borrow_temp)
1308 ///////////////////////////////////////////////////////////////////////////
1309 // Pattern binding - used for `let` and function parameters as well.
1311 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
1312 /// Initializes each of the bindings from the candidate by
1313 /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1314 /// any, and then branches to the arm. Returns the block for the case where
1315 /// the guard fails.
1317 /// Note: we check earlier that if there is a guard, there cannot be move
1318 /// bindings (unless feature(bind_by_move_pattern_guards) is used). This
1319 /// isn't really important for the self-consistency of this fn, but the
1320 /// reason for it should be clear: after we've done the assignments, if
1321 /// there were move bindings, further tests would be a use-after-move.
1322 /// bind_by_move_pattern_guards avoids this by only moving the binding once
1323 /// the guard has evaluated to true (see below).
1324 fn bind_and_guard_matched_candidate<'pat>(
1326 candidate: Candidate<'pat, 'tcx>,
1327 guard: Option<Guard<'tcx>>,
1328 arm_block: BasicBlock,
1329 fake_borrows: &Vec<(&Place<'tcx>, Local)>,
1330 scrutinee_span: Span,
1332 debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1334 debug_assert!(candidate.match_pairs.is_empty());
1336 let candidate_source_info = self.source_info(candidate.span);
1338 let mut block = self.cfg.start_new_block();
1340 candidate.pre_binding_block,
1341 candidate_source_info,
1342 TerminatorKind::FalseEdges {
1344 imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1347 self.ascribe_types(block, &candidate.ascriptions);
1349 // rust-lang/rust#27282: The `autoref` business deserves some
1350 // explanation here.
1352 // The intent of the `autoref` flag is that when it is true,
1353 // then any pattern bindings of type T will map to a `&T`
1354 // within the context of the guard expression, but will
1355 // continue to map to a `T` in the context of the arm body. To
1356 // avoid surfacing this distinction in the user source code
1357 // (which would be a severe change to the language and require
1358 // far more revision to the compiler), when `autoref` is true,
1359 // then any occurrence of the identifier in the guard
1360 // expression will automatically get a deref op applied to it.
1362 // So an input like:
1365 // let place = Foo::new();
1366 // match place { foo if inspect(foo)
1367 // => feed(foo), ... }
1370 // will be treated as if it were really something like:
1373 // let place = Foo::new();
1374 // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1375 // => { let tmp2 = place; feed(tmp2) }, ... }
1377 // And an input like:
1380 // let place = Foo::new();
1381 // match place { ref mut foo if inspect(foo)
1382 // => feed(foo), ... }
1385 // will be treated as if it were really something like:
1388 // let place = Foo::new();
1389 // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1390 // => { let tmp2 = &mut place; feed(tmp2) }, ... }
1393 // In short, any pattern binding will always look like *some*
1394 // kind of `&T` within the guard at least in terms of how the
1395 // MIR-borrowck views it, and this will ensure that guard
1396 // expressions cannot mutate their the match inputs via such
1397 // bindings. (It also ensures that guard expressions can at
1398 // most *copy* values from such bindings; non-Copy things
1399 // cannot be moved via pattern bindings in guard expressions.)
1403 // Implementation notes (under assumption `autoref` is true).
1405 // To encode the distinction above, we must inject the
1406 // temporaries `tmp1` and `tmp2`.
1408 // There are two cases of interest: binding by-value, and binding by-ref.
1410 // 1. Binding by-value: Things are simple.
1412 // * Establishing `tmp1` creates a reference into the
1413 // matched place. This code is emitted by
1414 // bind_matched_candidate_for_guard.
1416 // * `tmp2` is only initialized "lazily", after we have
1417 // checked the guard. Thus, the code that can trigger
1418 // moves out of the candidate can only fire after the
1419 // guard evaluated to true. This initialization code is
1420 // emitted by bind_matched_candidate_for_arm.
1422 // 2. Binding by-reference: Things are tricky.
1424 // * Here, the guard expression wants a `&&` or `&&mut`
1425 // into the original input. This means we need to borrow
1426 // the reference that we create for the arm.
1427 // * So we eagerly create the reference for the arm and then take a
1428 // reference to that.
1429 if let Some(guard) = guard {
1430 let tcx = self.hir.tcx();
1432 self.bind_matched_candidate_for_guard(
1434 &candidate.bindings,
1436 let guard_frame = GuardFrame {
1440 .map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode))
1443 debug!("Entering guard building context: {:?}", guard_frame);
1444 self.guard_context.push(guard_frame);
1446 let re_erased = tcx.lifetimes.re_erased;
1447 let scrutinee_source_info = self.source_info(scrutinee_span);
1448 for &(place, temp) in fake_borrows {
1449 let borrow = Rvalue::Ref(
1451 BorrowKind::Shallow,
1454 self.cfg.push_assign(
1456 scrutinee_source_info,
1457 &Place::Base(PlaceBase::Local(temp)),
1462 // the block to branch to if the guard fails; if there is no
1463 // guard, this block is simply unreachable
1464 let guard = match guard {
1465 Guard::If(e) => self.hir.mirror(e),
1467 let source_info = self.source_info(guard.span);
1468 let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1469 let cond = unpack!(block = self.as_local_operand(block, guard));
1470 let guard_frame = self.guard_context.pop().unwrap();
1472 "Exiting guard building context with locals: {:?}",
1476 for &(_, temp) in fake_borrows {
1477 self.cfg.push(block, Statement {
1478 source_info: guard_end,
1479 kind: StatementKind::FakeRead(
1480 FakeReadCause::ForMatchGuard,
1481 Place::Base(PlaceBase::Local(temp)),
1486 // We want to ensure that the matched candidates are bound
1487 // after we have confirmed this candidate *and* any
1488 // associated guard; Binding them on `block` is too soon,
1489 // because that would be before we've checked the result
1492 // But binding them on `arm_block` is *too late*, because
1493 // then all of the candidates for a single arm would be
1494 // bound in the same place, that would cause a case like:
1498 // (mut x, 1) | (2, mut x) if { true } => { ... }
1499 // ... // ^^^^^^^ (this is `arm_block`)
1503 // would yield a `arm_block` something like:
1506 // StorageLive(_4); // _4 is `x`
1507 // _4 = &mut (_1.0: i32); // this is handling `(mut x, 1)` case
1508 // _4 = &mut (_1.1: i32); // this is handling `(2, mut x)` case
1511 // and that is clearly not correct.
1512 let post_guard_block = self.cfg.start_new_block();
1516 TerminatorKind::if_(
1520 candidate.otherwise_block.unwrap()
1524 let by_value_bindings = candidate.bindings.iter().filter(|binding| {
1525 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1527 // Read all of the by reference bindings to ensure that the
1528 // place they refer to can't be modified by the guard.
1529 for binding in by_value_bindings.clone() {
1530 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1531 let place = Place::Base(PlaceBase::Local(local_id));
1535 source_info: guard_end,
1536 kind: StatementKind::FakeRead(FakeReadCause::ForGuardBinding, place),
1540 self.bind_matched_candidate_for_arm_body(
1548 TerminatorKind::Goto { target: arm_block },
1551 assert!(candidate.otherwise_block.is_none());
1552 // (Here, it is not too early to bind the matched
1553 // candidate on `block`, because there is no guard result
1554 // that we have to inspect before we bind them.)
1555 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1558 candidate_source_info,
1559 TerminatorKind::Goto { target: arm_block },
1564 /// Append `AscribeUserType` statements onto the end of `block`
1565 /// for each ascription
1566 fn ascribe_types<'pat>(
1569 ascriptions: &[Ascription<'tcx>],
1571 for ascription in ascriptions {
1572 let source_info = self.source_info(ascription.span);
1575 "adding user ascription at span {:?} of place {:?} and {:?}",
1581 let user_ty = box ascription.user_ty.clone().user_ty(
1582 &mut self.canonical_user_type_annotations,
1583 ascription.source.ty(&self.local_decls, self.hir.tcx()).ty,
1590 kind: StatementKind::AscribeUserType(
1591 ascription.source.clone(),
1592 ascription.variance,
1600 fn bind_matched_candidate_for_guard(
1603 bindings: &[Binding<'tcx>],
1605 debug!("bind_matched_candidate_for_guard(block={:?}, bindings={:?})", block, bindings);
1607 // Assign each of the bindings. Since we are binding for a
1608 // guard expression, this will never trigger moves out of the
1610 let re_erased = self.hir.tcx().lifetimes.re_erased;
1611 for binding in bindings {
1612 let source_info = self.source_info(binding.span);
1614 // For each pattern ident P of type T, `ref_for_guard` is
1615 // a reference R: &T pointing to the location matched by
1616 // the pattern, and every occurrence of P within a guard
1619 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1620 // Question: Why schedule drops if bindings are all
1622 // Answer: Because schedule_drop_for_binding also emits
1623 // StorageDead's for those locals.
1624 self.schedule_drop_for_binding(binding.var_id, binding.span, RefWithinGuard);
1625 match binding.binding_mode {
1626 BindingMode::ByValue => {
1627 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source.clone());
1629 .push_assign(block, source_info, &ref_for_guard, rvalue);
1631 BindingMode::ByRef(borrow_kind) => {
1632 let value_for_arm = self.storage_live_binding(
1638 self.schedule_drop_for_binding(
1644 let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source.clone());
1646 .push_assign(block, source_info, &value_for_arm, rvalue);
1647 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1649 .push_assign(block, source_info, &ref_for_guard, rvalue);
1655 fn bind_matched_candidate_for_arm_body<'b>(
1658 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1660 debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1662 let re_erased = self.hir.tcx().lifetimes.re_erased;
1663 // Assign each of the bindings. This may trigger moves out of the candidate.
1664 for binding in bindings {
1665 let source_info = self.source_info(binding.span);
1667 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1668 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1669 let rvalue = match binding.binding_mode {
1670 BindingMode::ByValue => {
1671 Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1673 BindingMode::ByRef(borrow_kind) => {
1674 Rvalue::Ref(re_erased, borrow_kind, binding.source.clone())
1677 self.cfg.push_assign(block, source_info, &local, rvalue);
1681 /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1682 /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1683 /// first local is a binding for occurrences of `var` in the guard, which
1684 /// will have type `&T`. The second local is a binding for occurrences of
1685 /// `var` in the arm body, which will have type `T`.
1688 source_info: SourceInfo,
1689 visibility_scope: SourceScope,
1690 mutability: Mutability,
1695 user_ty: UserTypeProjections,
1696 has_guard: ArmHasGuard,
1697 opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1701 "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1702 visibility_scope={:?}, source_info={:?})",
1703 var_id, name, mode, var_ty, visibility_scope, source_info
1706 let tcx = self.hir.tcx();
1707 let binding_mode = match mode {
1708 BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1709 BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1711 debug!("declare_binding: user_ty={:?}", user_ty);
1712 let local = LocalDecl::<'tcx> {
1720 is_block_tail: None,
1721 is_user_variable: Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1723 // hypothetically, `visit_bindings` could try to unzip
1724 // an outermost hir::Ty as we descend, matching up
1725 // idents in pat; but complex w/ unclear UI payoff.
1726 // Instead, just abandon providing diagnostic info.
1732 let for_arm_body = self.local_decls.push(local.clone());
1733 let locals = if has_guard.0 {
1734 let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1735 // This variable isn't mutated but has a name, so has to be
1736 // immutable to avoid the unused mut lint.
1737 mutability: Mutability::Not,
1738 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
1739 user_ty: UserTypeProjections::none(),
1744 is_block_tail: None,
1745 is_user_variable: Some(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1747 LocalsForNode::ForGuard {
1752 LocalsForNode::One(for_arm_body)
1754 debug!("declare_binding: vars={:?}", locals);
1755 self.var_indices.insert(var_id, locals);