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