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