]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/matches/test.rs
Auto merge of #50998 - bobtwinkles:nll_facts_invalidate_followup, r=nikomatsakis
[rust.git] / src / librustc_mir / build / matches / test.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Testing candidates
12 //
13 // After candidates have been simplified, the only match pairs that
14 // remain are those that require some sort of test. The functions here
15 // identify what tests are needed, perform the tests, and then filter
16 // the candidates based on the result.
17
18 use build::Builder;
19 use build::matches::{Candidate, MatchPair, Test, TestKind};
20 use hair::*;
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_data_structures::bitvec::BitVector;
23 use rustc::ty::{self, Ty};
24 use rustc::ty::util::IntTypeExt;
25 use rustc::mir::*;
26 use rustc::hir::{RangeEnd, Mutability};
27 use syntax_pos::Span;
28 use std::cmp::Ordering;
29
30 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
31     /// Identifies what test is needed to decide if `match_pair` is applicable.
32     ///
33     /// It is a bug to call this with a simplifyable pattern.
34     pub fn test<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> Test<'tcx> {
35         match *match_pair.pattern.kind {
36             PatternKind::Variant { ref adt_def, substs: _, variant_index: _, subpatterns: _ } => {
37                 Test {
38                     span: match_pair.pattern.span,
39                     kind: TestKind::Switch {
40                         adt_def: adt_def.clone(),
41                         variants: BitVector::new(adt_def.variants.len()),
42                     },
43                 }
44             }
45
46             PatternKind::Constant { .. }
47             if is_switch_ty(match_pair.pattern.ty) => {
48                 // for integers, we use a SwitchInt match, which allows
49                 // us to handle more cases
50                 Test {
51                     span: match_pair.pattern.span,
52                     kind: TestKind::SwitchInt {
53                         switch_ty: match_pair.pattern.ty,
54
55                         // these maps are empty to start; cases are
56                         // added below in add_cases_to_switch
57                         options: vec![],
58                         indices: FxHashMap(),
59                     }
60                 }
61             }
62
63             PatternKind::Constant { value } => {
64                 Test {
65                     span: match_pair.pattern.span,
66                     kind: TestKind::Eq {
67                         value,
68                         ty: match_pair.pattern.ty.clone()
69                     }
70                 }
71             }
72
73             PatternKind::Range { lo, hi, end } => {
74                 Test {
75                     span: match_pair.pattern.span,
76                     kind: TestKind::Range {
77                         lo: Literal::Value { value: lo },
78                         hi: Literal::Value { value: hi },
79                         ty: match_pair.pattern.ty.clone(),
80                         end,
81                     },
82                 }
83             }
84
85             PatternKind::Slice { ref prefix, ref slice, ref suffix }
86                     if !match_pair.slice_len_checked => {
87                 let len = prefix.len() + suffix.len();
88                 let op = if slice.is_some() {
89                     BinOp::Ge
90                 } else {
91                     BinOp::Eq
92                 };
93                 Test {
94                     span: match_pair.pattern.span,
95                     kind: TestKind::Len { len: len as u64, op: op },
96                 }
97             }
98
99             PatternKind::Array { .. } |
100             PatternKind::Slice { .. } |
101             PatternKind::Wild |
102             PatternKind::Binding { .. } |
103             PatternKind::Leaf { .. } |
104             PatternKind::Deref { .. } => {
105                 self.error_simplifyable(match_pair)
106             }
107         }
108     }
109
110     pub fn add_cases_to_switch<'pat>(&mut self,
111                                      test_place: &Place<'tcx>,
112                                      candidate: &Candidate<'pat, 'tcx>,
113                                      switch_ty: Ty<'tcx>,
114                                      options: &mut Vec<u128>,
115                                      indices: &mut FxHashMap<&'tcx ty::Const<'tcx>, usize>)
116                                      -> bool
117     {
118         let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
119             Some(match_pair) => match_pair,
120             _ => { return false; }
121         };
122
123         match *match_pair.pattern.kind {
124             PatternKind::Constant { value } => {
125                 indices.entry(value)
126                        .or_insert_with(|| {
127                            options.push(value.unwrap_bits(switch_ty));
128                            options.len() - 1
129                        });
130                 true
131             }
132             PatternKind::Variant { .. } => {
133                 panic!("you should have called add_variants_to_switch instead!");
134             }
135             PatternKind::Range { .. } |
136             PatternKind::Slice { .. } |
137             PatternKind::Array { .. } |
138             PatternKind::Wild |
139             PatternKind::Binding { .. } |
140             PatternKind::Leaf { .. } |
141             PatternKind::Deref { .. } => {
142                 // don't know how to add these patterns to a switch
143                 false
144             }
145         }
146     }
147
148     pub fn add_variants_to_switch<'pat>(&mut self,
149                                         test_place: &Place<'tcx>,
150                                         candidate: &Candidate<'pat, 'tcx>,
151                                         variants: &mut BitVector)
152                                         -> bool
153     {
154         let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
155             Some(match_pair) => match_pair,
156             _ => { return false; }
157         };
158
159         match *match_pair.pattern.kind {
160             PatternKind::Variant { adt_def: _ , variant_index,  .. } => {
161                 // We have a pattern testing for variant `variant_index`
162                 // set the corresponding index to true
163                 variants.insert(variant_index);
164                 true
165             }
166             _ => {
167                 // don't know how to add these patterns to a switch
168                 false
169             }
170         }
171     }
172
173     /// Generates the code to perform a test.
174     pub fn perform_test(&mut self,
175                         block: BasicBlock,
176                         place: &Place<'tcx>,
177                         test: &Test<'tcx>)
178                         -> Vec<BasicBlock> {
179         debug!("perform_test({:?}, {:?}: {:?}, {:?})",
180                block,
181                place,
182                place.ty(&self.local_decls, self.hir.tcx()),
183                test);
184         let source_info = self.source_info(test.span);
185         match test.kind {
186             TestKind::Switch { adt_def, ref variants } => {
187                 // Variants is a BitVec of indexes into adt_def.variants.
188                 let num_enum_variants = adt_def.variants.len();
189                 let used_variants = variants.count();
190                 let mut otherwise_block = None;
191                 let mut target_blocks = Vec::with_capacity(num_enum_variants);
192                 let mut targets = Vec::with_capacity(used_variants + 1);
193                 let mut values = Vec::with_capacity(used_variants);
194                 let tcx = self.hir.tcx();
195                 for (idx, discr) in adt_def.discriminants(tcx).enumerate() {
196                     target_blocks.push(if variants.contains(idx) {
197                         values.push(discr.val);
198                         targets.push(self.cfg.start_new_block());
199                         *targets.last().unwrap()
200                     } else {
201                         if otherwise_block.is_none() {
202                             otherwise_block = Some(self.cfg.start_new_block());
203                         }
204                         otherwise_block.unwrap()
205                     });
206                 }
207                 if let Some(otherwise_block) = otherwise_block {
208                     targets.push(otherwise_block);
209                 } else {
210                     targets.push(self.unreachable_block());
211                 }
212                 debug!("num_enum_variants: {}, tested variants: {:?}, variants: {:?}",
213                        num_enum_variants, values, variants);
214                 let discr_ty = adt_def.repr.discr_type().to_ty(tcx);
215                 let discr = self.temp(discr_ty, test.span);
216                 self.cfg.push_assign(block, source_info, &discr,
217                                      Rvalue::Discriminant(place.clone()));
218                 assert_eq!(values.len() + 1, targets.len());
219                 self.cfg.terminate(block, source_info, TerminatorKind::SwitchInt {
220                     discr: Operand::Move(discr),
221                     switch_ty: discr_ty,
222                     values: From::from(values),
223                     targets,
224                 });
225                 target_blocks
226             }
227
228             TestKind::SwitchInt { switch_ty, ref options, indices: _ } => {
229                 let (ret, terminator) = if switch_ty.sty == ty::TyBool {
230                     assert!(options.len() > 0 && options.len() <= 2);
231                     let (true_bb, false_bb) = (self.cfg.start_new_block(),
232                                                self.cfg.start_new_block());
233                     let ret = match options[0] {
234                         1 => vec![true_bb, false_bb],
235                         0 => vec![false_bb, true_bb],
236                         v => span_bug!(test.span, "expected boolean value but got {:?}", v)
237                     };
238                     (ret, TerminatorKind::if_(self.hir.tcx(), Operand::Copy(place.clone()),
239                                               true_bb, false_bb))
240                 } else {
241                     // The switch may be inexhaustive so we
242                     // add a catch all block
243                     let otherwise = self.cfg.start_new_block();
244                     let targets: Vec<_> =
245                         options.iter()
246                                .map(|_| self.cfg.start_new_block())
247                                .chain(Some(otherwise))
248                                .collect();
249                     (targets.clone(), TerminatorKind::SwitchInt {
250                         discr: Operand::Copy(place.clone()),
251                         switch_ty,
252                         values: options.clone().into(),
253                         targets,
254                     })
255                 };
256                 self.cfg.terminate(block, source_info, terminator);
257                 ret
258             }
259
260             TestKind::Eq { value, mut ty } => {
261                 let mut val = Operand::Copy(place.clone());
262                 let mut expect = self.literal_operand(test.span, ty, Literal::Value {
263                     value
264                 });
265                 // Use PartialEq::eq instead of BinOp::Eq
266                 // (the binop can only handle primitives)
267                 let fail = self.cfg.start_new_block();
268                 if !ty.is_scalar() {
269                     // If we're using b"..." as a pattern, we need to insert an
270                     // unsizing coercion, as the byte string has the type &[u8; N].
271                     //
272                     // We want to do this even when the scrutinee is a reference to an
273                     // array, so we can call `<[u8]>::eq` rather than having to find an
274                     // `<[u8; N]>::eq`.
275                     let unsize = |ty: Ty<'tcx>| match ty.sty {
276                         ty::TyRef(region, rty, _) => match rty.sty {
277                             ty::TyArray(inner_ty, n) => Some((region, inner_ty, n)),
278                             _ => None,
279                         },
280                         _ => None,
281                     };
282                     let opt_ref_ty = unsize(ty);
283                     let opt_ref_test_ty = unsize(value.ty);
284                     let mut place = place.clone();
285                     match (opt_ref_ty, opt_ref_test_ty) {
286                         // nothing to do, neither is an array
287                         (None, None) => {},
288                         (Some((region, elem_ty, _)), _) |
289                         (None, Some((region, elem_ty, _))) => {
290                             let tcx = self.hir.tcx();
291                             // make both a slice
292                             ty = tcx.mk_imm_ref(region, tcx.mk_slice(elem_ty));
293                             if opt_ref_ty.is_some() {
294                                 place = self.temp(ty, test.span);
295                                 self.cfg.push_assign(block, source_info, &place,
296                                                     Rvalue::Cast(CastKind::Unsize, val, ty));
297                             }
298                             if opt_ref_test_ty.is_some() {
299                                 let array = self.literal_operand(
300                                     test.span,
301                                     value.ty,
302                                     Literal::Value {
303                                         value
304                                     },
305                                 );
306
307                                 let slice = self.temp(ty, test.span);
308                                 self.cfg.push_assign(block, source_info, &slice,
309                                                     Rvalue::Cast(CastKind::Unsize, array, ty));
310                                 expect = Operand::Move(slice);
311                             }
312                         },
313                     }
314                     let eq_def_id = self.hir.tcx().lang_items().eq_trait().unwrap();
315                     let (mty, method) = self.hir.trait_method(eq_def_id, "eq", ty, &[ty.into()]);
316
317                     // take the argument by reference
318                     let region_scope = self.topmost_scope();
319                     let region = self.hir.tcx().mk_region(ty::ReScope(region_scope));
320                     let tam = ty::TypeAndMut {
321                         ty,
322                         mutbl: Mutability::MutImmutable,
323                     };
324                     let ref_ty = self.hir.tcx().mk_ref(region, tam);
325
326                     // let lhs_ref_place = &lhs;
327                     let ref_rvalue = Rvalue::Ref(region, BorrowKind::Shared, place.clone());
328                     let lhs_ref_place = self.temp(ref_ty, test.span);
329                     self.cfg.push_assign(block, source_info, &lhs_ref_place, ref_rvalue);
330                     let val = Operand::Move(lhs_ref_place);
331
332                     // let rhs_place = rhs;
333                     let rhs_place = self.temp(ty, test.span);
334                     self.cfg.push_assign(block, source_info, &rhs_place, Rvalue::Use(expect));
335
336                     // let rhs_ref_place = &rhs_place;
337                     let ref_rvalue = Rvalue::Ref(region, BorrowKind::Shared, rhs_place);
338                     let rhs_ref_place = self.temp(ref_ty, test.span);
339                     self.cfg.push_assign(block, source_info, &rhs_ref_place, ref_rvalue);
340                     let expect = Operand::Move(rhs_ref_place);
341
342                     let bool_ty = self.hir.bool_ty();
343                     let eq_result = self.temp(bool_ty, test.span);
344                     let eq_block = self.cfg.start_new_block();
345                     let cleanup = self.diverge_cleanup();
346                     self.cfg.terminate(block, source_info, TerminatorKind::Call {
347                         func: Operand::Constant(box Constant {
348                             span: test.span,
349                             ty: mty,
350                             literal: method
351                         }),
352                         args: vec![val, expect],
353                         destination: Some((eq_result.clone(), eq_block)),
354                         cleanup: Some(cleanup),
355                     });
356
357                     // check the result
358                     let block = self.cfg.start_new_block();
359                     self.cfg.terminate(eq_block, source_info,
360                                        TerminatorKind::if_(self.hir.tcx(),
361                                                            Operand::Move(eq_result),
362                                                            block, fail));
363                     vec![block, fail]
364                 } else {
365                     let block = self.compare(block, fail, test.span, BinOp::Eq, expect, val);
366                     vec![block, fail]
367                 }
368             }
369
370             TestKind::Range { ref lo, ref hi, ty, ref end } => {
371                 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
372                 let lo = self.literal_operand(test.span, ty.clone(), lo.clone());
373                 let hi = self.literal_operand(test.span, ty.clone(), hi.clone());
374                 let val = Operand::Copy(place.clone());
375
376                 let fail = self.cfg.start_new_block();
377                 let block = self.compare(block, fail, test.span, BinOp::Le, lo, val.clone());
378                 let block = match *end {
379                     RangeEnd::Included => self.compare(block, fail, test.span, BinOp::Le, val, hi),
380                     RangeEnd::Excluded => self.compare(block, fail, test.span, BinOp::Lt, val, hi),
381                 };
382
383                 vec![block, fail]
384             }
385
386             TestKind::Len { len, op } => {
387                 let (usize_ty, bool_ty) = (self.hir.usize_ty(), self.hir.bool_ty());
388                 let (actual, result) = (self.temp(usize_ty, test.span),
389                                         self.temp(bool_ty, test.span));
390
391                 // actual = len(place)
392                 self.cfg.push_assign(block, source_info,
393                                      &actual, Rvalue::Len(place.clone()));
394
395                 // expected = <N>
396                 let expected = self.push_usize(block, source_info, len);
397
398                 // result = actual == expected OR result = actual < expected
399                 self.cfg.push_assign(block, source_info, &result,
400                                      Rvalue::BinaryOp(op,
401                                                       Operand::Move(actual),
402                                                       Operand::Move(expected)));
403
404                 // branch based on result
405                 let (false_bb, true_bb) = (self.cfg.start_new_block(),
406                                            self.cfg.start_new_block());
407                 self.cfg.terminate(block, source_info,
408                                    TerminatorKind::if_(self.hir.tcx(), Operand::Move(result),
409                                                        true_bb, false_bb));
410                 vec![true_bb, false_bb]
411             }
412         }
413     }
414
415     fn compare(&mut self,
416                block: BasicBlock,
417                fail_block: BasicBlock,
418                span: Span,
419                op: BinOp,
420                left: Operand<'tcx>,
421                right: Operand<'tcx>) -> BasicBlock {
422         let bool_ty = self.hir.bool_ty();
423         let result = self.temp(bool_ty, span);
424
425         // result = op(left, right)
426         let source_info = self.source_info(span);
427         self.cfg.push_assign(block, source_info, &result,
428                              Rvalue::BinaryOp(op, left, right));
429
430         // branch based on result
431         let target_block = self.cfg.start_new_block();
432         self.cfg.terminate(block, source_info,
433                            TerminatorKind::if_(self.hir.tcx(), Operand::Move(result),
434                                                target_block, fail_block));
435         target_block
436     }
437
438     /// Given that we are performing `test` against `test_place`,
439     /// this job sorts out what the status of `candidate` will be
440     /// after the test. The `resulting_candidates` vector stores, for
441     /// each possible outcome of `test`, a vector of the candidates
442     /// that will result. This fn should add a (possibly modified)
443     /// clone of candidate into `resulting_candidates` wherever
444     /// appropriate.
445     ///
446     /// So, for example, if this candidate is `x @ Some(P0)` and the
447     /// test is a variant test, then we would add `(x as Option).0 @
448     /// P0` to the `resulting_candidates` entry corresponding to the
449     /// variant `Some`.
450     ///
451     /// However, in some cases, the test may just not be relevant to
452     /// candidate. For example, suppose we are testing whether `foo.x == 22`,
453     /// but in one match arm we have `Foo { x: _, ... }`... in that case,
454     /// the test for what value `x` has has no particular relevance
455     /// to this candidate. In such cases, this function just returns false
456     /// without doing anything. This is used by the overall `match_candidates`
457     /// algorithm to structure the match as a whole. See `match_candidates` for
458     /// more details.
459     ///
460     /// FIXME(#29623). In some cases, we have some tricky choices to
461     /// make.  for example, if we are testing that `x == 22`, but the
462     /// candidate is `x @ 13..55`, what should we do? In the event
463     /// that the test is true, we know that the candidate applies, but
464     /// in the event of false, we don't know that it *doesn't*
465     /// apply. For now, we return false, indicate that the test does
466     /// not apply to this candidate, but it might be we can get
467     /// tighter match code if we do something a bit different.
468     pub fn sort_candidate<'pat>(&mut self,
469                                 test_place: &Place<'tcx>,
470                                 test: &Test<'tcx>,
471                                 candidate: &Candidate<'pat, 'tcx>,
472                                 resulting_candidates: &mut [Vec<Candidate<'pat, 'tcx>>])
473                                 -> bool {
474         // Find the match_pair for this place (if any). At present,
475         // afaik, there can be at most one. (In the future, if we
476         // adopted a more general `@` operator, there might be more
477         // than one, but it'd be very unusual to have two sides that
478         // both require tests; you'd expect one side to be simplified
479         // away.)
480         let tested_match_pair = candidate.match_pairs.iter()
481                                                      .enumerate()
482                                                      .filter(|&(_, mp)| mp.place == *test_place)
483                                                      .next();
484         let (match_pair_index, match_pair) = match tested_match_pair {
485             Some(pair) => pair,
486             None => {
487                 // We are not testing this place. Therefore, this
488                 // candidate applies to ALL outcomes.
489                 return false;
490             }
491         };
492
493         match (&test.kind, &*match_pair.pattern.kind) {
494             // If we are performing a variant switch, then this
495             // informs variant patterns, but nothing else.
496             (&TestKind::Switch { adt_def: tested_adt_def, .. },
497              &PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. }) => {
498                 assert_eq!(adt_def, tested_adt_def);
499                 let new_candidate =
500                     self.candidate_after_variant_switch(match_pair_index,
501                                                         adt_def,
502                                                         variant_index,
503                                                         subpatterns,
504                                                         candidate);
505                 resulting_candidates[variant_index].push(new_candidate);
506                 true
507             }
508             (&TestKind::Switch { .. }, _) => false,
509
510             // If we are performing a switch over integers, then this informs integer
511             // equality, but nothing else.
512             //
513             // FIXME(#29623) we could use PatternKind::Range to rule
514             // things out here, in some cases.
515             (&TestKind::SwitchInt { switch_ty: _, options: _, ref indices },
516              &PatternKind::Constant { ref value })
517             if is_switch_ty(match_pair.pattern.ty) => {
518                 let index = indices[value];
519                 let new_candidate = self.candidate_without_match_pair(match_pair_index,
520                                                                       candidate);
521                 resulting_candidates[index].push(new_candidate);
522                 true
523             }
524             (&TestKind::SwitchInt { .. }, _) => false,
525
526
527             (&TestKind::Len { len: test_len, op: BinOp::Eq },
528              &PatternKind::Slice { ref prefix, ref slice, ref suffix }) => {
529                 let pat_len = (prefix.len() + suffix.len()) as u64;
530                 match (test_len.cmp(&pat_len), slice) {
531                     (Ordering::Equal, &None) => {
532                         // on true, min_len = len = $actual_length,
533                         // on false, len != $actual_length
534                         resulting_candidates[0].push(
535                             self.candidate_after_slice_test(match_pair_index,
536                                                             candidate,
537                                                             prefix,
538                                                             slice.as_ref(),
539                                                             suffix)
540                         );
541                         true
542                     }
543                     (Ordering::Less, _) => {
544                         // test_len < pat_len. If $actual_len = test_len,
545                         // then $actual_len < pat_len and we don't have
546                         // enough elements.
547                         resulting_candidates[1].push(candidate.clone());
548                         true
549                     }
550                     (Ordering::Equal, &Some(_)) | (Ordering::Greater, &Some(_)) => {
551                         // This can match both if $actual_len = test_len >= pat_len,
552                         // and if $actual_len > test_len. We can't advance.
553                         false
554                     }
555                     (Ordering::Greater, &None) => {
556                         // test_len != pat_len, so if $actual_len = test_len, then
557                         // $actual_len != pat_len.
558                         resulting_candidates[1].push(candidate.clone());
559                         true
560                     }
561                 }
562             }
563
564             (&TestKind::Len { len: test_len, op: BinOp::Ge },
565              &PatternKind::Slice { ref prefix, ref slice, ref suffix }) => {
566                 // the test is `$actual_len >= test_len`
567                 let pat_len = (prefix.len() + suffix.len()) as u64;
568                 match (test_len.cmp(&pat_len), slice) {
569                     (Ordering::Equal, &Some(_))  => {
570                         // $actual_len >= test_len = pat_len,
571                         // so we can match.
572                         resulting_candidates[0].push(
573                             self.candidate_after_slice_test(match_pair_index,
574                                                             candidate,
575                                                             prefix,
576                                                             slice.as_ref(),
577                                                             suffix)
578                         );
579                         true
580                     }
581                     (Ordering::Less, _) | (Ordering::Equal, &None) => {
582                         // test_len <= pat_len. If $actual_len < test_len,
583                         // then it is also < pat_len, so the test passing is
584                         // necessary (but insufficient).
585                         resulting_candidates[0].push(candidate.clone());
586                         true
587                     }
588                     (Ordering::Greater, &None) => {
589                         // test_len > pat_len. If $actual_len >= test_len > pat_len,
590                         // then we know we won't have a match.
591                         resulting_candidates[1].push(candidate.clone());
592                         true
593                     }
594                     (Ordering::Greater, &Some(_)) => {
595                         // test_len < pat_len, and is therefore less
596                         // strict. This can still go both ways.
597                         false
598                     }
599                 }
600             }
601
602             (&TestKind::Eq { .. }, _) |
603             (&TestKind::Range { .. }, _) |
604             (&TestKind::Len { .. }, _) => {
605                 // These are all binary tests.
606                 //
607                 // FIXME(#29623) we can be more clever here
608                 let pattern_test = self.test(&match_pair);
609                 if pattern_test.kind == test.kind {
610                     let new_candidate = self.candidate_without_match_pair(match_pair_index,
611                                                                           candidate);
612                     resulting_candidates[0].push(new_candidate);
613                     true
614                 } else {
615                     false
616                 }
617             }
618         }
619     }
620
621     fn candidate_without_match_pair<'pat>(&mut self,
622                                           match_pair_index: usize,
623                                           candidate: &Candidate<'pat, 'tcx>)
624                                           -> Candidate<'pat, 'tcx> {
625         let other_match_pairs =
626             candidate.match_pairs.iter()
627                                  .enumerate()
628                                  .filter(|&(index, _)| index != match_pair_index)
629                                  .map(|(_, mp)| mp.clone())
630                                  .collect();
631         Candidate {
632             span: candidate.span,
633             match_pairs: other_match_pairs,
634             bindings: candidate.bindings.clone(),
635             guard: candidate.guard.clone(),
636             arm_index: candidate.arm_index,
637             pre_binding_block: candidate.pre_binding_block,
638             next_candidate_pre_binding_block: candidate.next_candidate_pre_binding_block,
639         }
640     }
641
642     fn candidate_after_slice_test<'pat>(&mut self,
643                                         match_pair_index: usize,
644                                         candidate: &Candidate<'pat, 'tcx>,
645                                         prefix: &'pat [Pattern<'tcx>],
646                                         opt_slice: Option<&'pat Pattern<'tcx>>,
647                                         suffix: &'pat [Pattern<'tcx>])
648                                         -> Candidate<'pat, 'tcx> {
649         let mut new_candidate =
650             self.candidate_without_match_pair(match_pair_index, candidate);
651         self.prefix_slice_suffix(
652             &mut new_candidate.match_pairs,
653             &candidate.match_pairs[match_pair_index].place,
654             prefix,
655             opt_slice,
656             suffix);
657
658         new_candidate
659     }
660
661     fn candidate_after_variant_switch<'pat>(&mut self,
662                                             match_pair_index: usize,
663                                             adt_def: &'tcx ty::AdtDef,
664                                             variant_index: usize,
665                                             subpatterns: &'pat [FieldPattern<'tcx>],
666                                             candidate: &Candidate<'pat, 'tcx>)
667                                             -> Candidate<'pat, 'tcx> {
668         let match_pair = &candidate.match_pairs[match_pair_index];
669
670         // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`,
671         // we want to create a set of derived match-patterns like
672         // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`.
673         let elem = ProjectionElem::Downcast(adt_def, variant_index);
674         let downcast_place = match_pair.place.clone().elem(elem); // `(x as Variant)`
675         let consequent_match_pairs =
676             subpatterns.iter()
677                        .map(|subpattern| {
678                            // e.g., `(x as Variant).0`
679                            let place = downcast_place.clone().field(subpattern.field,
680                                                                       subpattern.pattern.ty);
681                            // e.g., `(x as Variant).0 @ P1`
682                            MatchPair::new(place, &subpattern.pattern)
683                        });
684
685         // In addition, we need all the other match pairs from the old candidate.
686         let other_match_pairs =
687             candidate.match_pairs.iter()
688                                  .enumerate()
689                                  .filter(|&(index, _)| index != match_pair_index)
690                                  .map(|(_, mp)| mp.clone());
691
692         let all_match_pairs = consequent_match_pairs.chain(other_match_pairs).collect();
693
694         Candidate {
695             span: candidate.span,
696             match_pairs: all_match_pairs,
697             bindings: candidate.bindings.clone(),
698             guard: candidate.guard.clone(),
699             arm_index: candidate.arm_index,
700             pre_binding_block: candidate.pre_binding_block,
701             next_candidate_pre_binding_block: candidate.next_candidate_pre_binding_block,
702         }
703     }
704
705     fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! {
706         span_bug!(match_pair.pattern.span,
707                   "simplifyable pattern found: {:?}",
708                   match_pair.pattern)
709     }
710 }
711
712 fn is_switch_ty<'tcx>(ty: Ty<'tcx>) -> bool {
713     ty.is_integral() || ty.is_char() || ty.is_bool()
714 }