]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/matches/mod.rs
0aabebcf9dc2c17636c086a61b7a2a4517c7ec68
[rust.git] / src / librustc_mir / build / matches / mod.rs
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.
4 //!
5 //! This also includes code for pattern bindings in `let` statements and
6 //! function parameters.
7
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::hir::HirId;
14 use rustc::mir::*;
15 use rustc::middle::region;
16 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty};
17 use rustc::ty::layout::VariantIdx;
18 use rustc_data_structures::bit_set::BitSet;
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use syntax::ast::Name;
21 use syntax_pos::Span;
22
23 // helper functions, broken out by category:
24 mod simplify;
25 mod test;
26 mod util;
27
28 use std::convert::TryFrom;
29
30 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
31     /// Generates MIR for a `match` expression.
32     ///
33     /// The MIR that we generate for a match looks like this.
34     ///
35     /// ```text
36     /// [ 0. Pre-match ]
37     ///        |
38     /// [ 1. Evaluate Scrutinee (expression being matched on) ]
39     /// [ (fake read of scrutinee) ]
40     ///        |
41     /// [ 2. Decision tree -- check discriminants ] <--------+
42     ///        |                                             |
43     ///        | (once a specific arm is chosen)             |
44     ///        |                                             |
45     /// [pre_binding_block]                           [otherwise_block]
46     ///        |                                             |
47     /// [ 3. Create "guard bindings" for arm ]               |
48     /// [ (create fake borrows) ]                            |
49     ///        |                                             |
50     /// [ 4. Execute guard code ]                            |
51     /// [ (read fake borrows) ] --(guard is false)-----------+
52     ///        |
53     ///        | (guard results in true)
54     ///        |
55     /// [ 5. Create real bindings and execute arm ]
56     ///        |
57     /// [ Exit match ]
58     /// ```
59     ///
60     /// All of the different arms have been stacked on top of each other to
61     /// simplify the diagram. For an arm with no guard the blocks marked 3 and
62     /// 4 and the fake borrows are omitted.
63     ///
64     /// We generate MIR in the following steps:
65     ///
66     /// 1. Evaluate the scrutinee and add the fake read of it.
67     /// 2. Create the prebinding and otherwise blocks.
68     /// 3. Create the decision tree and record the places that we bind or test.
69     /// 4. Determine the fake borrows that are needed from the above places.
70     ///    Create the required temporaries for them.
71     /// 5. Create everything else: Create everything else: the guards and the
72     ///    arms.
73     ///
74     /// ## Fake Reads and borrows
75     ///
76     /// Match exhaustiveness checking is not able to handle the case where the
77     /// place being matched on is mutated in the guards. There is an AST check
78     /// that tries to stop this but it is buggy and overly restrictive. Instead
79     /// we add "fake borrows" to the guards that prevent any mutation of the
80     /// place being matched. There are a some subtleties:
81     ///
82     /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
83     ///    refence, the borrow isn't even tracked. As such we have to add fake
84     ///    borrows of any prefixes of a place
85     /// 2. We don't want `match x { _ => (), }` to conflict with mutable
86     ///    borrows of `x`, so we only add fake borrows for places which are
87     ///    bound or tested by the match.
88     /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
89     ///    so we use a special BorrowKind for them.
90     /// 4. The fake borrows may be of places in inactive variants, so it would
91     ///    be UB to generate code for them. They therefore have to be removed
92     ///    by a MIR pass run after borrow checking.
93     ///
94     /// ## False edges
95     ///
96     /// We don't want to have the exact structure of the decision tree be
97     /// visible through borrow checking. False edges ensure that the CFG as
98     /// seen by borrow checking doesn't encode this. False edges are added:
99     ///
100     /// * From each prebinding block to the next prebinding block.
101     /// * From each otherwise block to the next prebinding block.
102     pub fn match_expr(
103         &mut self,
104         destination: &Place<'tcx>,
105         span: Span,
106         mut block: BasicBlock,
107         scrutinee: ExprRef<'tcx>,
108         arms: Vec<Arm<'tcx>>,
109     ) -> BlockAnd<()> {
110         let tcx = self.hir.tcx();
111
112         // Step 1. Evaluate the scrutinee and add the fake read of it.
113
114         let scrutinee_span = scrutinee.span();
115         let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
116
117         // Matching on a `scrutinee_place` with an uninhabited type doesn't
118         // generate any memory reads by itself, and so if the place "expression"
119         // contains unsafe operations like raw pointer dereferences or union
120         // field projections, we wouldn't know to require an `unsafe` block
121         // around a `match` equivalent to `std::intrinsics::unreachable()`.
122         // See issue #47412 for this hole being discovered in the wild.
123         //
124         // HACK(eddyb) Work around the above issue by adding a dummy inspection
125         // of `scrutinee_place`, specifically by applying `ReadForMatch`.
126         //
127         // NOTE: ReadForMatch also checks that the scrutinee is initialized.
128         // This is currently needed to not allow matching on an uninitialized,
129         // uninhabited value. If we get never patterns, those will check that
130         // the place is initialized, and so this read would only be used to
131         // check safety.
132
133         let source_info = self.source_info(scrutinee_span);
134         self.cfg.push(block, Statement {
135             source_info,
136             kind: StatementKind::FakeRead(
137                 FakeReadCause::ForMatchedPlace,
138                 scrutinee_place.clone(),
139             ),
140         });
141
142         // Step 2. Create the otherwise and prebinding blocks.
143
144         // create binding start block for link them by false edges
145         let candidate_count = arms.iter().map(|c| c.patterns.len()).sum::<usize>();
146         let pre_binding_blocks: Vec<_> = (0..=candidate_count)
147             .map(|_| self.cfg.start_new_block())
148             .collect();
149
150         // There's one more pre_binding block than there are candidates so that
151         // every candidate can have a `next_candidate_pre_binding_block`.
152         let outer_source_info = self.source_info(span);
153         self.cfg.terminate(
154             *pre_binding_blocks.last().unwrap(),
155             outer_source_info,
156             TerminatorKind::Unreachable,
157         );
158
159         let mut match_has_guard = false;
160
161         let mut candidate_pre_binding_blocks = pre_binding_blocks.iter();
162         let mut next_candidate_pre_binding_blocks = pre_binding_blocks.iter().skip(1);
163
164         // Assemble a list of candidates: there is one candidate per pattern,
165         // which means there may be more than one candidate *per arm*.
166         let mut arm_candidates: Vec<_> = arms
167             .iter()
168             .map(|arm| {
169                 let arm_has_guard = arm.guard.is_some();
170                 match_has_guard |= arm_has_guard;
171                 let arm_candidates: Vec<_> = arm.patterns
172                     .iter()
173                     .zip(candidate_pre_binding_blocks.by_ref())
174                     .zip(next_candidate_pre_binding_blocks.by_ref())
175                     .map(
176                         |((pattern, pre_binding_block), next_candidate_pre_binding_block)| {
177                             Candidate {
178                                 span: pattern.span,
179                                 match_pairs: vec![
180                                     MatchPair::new(scrutinee_place.clone(), pattern),
181                                 ],
182                                 bindings: vec![],
183                                 ascriptions: vec![],
184                                 otherwise_block: if arm_has_guard {
185                                     Some(self.cfg.start_new_block())
186                                 } else {
187                                     None
188                                 },
189                                 pre_binding_block: *pre_binding_block,
190                                 next_candidate_pre_binding_block:
191                                     *next_candidate_pre_binding_block,
192                             }
193                         },
194                     )
195                     .collect();
196                 (arm, arm_candidates)
197             })
198             .collect();
199
200         // Step 3. Create the decision tree and record the places that we bind or test.
201
202         // The set of places that we are creating fake borrows of. If there are
203         // no match guards then we don't need any fake borrows, so don't track
204         // them.
205         let mut fake_borrows = if match_has_guard && tcx.generate_borrow_of_any_match_input() {
206             Some(FxHashSet::default())
207         } else {
208             None
209         };
210
211         // These candidates are kept sorted such that the highest priority
212         // candidate comes first in the list. (i.e., same order as in source)
213         // As we gnerate the decision tree,
214         let candidates = &mut arm_candidates
215             .iter_mut()
216             .flat_map(|(_, candidates)| candidates)
217             .collect::<Vec<_>>();
218
219         // this will generate code to test scrutinee_place and
220         // branch to the appropriate arm block
221         let otherwise = self.match_candidates(
222             scrutinee_span,
223             candidates,
224             block,
225             &mut fake_borrows,
226         );
227
228         if !otherwise.is_empty() {
229             // All matches are exhaustive. However, because some matches
230             // only have exponentially-large exhaustive decision trees, we
231             // sometimes generate an inexhaustive decision tree.
232             //
233             // In that case, the inexhaustive tips of the decision tree
234             // can't be reached - terminate them with an `unreachable`.
235             let mut otherwise = otherwise;
236             otherwise.sort();
237             otherwise.dedup(); // variant switches can introduce duplicate target blocks
238             for block in otherwise {
239                 self.cfg
240                     .terminate(block, outer_source_info, TerminatorKind::Unreachable);
241             }
242         }
243
244         // Step 4. Determine the fake borrows that are needed from the above
245         // places. Create the required temporaries for them.
246
247         let fake_borrow_temps = if let Some(ref borrows) = fake_borrows {
248             self.calculate_fake_borrows(borrows, scrutinee_span)
249         } else {
250             Vec::new()
251         };
252
253         // Step 5. Create everything else: the guards and the arms.
254
255         let arm_end_blocks: Vec<_> = arm_candidates.into_iter().map(|(arm, candidates)| {
256             let arm_source_info = self.source_info(arm.span);
257             let region_scope = (arm.scope, arm_source_info);
258             self.in_scope(region_scope, arm.lint_level, |this| {
259                 let arm_block = this.cfg.start_new_block();
260
261                 let body = this.hir.mirror(arm.body.clone());
262                 let scope = this.declare_bindings(
263                     None,
264                     arm.span,
265                     &arm.patterns[0],
266                     ArmHasGuard(arm.guard.is_some()),
267                     Some((Some(&scrutinee_place), scrutinee_span)),
268                 );
269
270                 if let Some(source_scope) = scope {
271                     this.source_scope = source_scope;
272                 }
273
274                 for candidate in candidates {
275                     this.clear_top_scope(arm.scope);
276                     this.bind_and_guard_matched_candidate(
277                         candidate,
278                         arm.guard.clone(),
279                         arm_block,
280                         &fake_borrow_temps,
281                         scrutinee_span,
282                         region_scope,
283                     );
284                 }
285
286                 this.into(destination, arm_block, body)
287             })
288         }).collect();
289
290         // all the arm blocks will rejoin here
291         let end_block = self.cfg.start_new_block();
292
293         for arm_block in arm_end_blocks {
294             self.cfg.terminate(
295                 unpack!(arm_block),
296                 outer_source_info,
297                 TerminatorKind::Goto { target: end_block },
298             );
299         }
300
301         self.source_scope = outer_source_info.scope;
302
303         end_block.unit()
304     }
305
306     pub(super) fn expr_into_pattern(
307         &mut self,
308         mut block: BasicBlock,
309         irrefutable_pat: Pattern<'tcx>,
310         initializer: ExprRef<'tcx>,
311     ) -> BlockAnd<()> {
312         match *irrefutable_pat.kind {
313             // Optimize the case of `let x = ...` to write directly into `x`
314             PatternKind::Binding {
315                 mode: BindingMode::ByValue,
316                 var,
317                 subpattern: None,
318                 ..
319             } => {
320                 let place =
321                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
322                 unpack!(block = self.into(&place, block, initializer));
323
324
325                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
326                 let source_info = self.source_info(irrefutable_pat.span);
327                 self.cfg.push(
328                     block,
329                     Statement {
330                         source_info,
331                         kind: StatementKind::FakeRead(FakeReadCause::ForLet, place),
332                     },
333                 );
334
335                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
336                 block.unit()
337             }
338
339             // Optimize the case of `let x: T = ...` to write directly
340             // into `x` and then require that `T == typeof(x)`.
341             //
342             // Weirdly, this is needed to prevent the
343             // `intrinsic-move-val.rs` test case from crashing. That
344             // test works with uninitialized values in a rather
345             // dubious way, so it may be that the test is kind of
346             // broken.
347             PatternKind::AscribeUserType {
348                 subpattern: Pattern {
349                     kind: box PatternKind::Binding {
350                         mode: BindingMode::ByValue,
351                         var,
352                         subpattern: None,
353                         ..
354                     },
355                     ..
356                 },
357                 ascription: hair::pattern::Ascription {
358                     user_ty: pat_ascription_ty,
359                     variance: _,
360                     user_ty_span,
361                 },
362             } => {
363                 let place =
364                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
365                 unpack!(block = self.into(&place, block, initializer));
366
367                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
368                 let pattern_source_info = self.source_info(irrefutable_pat.span);
369                 self.cfg.push(
370                     block,
371                     Statement {
372                         source_info: pattern_source_info,
373                         kind: StatementKind::FakeRead(FakeReadCause::ForLet, place.clone()),
374                     },
375                 );
376
377                 let ty_source_info = self.source_info(user_ty_span);
378                 let user_ty = box pat_ascription_ty.user_ty(
379                     &mut self.canonical_user_type_annotations,
380                     place.ty(&self.local_decls, self.hir.tcx()).ty,
381                     ty_source_info.span,
382                 );
383                 self.cfg.push(
384                     block,
385                     Statement {
386                         source_info: ty_source_info,
387                         kind: StatementKind::AscribeUserType(
388                             place,
389                             // We always use invariant as the variance here. This is because the
390                             // variance field from the ascription refers to the variance to use
391                             // when applying the type to the value being matched, but this
392                             // ascription applies rather to the type of the binding. e.g., in this
393                             // example:
394                             //
395                             // ```
396                             // let x: T = <expr>
397                             // ```
398                             //
399                             // We are creating an ascription that defines the type of `x` to be
400                             // exactly `T` (i.e., with invariance). The variance field, in
401                             // contrast, is intended to be used to relate `T` to the type of
402                             // `<expr>`.
403                             ty::Variance::Invariant,
404                             user_ty,
405                         ),
406                     },
407                 );
408
409                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
410                 block.unit()
411             }
412
413             _ => {
414                 let place = unpack!(block = self.as_place(block, initializer));
415                 self.place_into_pattern(block, irrefutable_pat, &place, true)
416             }
417         }
418     }
419
420     pub fn place_into_pattern(
421         &mut self,
422         block: BasicBlock,
423         irrefutable_pat: Pattern<'tcx>,
424         initializer: &Place<'tcx>,
425         set_match_place: bool,
426     ) -> BlockAnd<()> {
427         // create a dummy candidate
428         let mut candidate = Candidate {
429             span: irrefutable_pat.span,
430             match_pairs: vec![MatchPair::new(initializer.clone(), &irrefutable_pat)],
431             bindings: vec![],
432             ascriptions: vec![],
433
434             // since we don't call `match_candidates`, next fields are unused
435             otherwise_block: None,
436             pre_binding_block: block,
437             next_candidate_pre_binding_block: block,
438         };
439
440         // Simplify the candidate. Since the pattern is irrefutable, this should
441         // always convert all match-pairs into bindings.
442         self.simplify_candidate(&mut candidate);
443
444         if !candidate.match_pairs.is_empty() {
445             // ICE if no other errors have been emitted. This used to be a hard error that wouldn't
446             // be reached because `hair::pattern::check_match::check_match` wouldn't have let the
447             // compiler continue. In our tests this is only ever hit by
448             // `ui/consts/const-match-check.rs` with `--cfg eval1`, and that file already generates
449             // a different error before hand.
450             self.hir.tcx().sess.delay_span_bug(
451                 candidate.match_pairs[0].pattern.span,
452                 &format!(
453                     "match pairs {:?} remaining after simplifying irrefutable pattern",
454                     candidate.match_pairs,
455                 ),
456             );
457         }
458
459         // for matches and function arguments, the place that is being matched
460         // can be set when creating the variables. But the place for
461         // let PATTERN = ... might not even exist until we do the assignment.
462         // so we set it here instead
463         if set_match_place {
464             for binding in &candidate.bindings {
465                 let local = self.var_local_id(binding.var_id, OutsideGuard);
466
467                 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
468                     opt_match_place: Some((ref mut match_place, _)),
469                     ..
470                 }))) = self.local_decls[local].is_user_variable
471                 {
472                     *match_place = Some(initializer.clone());
473                 } else {
474                     bug!("Let binding to non-user variable.")
475                 }
476             }
477         }
478
479         self.ascribe_types(block, &candidate.ascriptions);
480
481         // now apply the bindings, which will also declare the variables
482         self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
483
484         block.unit()
485     }
486
487     /// Declares the bindings of the given patterns and returns the visibility
488     /// scope for the bindings in these patterns, if such a scope had to be
489     /// created. NOTE: Declaring the bindings should always be done in their
490     /// drop scope.
491     pub fn declare_bindings(
492         &mut self,
493         mut visibility_scope: Option<SourceScope>,
494         scope_span: Span,
495         pattern: &Pattern<'tcx>,
496         has_guard: ArmHasGuard,
497         opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
498     ) -> Option<SourceScope> {
499         debug!("declare_bindings: pattern={:?}", pattern);
500         self.visit_bindings(
501             &pattern,
502             UserTypeProjections::none(),
503             &mut |this, mutability, name, mode, var, span, ty, user_ty| {
504                 if visibility_scope.is_none() {
505                     visibility_scope =
506                         Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
507                 }
508                 let source_info = SourceInfo { span, scope: this.source_scope };
509                 let visibility_scope = visibility_scope.unwrap();
510                 this.declare_binding(
511                     source_info,
512                     visibility_scope,
513                     mutability,
514                     name,
515                     mode,
516                     var,
517                     ty,
518                     user_ty,
519                     has_guard,
520                     opt_match_place.map(|(x, y)| (x.cloned(), y)),
521                     pattern.span,
522                 );
523             },
524         );
525         visibility_scope
526     }
527
528     pub fn storage_live_binding(
529         &mut self,
530         block: BasicBlock,
531         var: HirId,
532         span: Span,
533         for_guard: ForGuard,
534     ) -> Place<'tcx> {
535         let local_id = self.var_local_id(var, for_guard);
536         let source_info = self.source_info(span);
537         self.cfg.push(
538             block,
539             Statement {
540                 source_info,
541                 kind: StatementKind::StorageLive(local_id),
542             },
543         );
544         let place = Place::Base(PlaceBase::Local(local_id));
545         let var_ty = self.local_decls[local_id].ty;
546         let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
547         self.schedule_drop(span, region_scope, &place, var_ty, DropKind::Storage);
548         place
549     }
550
551     pub fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
552         let local_id = self.var_local_id(var, for_guard);
553         let var_ty = self.local_decls[local_id].ty;
554         let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
555         self.schedule_drop(
556             span,
557             region_scope,
558             &Place::Base(PlaceBase::Local(local_id)),
559             var_ty,
560             DropKind::Value,
561         );
562     }
563
564     pub(super) fn visit_bindings(
565         &mut self,
566         pattern: &Pattern<'tcx>,
567         pattern_user_ty: UserTypeProjections,
568         f: &mut impl FnMut(
569             &mut Self,
570             Mutability,
571             Name,
572             BindingMode,
573             HirId,
574             Span,
575             Ty<'tcx>,
576             UserTypeProjections,
577         ),
578     ) {
579         debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
580         match *pattern.kind {
581             PatternKind::Binding {
582                 mutability,
583                 name,
584                 mode,
585                 var,
586                 ty,
587                 ref subpattern,
588                 ..
589             } => {
590                 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
591                 if let Some(subpattern) = subpattern.as_ref() {
592                     self.visit_bindings(subpattern, pattern_user_ty, f);
593                 }
594             }
595
596             PatternKind::Array {
597                 ref prefix,
598                 ref slice,
599                 ref suffix,
600             }
601             | PatternKind::Slice {
602                 ref prefix,
603                 ref slice,
604                 ref suffix,
605             } => {
606                 let from = u32::try_from(prefix.len()).unwrap();
607                 let to = u32::try_from(suffix.len()).unwrap();
608                 for subpattern in prefix {
609                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
610                 }
611                 for subpattern in slice {
612                     self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
613                 }
614                 for subpattern in suffix {
615                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
616                 }
617             }
618
619             PatternKind::Constant { .. } | PatternKind::Range { .. } | PatternKind::Wild => {}
620
621             PatternKind::Deref { ref subpattern } => {
622                 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
623             }
624
625             PatternKind::AscribeUserType {
626                 ref subpattern,
627                 ascription: hair::pattern::Ascription {
628                     ref user_ty,
629                     user_ty_span,
630                     variance: _,
631                 },
632             } => {
633                 // This corresponds to something like
634                 //
635                 // ```
636                 // let A::<'a>(_): A<'static> = ...;
637                 // ```
638                 //
639                 // Note that the variance doesn't apply here, as we are tracking the effect
640                 // of `user_ty` on any bindings contained with subpattern.
641                 let annotation = CanonicalUserTypeAnnotation {
642                     span: user_ty_span,
643                     user_ty: user_ty.user_ty,
644                     inferred_ty: subpattern.ty,
645                 };
646                 let projection = UserTypeProjection {
647                     base: self.canonical_user_type_annotations.push(annotation),
648                     projs: Vec::new(),
649                 };
650                 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
651                 self.visit_bindings(subpattern, subpattern_user_ty, f)
652             }
653
654             PatternKind::Leaf { ref subpatterns } => {
655                 for subpattern in subpatterns {
656                     let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
657                     debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
658                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
659                 }
660             }
661
662             PatternKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
663                 for subpattern in subpatterns {
664                     let subpattern_user_ty = pattern_user_ty.clone().variant(
665                         adt_def, variant_index, subpattern.field);
666                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
667                 }
668             }
669         }
670     }
671 }
672
673 #[derive(Debug)]
674 pub struct Candidate<'pat, 'tcx: 'pat> {
675     // span of the original pattern that gave rise to this candidate
676     span: Span,
677
678     // all of these must be satisfied...
679     match_pairs: Vec<MatchPair<'pat, 'tcx>>,
680
681     // ...these bindings established...
682     bindings: Vec<Binding<'tcx>>,
683
684     // ...and these types asserted...
685     ascriptions: Vec<Ascription<'tcx>>,
686
687     // ...and the guard must be evaluated, if false branch to Block...
688     otherwise_block: Option<BasicBlock>,
689
690     // ...and the blocks for add false edges between candidates
691     pre_binding_block: BasicBlock,
692     next_candidate_pre_binding_block: BasicBlock,
693 }
694
695 #[derive(Clone, Debug)]
696 struct Binding<'tcx> {
697     span: Span,
698     source: Place<'tcx>,
699     name: Name,
700     var_id: HirId,
701     var_ty: Ty<'tcx>,
702     mutability: Mutability,
703     binding_mode: BindingMode,
704 }
705
706 /// Indicates that the type of `source` must be a subtype of the
707 /// user-given type `user_ty`; this is basically a no-op but can
708 /// influence region inference.
709 #[derive(Clone, Debug)]
710 struct Ascription<'tcx> {
711     span: Span,
712     source: Place<'tcx>,
713     user_ty: PatternTypeProjection<'tcx>,
714     variance: ty::Variance,
715 }
716
717 #[derive(Clone, Debug)]
718 pub struct MatchPair<'pat, 'tcx: 'pat> {
719     // this place...
720     place: Place<'tcx>,
721
722     // ... must match this pattern.
723     pattern: &'pat Pattern<'tcx>,
724 }
725
726 #[derive(Clone, Debug, PartialEq)]
727 enum TestKind<'tcx> {
728     // test the branches of enum
729     Switch {
730         adt_def: &'tcx ty::AdtDef,
731         variants: BitSet<VariantIdx>,
732     },
733
734     // test the branches of enum
735     SwitchInt {
736         switch_ty: Ty<'tcx>,
737         options: Vec<u128>,
738         indices: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
739     },
740
741     // test for equality
742     Eq {
743         value: &'tcx ty::Const<'tcx>,
744         ty: Ty<'tcx>,
745     },
746
747     // test whether the value falls within an inclusive or exclusive range
748     Range(PatternRange<'tcx>),
749
750     // test length of the slice is equal to len
751     Len {
752         len: u64,
753         op: BinOp,
754     },
755 }
756
757 #[derive(Debug)]
758 pub struct Test<'tcx> {
759     span: Span,
760     kind: TestKind<'tcx>,
761 }
762
763 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
764 /// a match arm has a guard expression attached to it.
765 #[derive(Copy, Clone, Debug)]
766 pub(crate) struct ArmHasGuard(pub bool);
767
768 ///////////////////////////////////////////////////////////////////////////
769 // Main matching algorithm
770
771 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
772     /// The main match algorithm. It begins with a set of candidates
773     /// `candidates` and has the job of generating code to determine
774     /// which of these candidates, if any, is the correct one. The
775     /// candidates are sorted such that the first item in the list
776     /// has the highest priority. When a candidate is found to match
777     /// the value, we will generate a branch to the appropriate
778     /// prebinding block.
779     ///
780     /// The return value is a list of "otherwise" blocks. These are
781     /// points in execution where we found that *NONE* of the
782     /// candidates apply. In principle, this means that the input
783     /// list was not exhaustive, though at present we sometimes are
784     /// not smart enough to recognize all exhaustive inputs.
785     ///
786     /// It might be surprising that the input can be inexhaustive.
787     /// Indeed, initially, it is not, because all matches are
788     /// exhaustive in Rust. But during processing we sometimes divide
789     /// up the list of candidates and recurse with a non-exhaustive
790     /// list. This is important to keep the size of the generated code
791     /// under control. See `test_candidates` for more details.
792     ///
793     /// If `fake_borrows` is Some, then places which need fake borrows
794     /// will be added to it.
795     fn match_candidates<'pat>(
796         &mut self,
797         span: Span,
798         candidates: &mut [&mut Candidate<'pat, 'tcx>],
799         mut block: BasicBlock,
800         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
801     ) -> Vec<BasicBlock> {
802         debug!(
803             "matched_candidate(span={:?}, block={:?}, candidates={:?})",
804             span, block, candidates
805         );
806
807         // Start by simplifying candidates. Once this process is complete, all
808         // the match pairs which remain require some form of test, whether it
809         // be a switch or pattern comparison.
810         for candidate in &mut *candidates {
811             self.simplify_candidate(candidate);
812         }
813
814         // The candidates are sorted by priority. Check to see whether the
815         // higher priority candidates (and hence at the front of the slice)
816         // have satisfied all their match pairs.
817         let fully_matched = candidates
818             .iter()
819             .take_while(|c| c.match_pairs.is_empty())
820             .count();
821         debug!(
822             "match_candidates: {:?} candidates fully matched",
823             fully_matched
824         );
825         let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
826
827         if !matched_candidates.is_empty() {
828             block = if let Some(last_otherwise_block) = self.select_matched_candidates(
829                 matched_candidates,
830                 block,
831                 fake_borrows,
832             ) {
833                 last_otherwise_block
834             } else {
835                 // Any remaining candidates are unreachable.
836                 if unmatched_candidates.is_empty() {
837                     return Vec::new();
838                 } else {
839                     self.cfg.start_new_block()
840                 }
841             };
842         }
843
844         // If there are no candidates that still need testing, we're
845         // done. Since all matches are exhaustive, execution should
846         // never reach this point.
847         if unmatched_candidates.is_empty() {
848             return vec![block];
849         }
850
851         // Test candidates where possible.
852         let (otherwise, untested_candidates) = self.test_candidates(
853             span,
854             unmatched_candidates,
855             block,
856             fake_borrows,
857         );
858
859         // If the target candidates were exhaustive, then we are done.
860         // But for borrowck continue build decision tree.
861         if untested_candidates.is_empty() {
862             return otherwise;
863         }
864
865         // Otherwise, let's process those remaining candidates.
866         let join_block = self.join_otherwise_blocks(span, otherwise);
867         self.match_candidates(
868             span,
869             untested_candidates,
870             join_block,
871             fake_borrows,
872         )
873     }
874
875     /// Link up matched candidates. For example, if we have something like
876     /// this:
877     ///
878     /// ...
879     /// Some(x) if cond => ...
880     /// Some(x) => ...
881     /// Some(x) if cond => ...
882     /// ...
883     ///
884     /// We generate real edges from:
885     /// * `block` to the prebinding_block of the first pattern,
886     /// * the otherwise block of the first pattern to the second pattern,
887     /// * the otherwise block of the third pattern to the a block with an
888     ///   Unreachable terminator.
889     ///
890     /// As well as that we add fake edges from the otherwise blocks to the
891     /// prebinding block of the next candidate in the original set of
892     /// candidates.
893     fn select_matched_candidates(
894         &mut self,
895         matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
896         block: BasicBlock,
897         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
898     ) -> Option<BasicBlock> {
899         debug_assert!(
900             !matched_candidates.is_empty(),
901             "select_matched_candidates called with no candidates",
902         );
903
904         // Insert a borrows of prefixes of places that are bound and are
905         // behind a dereference projection.
906         //
907         // These borrows are taken to avoid situations like the following:
908         //
909         // match x[10] {
910         //     _ if { x = &[0]; false } => (),
911         //     y => (), // Out of bounds array access!
912         // }
913         //
914         // match *x {
915         //     // y is bound by reference in the guard and then by copy in the
916         //     // arm, so y is 2 in the arm!
917         //     y if { y == 1 && (x = &2) == () } => y,
918         //     _ => 3,
919         // }
920         if let Some(fake_borrows) = fake_borrows {
921             for Binding { source, .. }
922                 in matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
923             {
924                 let mut cursor = source;
925                 while let Place::Projection(box Projection { base, elem }) = cursor {
926                     cursor = base;
927                     if let ProjectionElem::Deref = elem {
928                         fake_borrows.insert(cursor.clone());
929                         break;
930                     }
931                 }
932             }
933         }
934
935         let fully_matched_with_guard = matched_candidates
936             .iter()
937             .position(|c| c.otherwise_block.is_none())
938             .unwrap_or(matched_candidates.len() - 1);
939
940         let (reachable_candidates, unreachable_candidates)
941             = matched_candidates.split_at_mut(fully_matched_with_guard + 1);
942
943         let first_candidate = &reachable_candidates[0];
944
945         let candidate_source_info = self.source_info(first_candidate.span);
946
947         self.cfg.terminate(
948             block,
949             candidate_source_info,
950             TerminatorKind::Goto {
951                 target: first_candidate.pre_binding_block,
952             },
953         );
954
955         for window in reachable_candidates.windows(2) {
956             if let [first_candidate, second_candidate] = window {
957                 let source_info = self.source_info(first_candidate.span);
958                 if let Some(otherwise_block) = first_candidate.otherwise_block {
959                     self.cfg.terminate(
960                         otherwise_block,
961                         source_info,
962                         TerminatorKind::FalseEdges {
963                             real_target: second_candidate.pre_binding_block,
964                             imaginary_targets: vec![
965                                 first_candidate.next_candidate_pre_binding_block
966                             ],
967                         }
968                     )
969                 } else {
970                     bug!("candidate other than the last has no guard");
971                 }
972             } else {
973                 bug!("<[_]>::windows returned incorrectly sized window");
974             }
975         }
976
977         debug!("match_candidates: add false edges for unreachable {:?}", unreachable_candidates);
978         for candidate in unreachable_candidates {
979             if let Some(otherwise) = candidate.otherwise_block {
980                 let source_info = self.source_info(candidate.span);
981                 let unreachable = self.cfg.start_new_block();
982                 self.cfg.terminate(
983                     otherwise,
984                     source_info,
985                     TerminatorKind::FalseEdges {
986                         real_target: unreachable,
987                         imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
988                     }
989                 );
990                 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
991             }
992         }
993
994         let last_candidate = reachable_candidates.last().unwrap();
995
996         if let Some(otherwise) = last_candidate.otherwise_block {
997             let source_info = self.source_info(last_candidate.span);
998             let block = self.cfg.start_new_block();
999             self.cfg.terminate(
1000                 otherwise,
1001                 source_info,
1002                 TerminatorKind::FalseEdges {
1003                     real_target: block,
1004                     imaginary_targets: vec![last_candidate.next_candidate_pre_binding_block]
1005                 }
1006             );
1007             Some(block)
1008         } else {
1009             None
1010         }
1011     }
1012
1013     fn join_otherwise_blocks(&mut self, span: Span, mut otherwise: Vec<BasicBlock>) -> BasicBlock {
1014         let source_info = self.source_info(span);
1015         otherwise.sort();
1016         otherwise.dedup(); // variant switches can introduce duplicate target blocks
1017         if otherwise.len() == 1 {
1018             otherwise[0]
1019         } else {
1020             let join_block = self.cfg.start_new_block();
1021             for block in otherwise {
1022                 self.cfg.terminate(
1023                     block,
1024                     source_info,
1025                     TerminatorKind::Goto { target: join_block },
1026                 );
1027             }
1028             join_block
1029         }
1030     }
1031
1032     /// This is the most subtle part of the matching algorithm. At
1033     /// this point, the input candidates have been fully simplified,
1034     /// and so we know that all remaining match-pairs require some
1035     /// sort of test. To decide what test to do, we take the highest
1036     /// priority candidate (last one in the list) and extract the
1037     /// first match-pair from the list. From this we decide what kind
1038     /// of test is needed using `test`, defined in the `test` module.
1039     ///
1040     /// *Note:* taking the first match pair is somewhat arbitrary, and
1041     /// we might do better here by choosing more carefully what to
1042     /// test.
1043     ///
1044     /// For example, consider the following possible match-pairs:
1045     ///
1046     /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
1047     /// 2. `x @ 22` -- we will do a `SwitchInt`
1048     /// 3. `x @ 3..5` -- we will do a range test
1049     /// 4. etc.
1050     ///
1051     /// Once we know what sort of test we are going to perform, this
1052     /// Tests may also help us with other candidates. So we walk over
1053     /// the candidates (from high to low priority) and check. This
1054     /// gives us, for each outcome of the test, a transformed list of
1055     /// candidates. For example, if we are testing the current
1056     /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
1057     /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
1058     /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
1059     /// simpler (and, in fact, irrefutable).
1060     ///
1061     /// But there may also be candidates that the test just doesn't
1062     /// apply to. The classical example involves wildcards:
1063     ///
1064     /// ```
1065     /// # let (x, y, z) = (true, true, true);
1066     /// match (x, y, z) {
1067     ///     (true, _, true) => true,    // (0)
1068     ///     (_, true, _) => true,       // (1)
1069     ///     (false, false, _) => false, // (2)
1070     ///     (true, _, false) => false,  // (3)
1071     /// }
1072     /// ```
1073     ///
1074     /// In that case, after we test on `x`, there are 2 overlapping candidate
1075     /// sets:
1076     ///
1077     /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1078     /// - If the outcome is that `x` is false, candidates 1 and 2
1079     ///
1080     /// Here, the traditional "decision tree" method would generate 2
1081     /// separate code-paths for the 2 separate cases.
1082     ///
1083     /// In some cases, this duplication can create an exponential amount of
1084     /// code. This is most easily seen by noticing that this method terminates
1085     /// with precisely the reachable arms being reachable - but that problem
1086     /// is trivially NP-complete:
1087     ///
1088     /// ```rust
1089     ///     match (var0, var1, var2, var3, ..) {
1090     ///         (true, _, _, false, true, ...) => false,
1091     ///         (_, true, true, false, _, ...) => false,
1092     ///         (false, _, false, false, _, ...) => false,
1093     ///         ...
1094     ///         _ => true
1095     ///     }
1096     /// ```
1097     ///
1098     /// Here the last arm is reachable only if there is an assignment to
1099     /// the variables that does not match any of the literals. Therefore,
1100     /// compilation would take an exponential amount of time in some cases.
1101     ///
1102     /// That kind of exponential worst-case might not occur in practice, but
1103     /// our simplistic treatment of constants and guards would make it occur
1104     /// in very common situations - for example #29740:
1105     ///
1106     /// ```rust
1107     /// match x {
1108     ///     "foo" if foo_guard => ...,
1109     ///     "bar" if bar_guard => ...,
1110     ///     "baz" if baz_guard => ...,
1111     ///     ...
1112     /// }
1113     /// ```
1114     ///
1115     /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1116     ///
1117     /// It might seem that we would end up with 2 disjoint candidate
1118     /// sets, consisting of the first candidate or the other 3, but our
1119     /// algorithm doesn't reason about "foo" being distinct from the other
1120     /// constants; it considers the latter arms to potentially match after
1121     /// both outcomes, which obviously leads to an exponential amount
1122     /// of tests.
1123     ///
1124     /// To avoid these kinds of problems, our algorithm tries to ensure
1125     /// the amount of generated tests is linear. When we do a k-way test,
1126     /// we return an additional "unmatched" set alongside the obvious `k`
1127     /// sets. When we encounter a candidate that would be present in more
1128     /// than one of the sets, we put it and all candidates below it into the
1129     /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1130     ///
1131     /// After we perform our test, we branch into the appropriate candidate
1132     /// set and recurse with `match_candidates`. These sub-matches are
1133     /// obviously inexhaustive - as we discarded our otherwise set - so
1134     /// we set their continuation to do `match_candidates` on the
1135     /// "unmatched" set (which is again inexhaustive).
1136     ///
1137     /// If you apply this to the above test, you basically wind up
1138     /// with an if-else-if chain, testing each candidate in turn,
1139     /// which is precisely what we want.
1140     ///
1141     /// In addition to avoiding exponential-time blowups, this algorithm
1142     /// also has nice property that each guard and arm is only generated
1143     /// once.
1144     fn test_candidates<'pat, 'b, 'c>(
1145         &mut self,
1146         span: Span,
1147         mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1148         block: BasicBlock,
1149         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1150     ) -> (Vec<BasicBlock>, &'b mut [&'c mut Candidate<'pat, 'tcx>]) {
1151         // extract the match-pair from the highest priority candidate
1152         let match_pair = &candidates.first().unwrap().match_pairs[0];
1153         let mut test = self.test(match_pair);
1154         let match_place = match_pair.place.clone();
1155
1156         // most of the time, the test to perform is simply a function
1157         // of the main candidate; but for a test like SwitchInt, we
1158         // may want to add cases based on the candidates that are
1159         // available
1160         match test.kind {
1161             TestKind::SwitchInt {
1162                 switch_ty,
1163                 ref mut options,
1164                 ref mut indices,
1165             } => {
1166                 for candidate in candidates.iter() {
1167                     if !self.add_cases_to_switch(
1168                         &match_place,
1169                         candidate,
1170                         switch_ty,
1171                         options,
1172                         indices,
1173                     ) {
1174                         break;
1175                     }
1176                 }
1177             }
1178             TestKind::Switch {
1179                 adt_def: _,
1180                 ref mut variants,
1181             } => {
1182                 for candidate in candidates.iter() {
1183                     if !self.add_variants_to_switch(&match_place, candidate, variants) {
1184                         break;
1185                     }
1186                 }
1187             }
1188             _ => {}
1189         }
1190
1191         // Insert a Shallow borrow of any places that is switched on.
1192         fake_borrows.as_mut().map(|fb| {
1193             fb.insert(match_place.clone())
1194         });
1195
1196         // perform the test, branching to one of N blocks. For each of
1197         // those N possible outcomes, create a (initially empty)
1198         // vector of candidates. Those are the candidates that still
1199         // apply if the test has that particular outcome.
1200         debug!(
1201             "match_candidates: test={:?} match_pair={:?}",
1202             test, match_pair
1203         );
1204         let target_blocks = self.perform_test(block, &match_place, &test);
1205         let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1206         target_candidates.resize_with(target_blocks.len(), Default::default);
1207
1208         let total_candidate_count = candidates.len();
1209
1210         // Sort the candidates into the appropriate vector in
1211         // `target_candidates`. Note that at some point we may
1212         // encounter a candidate where the test is not relevant; at
1213         // that point, we stop sorting.
1214         while let Some(candidate) = candidates.first_mut() {
1215             if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1216                 let (candidate, rest) = candidates.split_first_mut().unwrap();
1217                 target_candidates[idx].push(candidate);
1218                 candidates = rest;
1219             } else {
1220                 break;
1221             }
1222         }
1223         // at least the first candidate ought to be tested
1224         assert!(total_candidate_count > candidates.len());
1225         debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1226         debug!("untested_candidates: {}", candidates.len());
1227
1228         // For each outcome of test, process the candidates that still
1229         // apply. Collect a list of blocks where control flow will
1230         // branch if one of the `target_candidate` sets is not
1231         // exhaustive.
1232         let otherwise: Vec<_> = target_blocks
1233             .into_iter()
1234             .zip(target_candidates)
1235             .flat_map(|(target_block, mut target_candidates)| {
1236                 self.match_candidates(
1237                     span,
1238                     &mut *target_candidates,
1239                     target_block,
1240                     fake_borrows,
1241                 )
1242             })
1243             .collect();
1244
1245         (otherwise, candidates)
1246     }
1247
1248     // Determine the fake borrows that are needed to ensure that the place
1249     // will evaluate to the same thing until an arm has been chosen.
1250     fn calculate_fake_borrows<'b>(
1251         &mut self,
1252         fake_borrows: &'b FxHashSet<Place<'tcx>>,
1253         temp_span: Span,
1254     ) -> Vec<(&'b Place<'tcx>, Local)> {
1255         let tcx = self.hir.tcx();
1256
1257         debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1258
1259         let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1260
1261         // Insert a Shallow borrow of the prefixes of any fake borrows.
1262         for place in fake_borrows
1263         {
1264             let mut prefix_cursor = place;
1265             while let Place::Projection(box Projection { base, elem }) = prefix_cursor {
1266                 if let ProjectionElem::Deref = elem {
1267                     // Insert a shallow borrow after a deref. For other
1268                     // projections the borrow of prefix_cursor will
1269                     // conflict with any mutation of base.
1270                     all_fake_borrows.push(base);
1271                 }
1272                 prefix_cursor = base;
1273             }
1274
1275             all_fake_borrows.push(place);
1276         }
1277
1278         // Deduplicate and ensure a deterministic order.
1279         all_fake_borrows.sort();
1280         all_fake_borrows.dedup();
1281
1282         debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1283
1284         all_fake_borrows.into_iter().map(|matched_place| {
1285             let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1286             let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1287             let fake_borrow_temp = self.local_decls.push(
1288                 LocalDecl::new_temp(fake_borrow_ty, temp_span)
1289             );
1290
1291             (matched_place, fake_borrow_temp)
1292         }).collect()
1293     }
1294 }
1295
1296 ///////////////////////////////////////////////////////////////////////////
1297 // Pattern binding - used for `let` and function parameters as well.
1298
1299 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
1300     /// Initializes each of the bindings from the candidate by
1301     /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1302     /// any, and then branches to the arm. Returns the block for the case where
1303     /// the guard fails.
1304     ///
1305     /// Note: we check earlier that if there is a guard, there cannot be move
1306     /// bindings (unless feature(bind_by_move_pattern_guards) is used). This
1307     /// isn't really important for the self-consistency of this fn, but the
1308     /// reason for it should be clear: after we've done the assignments, if
1309     /// there were move bindings, further tests would be a use-after-move.
1310     /// bind_by_move_pattern_guards avoids this by only moving the binding once
1311     /// the guard has evaluated to true (see below).
1312     fn bind_and_guard_matched_candidate<'pat>(
1313         &mut self,
1314         candidate: Candidate<'pat, 'tcx>,
1315         guard: Option<Guard<'tcx>>,
1316         arm_block: BasicBlock,
1317         fake_borrows: &Vec<(&Place<'tcx>, Local)>,
1318         scrutinee_span: Span,
1319         region_scope: (region::Scope, SourceInfo),
1320     ) {
1321         debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1322
1323         debug_assert!(candidate.match_pairs.is_empty());
1324
1325         let candidate_source_info = self.source_info(candidate.span);
1326
1327         let mut block = self.cfg.start_new_block();
1328         self.cfg.terminate(
1329             candidate.pre_binding_block,
1330             candidate_source_info,
1331             TerminatorKind::FalseEdges {
1332                 real_target: block,
1333                 imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1334             },
1335         );
1336         self.ascribe_types(block, &candidate.ascriptions);
1337
1338         // rust-lang/rust#27282: The `autoref` business deserves some
1339         // explanation here.
1340         //
1341         // The intent of the `autoref` flag is that when it is true,
1342         // then any pattern bindings of type T will map to a `&T`
1343         // within the context of the guard expression, but will
1344         // continue to map to a `T` in the context of the arm body. To
1345         // avoid surfacing this distinction in the user source code
1346         // (which would be a severe change to the language and require
1347         // far more revision to the compiler), when `autoref` is true,
1348         // then any occurrence of the identifier in the guard
1349         // expression will automatically get a deref op applied to it.
1350         //
1351         // So an input like:
1352         //
1353         // ```
1354         // let place = Foo::new();
1355         // match place { foo if inspect(foo)
1356         //     => feed(foo), ...  }
1357         // ```
1358         //
1359         // will be treated as if it were really something like:
1360         //
1361         // ```
1362         // let place = Foo::new();
1363         // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1364         //     => { let tmp2 = place; feed(tmp2) }, ... }
1365         //
1366         // And an input like:
1367         //
1368         // ```
1369         // let place = Foo::new();
1370         // match place { ref mut foo if inspect(foo)
1371         //     => feed(foo), ...  }
1372         // ```
1373         //
1374         // will be treated as if it were really something like:
1375         //
1376         // ```
1377         // let place = Foo::new();
1378         // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1379         //     => { let tmp2 = &mut place; feed(tmp2) }, ... }
1380         // ```
1381         //
1382         // In short, any pattern binding will always look like *some*
1383         // kind of `&T` within the guard at least in terms of how the
1384         // MIR-borrowck views it, and this will ensure that guard
1385         // expressions cannot mutate their the match inputs via such
1386         // bindings. (It also ensures that guard expressions can at
1387         // most *copy* values from such bindings; non-Copy things
1388         // cannot be moved via pattern bindings in guard expressions.)
1389         //
1390         // ----
1391         //
1392         // Implementation notes (under assumption `autoref` is true).
1393         //
1394         // To encode the distinction above, we must inject the
1395         // temporaries `tmp1` and `tmp2`.
1396         //
1397         // There are two cases of interest: binding by-value, and binding by-ref.
1398         //
1399         // 1. Binding by-value: Things are simple.
1400         //
1401         //    * Establishing `tmp1` creates a reference into the
1402         //      matched place. This code is emitted by
1403         //      bind_matched_candidate_for_guard.
1404         //
1405         //    * `tmp2` is only initialized "lazily", after we have
1406         //      checked the guard. Thus, the code that can trigger
1407         //      moves out of the candidate can only fire after the
1408         //      guard evaluated to true. This initialization code is
1409         //      emitted by bind_matched_candidate_for_arm.
1410         //
1411         // 2. Binding by-reference: Things are tricky.
1412         //
1413         //    * Here, the guard expression wants a `&&` or `&&mut`
1414         //      into the original input. This means we need to borrow
1415         //      the reference that we create for the arm.
1416         //    * So we eagerly create the reference for the arm and then take a
1417         //      reference to that.
1418         if let Some(guard) = guard {
1419             let tcx = self.hir.tcx();
1420
1421             self.bind_matched_candidate_for_guard(
1422                 block,
1423                 &candidate.bindings,
1424             );
1425             let guard_frame = GuardFrame {
1426                 locals: candidate
1427                     .bindings
1428                     .iter()
1429                     .map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode))
1430                     .collect(),
1431             };
1432             debug!("Entering guard building context: {:?}", guard_frame);
1433             self.guard_context.push(guard_frame);
1434
1435             let re_erased = tcx.lifetimes.re_erased;
1436             let scrutinee_source_info = self.source_info(scrutinee_span);
1437             for &(place, temp) in fake_borrows {
1438                 let borrow = Rvalue::Ref(
1439                     re_erased,
1440                     BorrowKind::Shallow,
1441                     place.clone(),
1442                 );
1443                 self.cfg.push_assign(
1444                     block,
1445                     scrutinee_source_info,
1446                     &Place::Base(PlaceBase::Local(temp)),
1447                     borrow,
1448                 );
1449             }
1450
1451             // the block to branch to if the guard fails; if there is no
1452             // guard, this block is simply unreachable
1453             let guard = match guard {
1454                 Guard::If(e) => self.hir.mirror(e),
1455             };
1456             let source_info = self.source_info(guard.span);
1457             let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1458             let cond = unpack!(block = self.as_local_operand(block, guard));
1459             let guard_frame = self.guard_context.pop().unwrap();
1460             debug!(
1461                 "Exiting guard building context with locals: {:?}",
1462                 guard_frame
1463             );
1464
1465             for &(_, temp) in fake_borrows {
1466                 self.cfg.push(block, Statement {
1467                     source_info: guard_end,
1468                     kind: StatementKind::FakeRead(
1469                         FakeReadCause::ForMatchGuard,
1470                         Place::Base(PlaceBase::Local(temp)),
1471                     ),
1472                 });
1473             }
1474
1475             // We want to ensure that the matched candidates are bound
1476             // after we have confirmed this candidate *and* any
1477             // associated guard; Binding them on `block` is too soon,
1478             // because that would be before we've checked the result
1479             // from the guard.
1480             //
1481             // But binding them on `arm_block` is *too late*, because
1482             // then all of the candidates for a single arm would be
1483             // bound in the same place, that would cause a case like:
1484             //
1485             // ```rust
1486             // match (30, 2) {
1487             //     (mut x, 1) | (2, mut x) if { true } => { ... }
1488             //     ...                                 // ^^^^^^^ (this is `arm_block`)
1489             // }
1490             // ```
1491             //
1492             // would yield a `arm_block` something like:
1493             //
1494             // ```
1495             // StorageLive(_4);        // _4 is `x`
1496             // _4 = &mut (_1.0: i32);  // this is handling `(mut x, 1)` case
1497             // _4 = &mut (_1.1: i32);  // this is handling `(2, mut x)` case
1498             // ```
1499             //
1500             // and that is clearly not correct.
1501             let post_guard_block = self.cfg.start_new_block();
1502             let otherwise_post_guard_block = self.cfg.start_new_block();
1503             self.cfg.terminate(
1504                 block,
1505                 source_info,
1506                 TerminatorKind::if_(
1507                     self.hir.tcx(),
1508                     cond.clone(),
1509                     post_guard_block,
1510                     otherwise_post_guard_block,
1511                 ),
1512             );
1513
1514             self.exit_scope(
1515                 source_info.span,
1516                 region_scope,
1517                 otherwise_post_guard_block,
1518                 candidate.otherwise_block.unwrap(),
1519             );
1520
1521             if let Operand::Copy(cond_place) | Operand::Move(cond_place) = cond {
1522                 if let Place::Base(PlaceBase::Local(cond_temp)) = cond_place {
1523                     // We will call `clear_top_scope` if there's another guard. So
1524                     // we have to drop this variable now or it will be "storage
1525                     // leaked".
1526                     self.pop_variable(
1527                         post_guard_block,
1528                         region_scope.0,
1529                         cond_temp
1530                     );
1531                 } else {
1532                     bug!("Expected as_local_operand to produce a temporary");
1533                 }
1534             }
1535
1536             let by_value_bindings = candidate.bindings.iter().filter(|binding| {
1537                 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1538             });
1539             // Read all of the by reference bindings to ensure that the
1540             // place they refer to can't be modified by the guard.
1541             for binding in by_value_bindings.clone() {
1542                 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1543                     let place = Place::Base(PlaceBase::Local(local_id));
1544                 self.cfg.push(
1545                     block,
1546                     Statement {
1547                         source_info: guard_end,
1548                         kind: StatementKind::FakeRead(FakeReadCause::ForGuardBinding, place),
1549                     },
1550                 );
1551             }
1552             self.bind_matched_candidate_for_arm_body(
1553                 post_guard_block,
1554                 by_value_bindings,
1555             );
1556
1557             self.cfg.terminate(
1558                 post_guard_block,
1559                 source_info,
1560                 TerminatorKind::Goto { target: arm_block },
1561             );
1562         } else {
1563             assert!(candidate.otherwise_block.is_none());
1564             // (Here, it is not too early to bind the matched
1565             // candidate on `block`, because there is no guard result
1566             // that we have to inspect before we bind them.)
1567             self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1568             self.cfg.terminate(
1569                 block,
1570                 candidate_source_info,
1571                 TerminatorKind::Goto { target: arm_block },
1572             );
1573         }
1574     }
1575
1576     /// Append `AscribeUserType` statements onto the end of `block`
1577     /// for each ascription
1578     fn ascribe_types(&mut self, block: BasicBlock, ascriptions: &[Ascription<'tcx>]) {
1579         for ascription in ascriptions {
1580             let source_info = self.source_info(ascription.span);
1581
1582             debug!(
1583                 "adding user ascription at span {:?} of place {:?} and {:?}",
1584                 source_info.span,
1585                 ascription.source,
1586                 ascription.user_ty,
1587             );
1588
1589             let user_ty = box ascription.user_ty.clone().user_ty(
1590                 &mut self.canonical_user_type_annotations,
1591                 ascription.source.ty(&self.local_decls, self.hir.tcx()).ty,
1592                 source_info.span
1593             );
1594             self.cfg.push(
1595                 block,
1596                 Statement {
1597                     source_info,
1598                     kind: StatementKind::AscribeUserType(
1599                         ascription.source.clone(),
1600                         ascription.variance,
1601                         user_ty,
1602                     ),
1603                 },
1604             );
1605         }
1606     }
1607
1608     fn bind_matched_candidate_for_guard(
1609         &mut self,
1610         block: BasicBlock,
1611         bindings: &[Binding<'tcx>],
1612     ) {
1613         debug!("bind_matched_candidate_for_guard(block={:?}, bindings={:?})", block, bindings);
1614
1615         // Assign each of the bindings. Since we are binding for a
1616         // guard expression, this will never trigger moves out of the
1617         // candidate.
1618         let re_erased = self.hir.tcx().lifetimes.re_erased;
1619         for binding in bindings {
1620             let source_info = self.source_info(binding.span);
1621
1622             // For each pattern ident P of type T, `ref_for_guard` is
1623             // a reference R: &T pointing to the location matched by
1624             // the pattern, and every occurrence of P within a guard
1625             // denotes *R.
1626             let ref_for_guard =
1627                 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1628             // Question: Why schedule drops if bindings are all
1629             // shared-&'s?
1630             // Answer: Because schedule_drop_for_binding also emits
1631             // StorageDead's for those locals.
1632             self.schedule_drop_for_binding(binding.var_id, binding.span, RefWithinGuard);
1633             match binding.binding_mode {
1634                 BindingMode::ByValue => {
1635                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source.clone());
1636                     self.cfg
1637                         .push_assign(block, source_info, &ref_for_guard, rvalue);
1638                 }
1639                 BindingMode::ByRef(borrow_kind) => {
1640                     let value_for_arm = self.storage_live_binding(
1641                         block,
1642                         binding.var_id,
1643                         binding.span,
1644                         OutsideGuard,
1645                     );
1646                     self.schedule_drop_for_binding(
1647                         binding.var_id,
1648                         binding.span,
1649                         OutsideGuard,
1650                     );
1651
1652                     let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source.clone());
1653                     self.cfg
1654                         .push_assign(block, source_info, &value_for_arm, rvalue);
1655                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1656                     self.cfg
1657                         .push_assign(block, source_info, &ref_for_guard, rvalue);
1658                 }
1659             }
1660         }
1661     }
1662
1663     fn bind_matched_candidate_for_arm_body<'b>(
1664         &mut self,
1665         block: BasicBlock,
1666         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1667     ) where 'tcx: 'b {
1668         debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1669
1670         let re_erased = self.hir.tcx().lifetimes.re_erased;
1671         // Assign each of the bindings. This may trigger moves out of the candidate.
1672         for binding in bindings {
1673             let source_info = self.source_info(binding.span);
1674             let local =
1675                 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1676             self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1677             let rvalue = match binding.binding_mode {
1678                 BindingMode::ByValue => {
1679                     Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1680                 }
1681                 BindingMode::ByRef(borrow_kind) => {
1682                     Rvalue::Ref(re_erased, borrow_kind, binding.source.clone())
1683                 }
1684             };
1685             self.cfg.push_assign(block, source_info, &local, rvalue);
1686         }
1687     }
1688
1689     /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1690     /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1691     /// first local is a binding for occurrences of `var` in the guard, which
1692     /// will have type `&T`. The second local is a binding for occurrences of
1693     /// `var` in the arm body, which will have type `T`.
1694     fn declare_binding(
1695         &mut self,
1696         source_info: SourceInfo,
1697         visibility_scope: SourceScope,
1698         mutability: Mutability,
1699         name: Name,
1700         mode: BindingMode,
1701         var_id: HirId,
1702         var_ty: Ty<'tcx>,
1703         user_ty: UserTypeProjections,
1704         has_guard: ArmHasGuard,
1705         opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1706         pat_span: Span,
1707     ) {
1708         debug!(
1709             "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1710              visibility_scope={:?}, source_info={:?})",
1711             var_id, name, mode, var_ty, visibility_scope, source_info
1712         );
1713
1714         let tcx = self.hir.tcx();
1715         let binding_mode = match mode {
1716             BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1717             BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1718         };
1719         debug!("declare_binding: user_ty={:?}", user_ty);
1720         let local = LocalDecl::<'tcx> {
1721             mutability,
1722             ty: var_ty,
1723             user_ty,
1724             name: Some(name),
1725             source_info,
1726             visibility_scope,
1727             internal: false,
1728             is_block_tail: None,
1729             is_user_variable: Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1730                 binding_mode,
1731                 // hypothetically, `visit_bindings` could try to unzip
1732                 // an outermost hir::Ty as we descend, matching up
1733                 // idents in pat; but complex w/ unclear UI payoff.
1734                 // Instead, just abandon providing diagnostic info.
1735                 opt_ty_info: None,
1736                 opt_match_place,
1737                 pat_span,
1738             }))),
1739         };
1740         let for_arm_body = self.local_decls.push(local.clone());
1741         let locals = if has_guard.0 {
1742             let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1743                 // This variable isn't mutated but has a name, so has to be
1744                 // immutable to avoid the unused mut lint.
1745                 mutability: Mutability::Not,
1746                 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
1747                 user_ty: UserTypeProjections::none(),
1748                 name: Some(name),
1749                 source_info,
1750                 visibility_scope,
1751                 internal: false,
1752                 is_block_tail: None,
1753                 is_user_variable: Some(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1754             });
1755             LocalsForNode::ForGuard {
1756                 ref_for_guard,
1757                 for_arm_body,
1758             }
1759         } else {
1760             LocalsForNode::One(for_arm_body)
1761         };
1762         debug!("declare_binding: vars={:?}", locals);
1763         self.var_indices.insert(var_id, locals);
1764     }
1765 }