]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/matches/mod.rs
51d5c96083d8f61b6b15b28b9a5278cae7242372
[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::{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;
14 use rustc::mir::*;
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;
20 use syntax_pos::Span;
21
22 // helper functions, broken out by category:
23 mod simplify;
24 mod test;
25 mod util;
26
27 use std::convert::TryFrom;
28
29 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
30     /// Generates MIR for a `match` expression.
31     ///
32     /// The MIR that we generate for a match looks like this.
33     ///
34     /// ```text
35     /// [ 0. Pre-match ]
36     ///        |
37     /// [ 1. Evaluate Scrutinee (expression being matched on) ]
38     /// [ (fake read of scrutinee) ]
39     ///        |
40     /// [ 2. Decision tree -- check discriminants ] <--------+
41     ///        |                                             |
42     ///        | (once a specific arm is chosen)             |
43     ///        |                                             |
44     /// [pre_binding_block]                           [otherwise_block]
45     ///        |                                             |
46     /// [ 3. Create "guard bindings" for arm ]               |
47     /// [ (create fake borrows) ]                            |
48     ///        |                                             |
49     /// [ 4. Execute guard code ]                            |
50     /// [ (read fake borrows) ] --(guard is false)-----------+
51     ///        |
52     ///        | (guard results in true)
53     ///        |
54     /// [ 5. Create real bindings and execute arm ]
55     ///        |
56     /// [ Exit match ]
57     /// ```
58     ///
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.
62     ///
63     /// We generate MIR in the following steps:
64     ///
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
71     ///    arms.
72     ///
73     /// ## Fake Reads and borrows
74     ///
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:
80     ///
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.
92     ///
93     /// ## False edges
94     ///
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:
98     ///
99     /// * From each prebinding block to the next prebinding block.
100     /// * From each otherwise block to the next prebinding block.
101     pub fn match_expr(
102         &mut self,
103         destination: &Place<'tcx>,
104         span: Span,
105         mut block: BasicBlock,
106         scrutinee: ExprRef<'tcx>,
107         arms: Vec<Arm<'tcx>>,
108     ) -> BlockAnd<()> {
109         let tcx = self.hir.tcx();
110
111         // Step 1. Evaluate the scrutinee and add the fake read of it.
112
113         let scrutinee_span = scrutinee.span();
114         let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
115
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.
122         //
123         // HACK(eddyb) Work around the above issue by adding a dummy inspection
124         // of `scrutinee_place`, specifically by applying `ReadForMatch`.
125         //
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
130         // check safety.
131
132         let source_info = self.source_info(scrutinee_span);
133         self.cfg.push(block, Statement {
134             source_info,
135             kind: StatementKind::FakeRead(
136                 FakeReadCause::ForMatchedPlace,
137                 scrutinee_place.clone(),
138             ),
139         });
140
141         // Step 2. Create the otherwise and prebinding blocks.
142
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())
147             .collect();
148
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);
152         self.cfg.terminate(
153             *pre_binding_blocks.last().unwrap(),
154             outer_source_info,
155             TerminatorKind::Unreachable,
156         );
157
158         let mut match_has_guard = false;
159
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);
162
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
166             .iter()
167             .map(|arm| {
168                 let arm_has_guard = arm.guard.is_some();
169                 match_has_guard |= arm_has_guard;
170                 let arm_candidates: Vec<_> = arm.patterns
171                     .iter()
172                     .zip(candidate_pre_binding_blocks.by_ref())
173                     .zip(next_candidate_pre_binding_blocks.by_ref())
174                     .map(
175                         |((pattern, pre_binding_block), next_candidate_pre_binding_block)| {
176                             Candidate {
177                                 span: pattern.span,
178                                 match_pairs: vec![
179                                     MatchPair::new(scrutinee_place.clone(), pattern),
180                                 ],
181                                 bindings: vec![],
182                                 ascriptions: vec![],
183                                 otherwise_block: if arm_has_guard {
184                                     Some(self.cfg.start_new_block())
185                                 } else {
186                                     None
187                                 },
188                                 pre_binding_block: *pre_binding_block,
189                                 next_candidate_pre_binding_block:
190                                     *next_candidate_pre_binding_block,
191                             }
192                         },
193                     )
194                     .collect();
195                 (arm, arm_candidates)
196             })
197             .collect();
198
199         // Step 3. Create the decision tree and record the places that we bind or test.
200
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
203         // them.
204         let mut fake_borrows = if match_has_guard && tcx.generate_borrow_of_any_match_input() {
205             Some(FxHashSet::default())
206         } else {
207             None
208         };
209
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
214             .iter_mut()
215             .flat_map(|(_, candidates)| candidates)
216             .collect::<Vec<_>>();
217
218         // this will generate code to test scrutinee_place and
219         // branch to the appropriate arm block
220         let otherwise = self.match_candidates(
221             scrutinee_span,
222             candidates,
223             block,
224             &mut fake_borrows,
225         );
226
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.
231             //
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;
235             otherwise.sort();
236             otherwise.dedup(); // variant switches can introduce duplicate target blocks
237             for block in otherwise {
238                 self.cfg
239                     .terminate(block, outer_source_info, TerminatorKind::Unreachable);
240             }
241         }
242
243         // Step 4. Determine the fake borrows that are needed from the above
244         // places. Create the required temporaries for them.
245
246         let fake_borrow_temps = if let Some(ref borrows) = fake_borrows {
247             self.calculate_fake_borrows(borrows, scrutinee_span)
248         } else {
249             Vec::new()
250         };
251
252         // Step 5. Create everything else: the guards and the arms.
253
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();
257
258             let body = self.hir.mirror(arm.body.clone());
259             let scope = self.declare_bindings(
260                 None,
261                 body.span,
262                 LintLevel::Inherited,
263                 &arm.patterns[0],
264                 ArmHasGuard(arm.guard.is_some()),
265                 Some((Some(&scrutinee_place), scrutinee_span)),
266             );
267
268             for candidate in candidates {
269                 self.bind_and_guard_matched_candidate(
270                     candidate,
271                     arm.guard.clone(),
272                     arm_block,
273                     &fake_borrow_temps,
274                     scrutinee_span,
275                 );
276             }
277
278             if let Some(source_scope) = scope {
279                 self.source_scope = source_scope;
280             }
281
282             unpack!(arm_block = self.into(destination, arm_block, body));
283
284             arm_block
285         }).collect();
286
287         // all the arm blocks will rejoin here
288         let end_block = self.cfg.start_new_block();
289
290         for arm_block in arm_end_blocks {
291             self.cfg.terminate(
292                 arm_block,
293                 outer_source_info,
294                 TerminatorKind::Goto { target: end_block },
295             );
296         }
297
298         self.source_scope = outer_source_info.scope;
299
300         end_block.unit()
301     }
302
303     pub(super) fn expr_into_pattern(
304         &mut self,
305         mut block: BasicBlock,
306         irrefutable_pat: Pattern<'tcx>,
307         initializer: ExprRef<'tcx>,
308     ) -> BlockAnd<()> {
309         match *irrefutable_pat.kind {
310             // Optimize the case of `let x = ...` to write directly into `x`
311             PatternKind::Binding {
312                 mode: BindingMode::ByValue,
313                 var,
314                 subpattern: None,
315                 ..
316             } => {
317                 let place =
318                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
319                 unpack!(block = self.into(&place, block, initializer));
320
321
322                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
323                 let source_info = self.source_info(irrefutable_pat.span);
324                 self.cfg.push(
325                     block,
326                     Statement {
327                         source_info,
328                         kind: StatementKind::FakeRead(FakeReadCause::ForLet, place),
329                     },
330                 );
331
332                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
333                 block.unit()
334             }
335
336             // Optimize the case of `let x: T = ...` to write directly
337             // into `x` and then require that `T == typeof(x)`.
338             //
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
343             // broken.
344             PatternKind::AscribeUserType {
345                 subpattern: Pattern {
346                     kind: box PatternKind::Binding {
347                         mode: BindingMode::ByValue,
348                         var,
349                         subpattern: None,
350                         ..
351                     },
352                     ..
353                 },
354                 ascription: hair::pattern::Ascription {
355                     user_ty: pat_ascription_ty,
356                     variance: _,
357                     user_ty_span,
358                 },
359             } => {
360                 let place =
361                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
362                 unpack!(block = self.into(&place, block, initializer));
363
364                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
365                 let pattern_source_info = self.source_info(irrefutable_pat.span);
366                 self.cfg.push(
367                     block,
368                     Statement {
369                         source_info: pattern_source_info,
370                         kind: StatementKind::FakeRead(FakeReadCause::ForLet, place.clone()),
371                     },
372                 );
373
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,
378                     ty_source_info.span,
379                 );
380                 self.cfg.push(
381                     block,
382                     Statement {
383                         source_info: ty_source_info,
384                         kind: StatementKind::AscribeUserType(
385                             place,
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
390                             // example:
391                             //
392                             // ```
393                             // let x: T = <expr>
394                             // ```
395                             //
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
399                             // `<expr>`.
400                             ty::Variance::Invariant,
401                             user_ty,
402                         ),
403                     },
404                 );
405
406                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
407                 block.unit()
408             }
409
410             _ => {
411                 let place = unpack!(block = self.as_place(block, initializer));
412                 self.place_into_pattern(block, irrefutable_pat, &place, true)
413             }
414         }
415     }
416
417     pub fn place_into_pattern(
418         &mut self,
419         block: BasicBlock,
420         irrefutable_pat: Pattern<'tcx>,
421         initializer: &Place<'tcx>,
422         set_match_place: bool,
423     ) -> BlockAnd<()> {
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)],
428             bindings: vec![],
429             ascriptions: vec![],
430
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,
435         };
436
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);
440
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,
449                 &format!(
450                     "match pairs {:?} remaining after simplifying irrefutable pattern",
451                     candidate.match_pairs,
452                 ),
453             );
454         }
455
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
460         if set_match_place {
461             for binding in &candidate.bindings {
462                 let local = self.var_local_id(binding.var_id, OutsideGuard);
463
464                 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
465                     opt_match_place: Some((ref mut match_place, _)),
466                     ..
467                 }))) = self.local_decls[local].is_user_variable
468                 {
469                     *match_place = Some(initializer.clone());
470                 } else {
471                     bug!("Let binding to non-user variable.")
472                 }
473             }
474         }
475
476         self.ascribe_types(block, &candidate.ascriptions);
477
478         // now apply the bindings, which will also declare the variables
479         self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
480
481         block.unit()
482     }
483
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
487     /// drop scope.
488     pub fn declare_bindings(
489         &mut self,
490         mut visibility_scope: Option<SourceScope>,
491         scope_span: Span,
492         lint_level: LintLevel,
493         pattern: &Pattern<'tcx>,
494         has_guard: ArmHasGuard,
495         opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
496     ) -> Option<SourceScope> {
497         assert!(
498             !(visibility_scope.is_some() && lint_level.is_explicit()),
499             "can't have both a visibility and a lint scope at the same time"
500         );
501         let mut scope = self.source_scope;
502         debug!("declare_bindings: pattern={:?}", pattern);
503         self.visit_bindings(
504             &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);
513                     }
514                 visibility_scope = Some(this.new_source_scope(scope_span,
515                                                            LintLevel::Inherited,
516                                                            None));
517                 }
518                 let source_info = SourceInfo { span, scope };
519                 let visibility_scope = visibility_scope.unwrap();
520                 this.declare_binding(
521                     source_info,
522                     visibility_scope,
523                     mutability,
524                     name,
525                     mode,
526                     var,
527                     ty,
528                     user_ty,
529                     has_guard,
530                     opt_match_place.map(|(x, y)| (x.cloned(), y)),
531                     pattern.span,
532                 );
533             },
534         );
535         visibility_scope
536     }
537
538     pub fn storage_live_binding(
539         &mut self,
540         block: BasicBlock,
541         var: HirId,
542         span: Span,
543         for_guard: ForGuard,
544     ) -> Place<'tcx> {
545         let local_id = self.var_local_id(var, for_guard);
546         let source_info = self.source_info(span);
547         self.cfg.push(
548             block,
549             Statement {
550                 source_info,
551                 kind: StatementKind::StorageLive(local_id),
552             },
553         );
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);
558         place
559     }
560
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);
565         self.schedule_drop(
566             span,
567             region_scope,
568             &Place::Base(PlaceBase::Local(local_id)),
569             var_ty,
570             DropKind::Value {
571                 cached_block: CachedBlock::default(),
572             },
573         );
574     }
575
576     pub(super) fn visit_bindings(
577         &mut self,
578         pattern: &Pattern<'tcx>,
579         pattern_user_ty: UserTypeProjections,
580         f: &mut impl FnMut(
581             &mut Self,
582             Mutability,
583             Name,
584             BindingMode,
585             HirId,
586             Span,
587             Ty<'tcx>,
588             UserTypeProjections,
589         ),
590     ) {
591         debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
592         match *pattern.kind {
593             PatternKind::Binding {
594                 mutability,
595                 name,
596                 mode,
597                 var,
598                 ty,
599                 ref subpattern,
600                 ..
601             } => {
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);
605                 }
606             }
607
608             PatternKind::Array {
609                 ref prefix,
610                 ref slice,
611                 ref suffix,
612             }
613             | PatternKind::Slice {
614                 ref prefix,
615                 ref slice,
616                 ref suffix,
617             } => {
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);
622                 }
623                 for subpattern in slice {
624                     self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
625                 }
626                 for subpattern in suffix {
627                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
628                 }
629             }
630
631             PatternKind::Constant { .. } | PatternKind::Range { .. } | PatternKind::Wild => {}
632
633             PatternKind::Deref { ref subpattern } => {
634                 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
635             }
636
637             PatternKind::AscribeUserType {
638                 ref subpattern,
639                 ascription: hair::pattern::Ascription {
640                     ref user_ty,
641                     user_ty_span,
642                     variance: _,
643                 },
644             } => {
645                 // This corresponds to something like
646                 //
647                 // ```
648                 // let A::<'a>(_): A<'static> = ...;
649                 // ```
650                 //
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 {
654                     span: user_ty_span,
655                     user_ty: user_ty.user_ty,
656                     inferred_ty: subpattern.ty,
657                 };
658                 let projection = UserTypeProjection {
659                     base: self.canonical_user_type_annotations.push(annotation),
660                     projs: Vec::new(),
661                 };
662                 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
663                 self.visit_bindings(subpattern, subpattern_user_ty, f)
664             }
665
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);
671                 }
672             }
673
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);
679                 }
680             }
681         }
682     }
683 }
684
685 #[derive(Debug)]
686 pub struct Candidate<'pat, 'tcx: 'pat> {
687     // span of the original pattern that gave rise to this candidate
688     span: Span,
689
690     // all of these must be satisfied...
691     match_pairs: Vec<MatchPair<'pat, 'tcx>>,
692
693     // ...these bindings established...
694     bindings: Vec<Binding<'tcx>>,
695
696     // ...and these types asserted...
697     ascriptions: Vec<Ascription<'tcx>>,
698
699     // ...and the guard must be evaluated, if false branch to Block...
700     otherwise_block: Option<BasicBlock>,
701
702     // ...and the blocks for add false edges between candidates
703     pre_binding_block: BasicBlock,
704     next_candidate_pre_binding_block: BasicBlock,
705 }
706
707 #[derive(Clone, Debug)]
708 struct Binding<'tcx> {
709     span: Span,
710     source: Place<'tcx>,
711     name: Name,
712     var_id: HirId,
713     var_ty: Ty<'tcx>,
714     mutability: Mutability,
715     binding_mode: BindingMode,
716 }
717
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> {
723     span: Span,
724     source: Place<'tcx>,
725     user_ty: PatternTypeProjection<'tcx>,
726     variance: ty::Variance,
727 }
728
729 #[derive(Clone, Debug)]
730 pub struct MatchPair<'pat, 'tcx: 'pat> {
731     // this place...
732     place: Place<'tcx>,
733
734     // ... must match this pattern.
735     pattern: &'pat Pattern<'tcx>,
736 }
737
738 #[derive(Clone, Debug, PartialEq)]
739 enum TestKind<'tcx> {
740     // test the branches of enum
741     Switch {
742         adt_def: &'tcx ty::AdtDef,
743         variants: BitSet<VariantIdx>,
744     },
745
746     // test the branches of enum
747     SwitchInt {
748         switch_ty: Ty<'tcx>,
749         options: Vec<u128>,
750         indices: FxHashMap<ty::Const<'tcx>, usize>,
751     },
752
753     // test for equality
754     Eq {
755         value: ty::Const<'tcx>,
756         ty: Ty<'tcx>,
757     },
758
759     // test whether the value falls within an inclusive or exclusive range
760     Range(PatternRange<'tcx>),
761
762     // test length of the slice is equal to len
763     Len {
764         len: u64,
765         op: BinOp,
766     },
767 }
768
769 #[derive(Debug)]
770 pub struct Test<'tcx> {
771     span: Span,
772     kind: TestKind<'tcx>,
773 }
774
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);
779
780 ///////////////////////////////////////////////////////////////////////////
781 // Main matching algorithm
782
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.
791     ///
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.
797     ///
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.
804     ///
805     /// If `fake_borrows` is Some, then places which need fake borrows
806     /// will be added to it.
807     fn match_candidates<'pat>(
808         &mut self,
809         span: Span,
810         candidates: &mut [&mut Candidate<'pat, 'tcx>],
811         mut block: BasicBlock,
812         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
813     ) -> Vec<BasicBlock> {
814         debug!(
815             "matched_candidate(span={:?}, block={:?}, candidates={:?})",
816             span, block, candidates
817         );
818
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);
824         }
825
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
830             .iter()
831             .take_while(|c| c.match_pairs.is_empty())
832             .count();
833         debug!(
834             "match_candidates: {:?} candidates fully matched",
835             fully_matched
836         );
837         let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
838
839         if !matched_candidates.is_empty() {
840             block = if let Some(last_otherwise_block) = self.select_matched_candidates(
841                 matched_candidates,
842                 block,
843                 fake_borrows,
844             ) {
845                 last_otherwise_block
846             } else {
847                 // Any remaining candidates are unreachable.
848                 if unmatched_candidates.is_empty() {
849                     return Vec::new();
850                 } else {
851                     self.cfg.start_new_block()
852                 }
853             };
854         }
855
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() {
860             return vec![block];
861         }
862
863         // Test candidates where possible.
864         let (otherwise, untested_candidates) = self.test_candidates(
865             span,
866             unmatched_candidates,
867             block,
868             fake_borrows,
869         );
870
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() {
874             return otherwise;
875         }
876
877         // Otherwise, let's process those remaining candidates.
878         let join_block = self.join_otherwise_blocks(span, otherwise);
879         self.match_candidates(
880             span,
881             untested_candidates,
882             join_block,
883             &mut None,
884         )
885     }
886
887     /// Link up matched candidates. For example, if we have something like
888     /// this:
889     ///
890     /// ...
891     /// Some(x) if cond => ...
892     /// Some(x) => ...
893     /// Some(x) if cond => ...
894     /// ...
895     ///
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.
901     ///
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
904     /// candidates.
905     fn select_matched_candidates(
906         &mut self,
907         matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
908         block: BasicBlock,
909         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
910     ) -> Option<BasicBlock> {
911         debug_assert!(
912             !matched_candidates.is_empty(),
913             "select_matched_candidates called with no candidates",
914         );
915
916         // Insert a borrows of prefixes of places that are bound and are
917         // behind a dereference projection.
918         //
919         // These borrows are taken to avoid situations like the following:
920         //
921         // match x[10] {
922         //     _ if { x = &[0]; false } => (),
923         //     y => (), // Out of bounds array access!
924         // }
925         //
926         // match *x {
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,
930         //     _ => 3,
931         // }
932         if let Some(fake_borrows) = fake_borrows {
933             for Binding { source, .. }
934                 in matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
935             {
936                 let mut cursor = source;
937                 while let Place::Projection(box Projection { base, elem }) = cursor {
938                     cursor = base;
939                     if let ProjectionElem::Deref = elem {
940                         fake_borrows.insert(cursor.clone());
941                         break;
942                     }
943                 }
944             }
945         }
946
947         let fully_matched_with_guard = matched_candidates
948             .iter()
949             .position(|c| c.otherwise_block.is_none())
950             .unwrap_or(matched_candidates.len() - 1);
951
952         let (reachable_candidates, unreachable_candidates)
953             = matched_candidates.split_at_mut(fully_matched_with_guard + 1);
954
955         let first_candidate = &reachable_candidates[0];
956
957         let candidate_source_info = self.source_info(first_candidate.span);
958
959         self.cfg.terminate(
960             block,
961             candidate_source_info,
962             TerminatorKind::Goto {
963                 target: first_candidate.pre_binding_block,
964             },
965         );
966
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 {
971                     self.cfg.terminate(
972                         otherwise_block,
973                         source_info,
974                         TerminatorKind::FalseEdges {
975                             real_target: second_candidate.pre_binding_block,
976                             imaginary_targets: vec![
977                                 first_candidate.next_candidate_pre_binding_block
978                             ],
979                         }
980                     )
981                 } else {
982                     bug!("candidate other than the last has no guard");
983                 }
984             } else {
985                 bug!("<[_]>::windows returned incorrectly sized window");
986             }
987         }
988
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();
994                 self.cfg.terminate(
995                     otherwise,
996                     source_info,
997                     TerminatorKind::FalseEdges {
998                         real_target: unreachable,
999                         imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1000                     }
1001                 );
1002                 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
1003             }
1004         }
1005
1006         let last_candidate = reachable_candidates.last().unwrap();
1007
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();
1011             self.cfg.terminate(
1012                 otherwise,
1013                 source_info,
1014                 TerminatorKind::FalseEdges {
1015                     real_target: block,
1016                     imaginary_targets: vec![last_candidate.next_candidate_pre_binding_block]
1017                 }
1018             );
1019             Some(block)
1020         } else {
1021             None
1022         }
1023     }
1024
1025     fn join_otherwise_blocks(&mut self, span: Span, mut otherwise: Vec<BasicBlock>) -> BasicBlock {
1026         let source_info = self.source_info(span);
1027         otherwise.sort();
1028         otherwise.dedup(); // variant switches can introduce duplicate target blocks
1029         if otherwise.len() == 1 {
1030             otherwise[0]
1031         } else {
1032             let join_block = self.cfg.start_new_block();
1033             for block in otherwise {
1034                 self.cfg.terminate(
1035                     block,
1036                     source_info,
1037                     TerminatorKind::Goto { target: join_block },
1038                 );
1039             }
1040             join_block
1041         }
1042     }
1043
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.
1051     ///
1052     /// *Note:* taking the first match pair is somewhat arbitrary, and
1053     /// we might do better here by choosing more carefully what to
1054     /// test.
1055     ///
1056     /// For example, consider the following possible match-pairs:
1057     ///
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
1061     /// 4. etc.
1062     ///
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).
1072     ///
1073     /// But there may also be candidates that the test just doesn't
1074     /// apply to. The classical example involves wildcards:
1075     ///
1076     /// ```
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)
1083     /// }
1084     /// ```
1085     ///
1086     /// In that case, after we test on `x`, there are 2 overlapping candidate
1087     /// sets:
1088     ///
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
1091     ///
1092     /// Here, the traditional "decision tree" method would generate 2
1093     /// separate code-paths for the 2 separate cases.
1094     ///
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:
1099     ///
1100     /// ```rust
1101     ///     match (var0, var1, var2, var3, ..) {
1102     ///         (true, _, _, false, true, ...) => false,
1103     ///         (_, true, true, false, _, ...) => false,
1104     ///         (false, _, false, false, _, ...) => false,
1105     ///         ...
1106     ///         _ => true
1107     ///     }
1108     /// ```
1109     ///
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.
1113     ///
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:
1117     ///
1118     /// ```rust
1119     /// match x {
1120     ///     "foo" if foo_guard => ...,
1121     ///     "bar" if bar_guard => ...,
1122     ///     "baz" if baz_guard => ...,
1123     ///     ...
1124     /// }
1125     /// ```
1126     ///
1127     /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1128     ///
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
1134     /// of tests.
1135     ///
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.
1142     ///
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).
1148     ///
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.
1152     ///
1153     /// In addition to avoiding exponential-time blowups, this algorithm
1154     /// also has nice property that each guard and arm is only generated
1155     /// once.
1156     fn test_candidates<'pat, 'b, 'c>(
1157         &mut self,
1158         span: Span,
1159         mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1160         block: BasicBlock,
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();
1167
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
1171         // available
1172         match test.kind {
1173             TestKind::SwitchInt {
1174                 switch_ty,
1175                 ref mut options,
1176                 ref mut indices,
1177             } => {
1178                 for candidate in candidates.iter() {
1179                     if !self.add_cases_to_switch(
1180                         &match_place,
1181                         candidate,
1182                         switch_ty,
1183                         options,
1184                         indices,
1185                     ) {
1186                         break;
1187                     }
1188                 }
1189             }
1190             TestKind::Switch {
1191                 adt_def: _,
1192                 ref mut variants,
1193             } => {
1194                 for candidate in candidates.iter() {
1195                     if !self.add_variants_to_switch(&match_place, candidate, variants) {
1196                         break;
1197                     }
1198                 }
1199             }
1200             _ => {}
1201         }
1202
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())
1206         });
1207
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.
1212         debug!(
1213             "match_candidates: test={:?} match_pair={:?}",
1214             test, match_pair
1215         );
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);
1219
1220         let total_candidate_count = candidates.len();
1221
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);
1230                 candidates = rest;
1231             } else {
1232                 break;
1233             }
1234         }
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());
1239
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
1243         // exhaustive.
1244         let otherwise: Vec<_> = target_blocks
1245             .into_iter()
1246             .zip(target_candidates)
1247             .flat_map(|(target_block, mut target_candidates)| {
1248                 self.match_candidates(
1249                     span,
1250                     &mut *target_candidates,
1251                     target_block,
1252                     fake_borrows,
1253                 )
1254             })
1255             .collect();
1256
1257         (otherwise, candidates)
1258     }
1259
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>(
1263         &mut self,
1264         fake_borrows: &'b FxHashSet<Place<'tcx>>,
1265         temp_span: Span,
1266     ) -> Vec<(&'b Place<'tcx>, Local)> {
1267         let tcx = self.hir.tcx();
1268
1269         debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1270
1271         let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1272
1273         // Insert a Shallow borrow of the prefixes of any fake borrows.
1274         for place in fake_borrows
1275         {
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);
1283                 }
1284                 prefix_cursor = base;
1285             }
1286
1287             all_fake_borrows.push(place);
1288         }
1289
1290         // Deduplicate and ensure a deterministic order.
1291         all_fake_borrows.sort();
1292         all_fake_borrows.dedup();
1293
1294         debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1295
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)
1301             );
1302
1303             (matched_place, fake_borrow_temp)
1304         }).collect()
1305     }
1306 }
1307
1308 ///////////////////////////////////////////////////////////////////////////
1309 // Pattern binding - used for `let` and function parameters as well.
1310
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.
1316     ///
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>(
1325         &mut self,
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,
1331     ) {
1332         debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1333
1334         debug_assert!(candidate.match_pairs.is_empty());
1335
1336         let candidate_source_info = self.source_info(candidate.span);
1337
1338         let mut block = self.cfg.start_new_block();
1339         self.cfg.terminate(
1340             candidate.pre_binding_block,
1341             candidate_source_info,
1342             TerminatorKind::FalseEdges {
1343                 real_target: block,
1344                 imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1345             },
1346         );
1347         self.ascribe_types(block, &candidate.ascriptions);
1348
1349         // rust-lang/rust#27282: The `autoref` business deserves some
1350         // explanation here.
1351         //
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.
1361         //
1362         // So an input like:
1363         //
1364         // ```
1365         // let place = Foo::new();
1366         // match place { foo if inspect(foo)
1367         //     => feed(foo), ...  }
1368         // ```
1369         //
1370         // will be treated as if it were really something like:
1371         //
1372         // ```
1373         // let place = Foo::new();
1374         // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1375         //     => { let tmp2 = place; feed(tmp2) }, ... }
1376         //
1377         // And an input like:
1378         //
1379         // ```
1380         // let place = Foo::new();
1381         // match place { ref mut foo if inspect(foo)
1382         //     => feed(foo), ...  }
1383         // ```
1384         //
1385         // will be treated as if it were really something like:
1386         //
1387         // ```
1388         // let place = Foo::new();
1389         // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1390         //     => { let tmp2 = &mut place; feed(tmp2) }, ... }
1391         // ```
1392         //
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.)
1400         //
1401         // ----
1402         //
1403         // Implementation notes (under assumption `autoref` is true).
1404         //
1405         // To encode the distinction above, we must inject the
1406         // temporaries `tmp1` and `tmp2`.
1407         //
1408         // There are two cases of interest: binding by-value, and binding by-ref.
1409         //
1410         // 1. Binding by-value: Things are simple.
1411         //
1412         //    * Establishing `tmp1` creates a reference into the
1413         //      matched place. This code is emitted by
1414         //      bind_matched_candidate_for_guard.
1415         //
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.
1421         //
1422         // 2. Binding by-reference: Things are tricky.
1423         //
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();
1431
1432             self.bind_matched_candidate_for_guard(
1433                 block,
1434                 &candidate.bindings,
1435             );
1436             let guard_frame = GuardFrame {
1437                 locals: candidate
1438                     .bindings
1439                     .iter()
1440                     .map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode))
1441                     .collect(),
1442             };
1443             debug!("Entering guard building context: {:?}", guard_frame);
1444             self.guard_context.push(guard_frame);
1445
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(
1450                     re_erased,
1451                     BorrowKind::Shallow,
1452                     place.clone(),
1453                 );
1454                 self.cfg.push_assign(
1455                     block,
1456                     scrutinee_source_info,
1457                     &Place::Base(PlaceBase::Local(temp)),
1458                     borrow,
1459                 );
1460             }
1461
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),
1466             };
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();
1471             debug!(
1472                 "Exiting guard building context with locals: {:?}",
1473                 guard_frame
1474             );
1475
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)),
1482                     ),
1483                 });
1484             }
1485
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
1490             // from the guard.
1491             //
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:
1495             //
1496             // ```rust
1497             // match (30, 2) {
1498             //     (mut x, 1) | (2, mut x) if { true } => { ... }
1499             //     ...                                 // ^^^^^^^ (this is `arm_block`)
1500             // }
1501             // ```
1502             //
1503             // would yield a `arm_block` something like:
1504             //
1505             // ```
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
1509             // ```
1510             //
1511             // and that is clearly not correct.
1512             let post_guard_block = self.cfg.start_new_block();
1513             self.cfg.terminate(
1514                 block,
1515                 source_info,
1516                 TerminatorKind::if_(
1517                     self.hir.tcx(),
1518                     cond,
1519                     post_guard_block,
1520                     candidate.otherwise_block.unwrap()
1521                 ),
1522             );
1523
1524             let by_value_bindings = candidate.bindings.iter().filter(|binding| {
1525                 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1526             });
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));
1532                 self.cfg.push(
1533                     block,
1534                     Statement {
1535                         source_info: guard_end,
1536                         kind: StatementKind::FakeRead(FakeReadCause::ForGuardBinding, place),
1537                     },
1538                 );
1539             }
1540             self.bind_matched_candidate_for_arm_body(
1541                 post_guard_block,
1542                 by_value_bindings,
1543             );
1544
1545             self.cfg.terminate(
1546                 post_guard_block,
1547                 source_info,
1548                 TerminatorKind::Goto { target: arm_block },
1549             );
1550         } else {
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);
1556             self.cfg.terminate(
1557                 block,
1558                 candidate_source_info,
1559                 TerminatorKind::Goto { target: arm_block },
1560             );
1561         }
1562     }
1563
1564     /// Append `AscribeUserType` statements onto the end of `block`
1565     /// for each ascription
1566     fn ascribe_types<'pat>(
1567         &mut self,
1568         block: BasicBlock,
1569         ascriptions: &[Ascription<'tcx>],
1570     ) {
1571         for ascription in ascriptions {
1572             let source_info = self.source_info(ascription.span);
1573
1574             debug!(
1575                 "adding user ascription at span {:?} of place {:?} and {:?}",
1576                 source_info.span,
1577                 ascription.source,
1578                 ascription.user_ty,
1579             );
1580
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,
1584                 source_info.span
1585             );
1586             self.cfg.push(
1587                 block,
1588                 Statement {
1589                     source_info,
1590                     kind: StatementKind::AscribeUserType(
1591                         ascription.source.clone(),
1592                         ascription.variance,
1593                         user_ty,
1594                     ),
1595                 },
1596             );
1597         }
1598     }
1599
1600     fn bind_matched_candidate_for_guard(
1601         &mut self,
1602         block: BasicBlock,
1603         bindings: &[Binding<'tcx>],
1604     ) {
1605         debug!("bind_matched_candidate_for_guard(block={:?}, bindings={:?})", block, bindings);
1606
1607         // Assign each of the bindings. Since we are binding for a
1608         // guard expression, this will never trigger moves out of the
1609         // candidate.
1610         let re_erased = self.hir.tcx().lifetimes.re_erased;
1611         for binding in bindings {
1612             let source_info = self.source_info(binding.span);
1613
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
1617             // denotes *R.
1618             let ref_for_guard =
1619                 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1620             // Question: Why schedule drops if bindings are all
1621             // shared-&'s?
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());
1628                     self.cfg
1629                         .push_assign(block, source_info, &ref_for_guard, rvalue);
1630                 }
1631                 BindingMode::ByRef(borrow_kind) => {
1632                     let value_for_arm = self.storage_live_binding(
1633                         block,
1634                         binding.var_id,
1635                         binding.span,
1636                         OutsideGuard,
1637                     );
1638                     self.schedule_drop_for_binding(
1639                         binding.var_id,
1640                         binding.span,
1641                         OutsideGuard,
1642                     );
1643
1644                     let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source.clone());
1645                     self.cfg
1646                         .push_assign(block, source_info, &value_for_arm, rvalue);
1647                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1648                     self.cfg
1649                         .push_assign(block, source_info, &ref_for_guard, rvalue);
1650                 }
1651             }
1652         }
1653     }
1654
1655     fn bind_matched_candidate_for_arm_body<'b>(
1656         &mut self,
1657         block: BasicBlock,
1658         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1659     ) where 'tcx: 'b {
1660         debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1661
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);
1666             let local =
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()))
1672                 }
1673                 BindingMode::ByRef(borrow_kind) => {
1674                     Rvalue::Ref(re_erased, borrow_kind, binding.source.clone())
1675                 }
1676             };
1677             self.cfg.push_assign(block, source_info, &local, rvalue);
1678         }
1679     }
1680
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`.
1686     fn declare_binding(
1687         &mut self,
1688         source_info: SourceInfo,
1689         visibility_scope: SourceScope,
1690         mutability: Mutability,
1691         name: Name,
1692         mode: BindingMode,
1693         var_id: HirId,
1694         var_ty: Ty<'tcx>,
1695         user_ty: UserTypeProjections,
1696         has_guard: ArmHasGuard,
1697         opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1698         pat_span: Span,
1699     ) {
1700         debug!(
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
1704         );
1705
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()),
1710         };
1711         debug!("declare_binding: user_ty={:?}", user_ty);
1712         let local = LocalDecl::<'tcx> {
1713             mutability,
1714             ty: var_ty,
1715             user_ty,
1716             name: Some(name),
1717             source_info,
1718             visibility_scope,
1719             internal: false,
1720             is_block_tail: None,
1721             is_user_variable: Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1722                 binding_mode,
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.
1727                 opt_ty_info: None,
1728                 opt_match_place,
1729                 pat_span,
1730             }))),
1731         };
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(),
1740                 name: Some(name),
1741                 source_info,
1742                 visibility_scope,
1743                 internal: false,
1744                 is_block_tail: None,
1745                 is_user_variable: Some(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1746             });
1747             LocalsForNode::ForGuard {
1748                 ref_for_guard,
1749                 for_arm_body,
1750             }
1751         } else {
1752             LocalsForNode::One(for_arm_body)
1753         };
1754         debug!("declare_binding: vars={:?}", locals);
1755         self.var_indices.insert(var_id, locals);
1756     }
1757 }