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