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