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