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.
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.
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.
19 use build::matches::{Candidate, MatchPair, Test, TestKind};
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_data_structures::bitvec::BitArray;
23 use rustc::ty::{self, Ty};
24 use rustc::ty::util::IntTypeExt;
26 use rustc::hir::{RangeEnd, Mutability};
28 use std::cmp::Ordering;
30 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
31 /// Identifies what test is needed to decide if `match_pair` is applicable.
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: _ } => {
38 span: match_pair.pattern.span,
39 kind: TestKind::Switch {
40 adt_def: adt_def.clone(),
41 variants: BitArray::new(adt_def.variants.len()),
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
51 span: match_pair.pattern.span,
52 kind: TestKind::SwitchInt {
53 switch_ty: match_pair.pattern.ty,
55 // these maps are empty to start; cases are
56 // added below in add_cases_to_switch
63 PatternKind::Constant { value } => {
65 span: match_pair.pattern.span,
68 ty: match_pair.pattern.ty.clone()
73 PatternKind::Range { lo, hi, end } => {
75 span: match_pair.pattern.span,
76 kind: TestKind::Range {
79 ty: match_pair.pattern.ty.clone(),
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() {
94 span: match_pair.pattern.span,
95 kind: TestKind::Len { len: len as u64, op: op },
99 PatternKind::Array { .. } |
100 PatternKind::Slice { .. } |
102 PatternKind::Binding { .. } |
103 PatternKind::Leaf { .. } |
104 PatternKind::Deref { .. } => {
105 self.error_simplifyable(match_pair)
110 pub fn add_cases_to_switch<'pat>(&mut self,
111 test_place: &Place<'tcx>,
112 candidate: &Candidate<'pat, 'tcx>,
114 options: &mut Vec<u128>,
115 indices: &mut FxHashMap<&'tcx ty::Const<'tcx>, usize>)
118 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
119 Some(match_pair) => match_pair,
120 _ => { return false; }
123 match *match_pair.pattern.kind {
124 PatternKind::Constant { value } => {
125 let switch_ty = ty::ParamEnv::empty().and(switch_ty);
128 options.push(value.unwrap_bits(self.hir.tcx(), switch_ty));
133 PatternKind::Variant { .. } => {
134 panic!("you should have called add_variants_to_switch instead!");
136 PatternKind::Range { .. } |
137 PatternKind::Slice { .. } |
138 PatternKind::Array { .. } |
140 PatternKind::Binding { .. } |
141 PatternKind::Leaf { .. } |
142 PatternKind::Deref { .. } => {
143 // don't know how to add these patterns to a switch
149 pub fn add_variants_to_switch<'pat>(&mut self,
150 test_place: &Place<'tcx>,
151 candidate: &Candidate<'pat, 'tcx>,
152 variants: &mut BitArray<usize>)
155 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
156 Some(match_pair) => match_pair,
157 _ => { return false; }
160 match *match_pair.pattern.kind {
161 PatternKind::Variant { adt_def: _ , variant_index, .. } => {
162 // We have a pattern testing for variant `variant_index`
163 // set the corresponding index to true
164 variants.insert(variant_index);
168 // don't know how to add these patterns to a switch
174 /// Generates the code to perform a test.
175 pub fn perform_test(&mut self,
180 debug!("perform_test({:?}, {:?}: {:?}, {:?})",
183 place.ty(&self.local_decls, self.hir.tcx()),
185 let source_info = self.source_info(test.span);
187 TestKind::Switch { adt_def, ref variants } => {
188 // Variants is a BitVec of indexes into adt_def.variants.
189 let num_enum_variants = adt_def.variants.len();
190 let used_variants = variants.count();
191 let mut otherwise_block = None;
192 let mut target_blocks = Vec::with_capacity(num_enum_variants);
193 let mut targets = Vec::with_capacity(used_variants + 1);
194 let mut values = Vec::with_capacity(used_variants);
195 let tcx = self.hir.tcx();
196 for (idx, discr) in adt_def.discriminants(tcx).enumerate() {
197 target_blocks.push(if variants.contains(idx) {
198 values.push(discr.val);
199 targets.push(self.cfg.start_new_block());
200 *targets.last().unwrap()
202 if otherwise_block.is_none() {
203 otherwise_block = Some(self.cfg.start_new_block());
205 otherwise_block.unwrap()
208 if let Some(otherwise_block) = otherwise_block {
209 targets.push(otherwise_block);
211 targets.push(self.unreachable_block());
213 debug!("num_enum_variants: {}, tested variants: {:?}, variants: {:?}",
214 num_enum_variants, values, variants);
215 let discr_ty = adt_def.repr.discr_type().to_ty(tcx);
216 let discr = self.temp(discr_ty, test.span);
217 self.cfg.push_assign(block, source_info, &discr,
218 Rvalue::Discriminant(place.clone()));
219 assert_eq!(values.len() + 1, targets.len());
220 self.cfg.terminate(block, source_info, TerminatorKind::SwitchInt {
221 discr: Operand::Move(discr),
223 values: From::from(values),
229 TestKind::SwitchInt { switch_ty, ref options, indices: _ } => {
230 let (ret, terminator) = if switch_ty.sty == ty::TyBool {
231 assert!(options.len() > 0 && options.len() <= 2);
232 let (true_bb, false_bb) = (self.cfg.start_new_block(),
233 self.cfg.start_new_block());
234 let ret = match options[0] {
235 1 => vec![true_bb, false_bb],
236 0 => vec![false_bb, true_bb],
237 v => span_bug!(test.span, "expected boolean value but got {:?}", v)
239 (ret, TerminatorKind::if_(self.hir.tcx(), Operand::Copy(place.clone()),
242 // The switch may be inexhaustive so we
243 // add a catch all block
244 let otherwise = self.cfg.start_new_block();
245 let targets: Vec<_> =
247 .map(|_| self.cfg.start_new_block())
248 .chain(Some(otherwise))
250 (targets.clone(), TerminatorKind::SwitchInt {
251 discr: Operand::Copy(place.clone()),
253 values: options.clone().into(),
257 self.cfg.terminate(block, source_info, terminator);
261 TestKind::Eq { value, mut ty } => {
262 let val = Operand::Copy(place.clone());
263 let mut expect = self.literal_operand(test.span, ty, value);
264 // Use PartialEq::eq instead of BinOp::Eq
265 // (the binop can only handle primitives)
266 let fail = self.cfg.start_new_block();
268 // If we're using b"..." as a pattern, we need to insert an
269 // unsizing coercion, as the byte string has the type &[u8; N].
271 // We want to do this even when the scrutinee is a reference to an
272 // array, so we can call `<[u8]>::eq` rather than having to find an
274 let unsize = |ty: Ty<'tcx>| match ty.sty {
275 ty::TyRef(region, rty, _) => match rty.sty {
276 ty::TyArray(inner_ty, n) => Some((region, inner_ty, n)),
281 let opt_ref_ty = unsize(ty);
282 let opt_ref_test_ty = unsize(value.ty);
283 let mut place = place.clone();
284 match (opt_ref_ty, opt_ref_test_ty) {
285 // nothing to do, neither is an array
287 (Some((region, elem_ty, _)), _) |
288 (None, Some((region, elem_ty, _))) => {
289 let tcx = self.hir.tcx();
291 ty = tcx.mk_imm_ref(region, tcx.mk_slice(elem_ty));
292 if opt_ref_ty.is_some() {
293 place = self.temp(ty, test.span);
294 self.cfg.push_assign(block, source_info, &place,
295 Rvalue::Cast(CastKind::Unsize, val, ty));
297 if opt_ref_test_ty.is_some() {
298 let array = self.literal_operand(
304 let slice = self.temp(ty, test.span);
305 self.cfg.push_assign(block, source_info, &slice,
306 Rvalue::Cast(CastKind::Unsize, array, ty));
307 expect = Operand::Move(slice);
311 let eq_def_id = self.hir.tcx().lang_items().eq_trait().unwrap();
312 let (mty, method) = self.hir.trait_method(eq_def_id, "eq", ty, &[ty.into()]);
314 // take the argument by reference
315 let region_scope = self.topmost_scope();
316 let region = self.hir.tcx().mk_region(ty::ReScope(region_scope));
317 let tam = ty::TypeAndMut {
319 mutbl: Mutability::MutImmutable,
321 let ref_ty = self.hir.tcx().mk_ref(region, tam);
323 // let lhs_ref_place = &lhs;
324 let ref_rvalue = Rvalue::Ref(region, BorrowKind::Shared, place.clone());
325 let lhs_ref_place = self.temp(ref_ty, test.span);
326 self.cfg.push_assign(block, source_info, &lhs_ref_place, ref_rvalue);
327 let val = Operand::Move(lhs_ref_place);
329 // let rhs_place = rhs;
330 let rhs_place = self.temp(ty, test.span);
331 self.cfg.push_assign(block, source_info, &rhs_place, Rvalue::Use(expect));
333 // let rhs_ref_place = &rhs_place;
334 let ref_rvalue = Rvalue::Ref(region, BorrowKind::Shared, rhs_place);
335 let rhs_ref_place = self.temp(ref_ty, test.span);
336 self.cfg.push_assign(block, source_info, &rhs_ref_place, ref_rvalue);
337 let expect = Operand::Move(rhs_ref_place);
339 let bool_ty = self.hir.bool_ty();
340 let eq_result = self.temp(bool_ty, test.span);
341 let eq_block = self.cfg.start_new_block();
342 let cleanup = self.diverge_cleanup();
343 self.cfg.terminate(block, source_info, TerminatorKind::Call {
344 func: Operand::Constant(box Constant {
349 args: vec![val, expect],
350 destination: Some((eq_result.clone(), eq_block)),
351 cleanup: Some(cleanup),
355 let block = self.cfg.start_new_block();
356 self.cfg.terminate(eq_block, source_info,
357 TerminatorKind::if_(self.hir.tcx(),
358 Operand::Move(eq_result),
362 let block = self.compare(block, fail, test.span, BinOp::Eq, expect, val);
367 TestKind::Range { ref lo, ref hi, ty, ref end } => {
368 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
369 let lo = self.literal_operand(test.span, ty.clone(), lo.clone());
370 let hi = self.literal_operand(test.span, ty.clone(), hi.clone());
371 let val = Operand::Copy(place.clone());
373 let fail = self.cfg.start_new_block();
374 let block = self.compare(block, fail, test.span, BinOp::Le, lo, val.clone());
375 let block = match *end {
376 RangeEnd::Included => self.compare(block, fail, test.span, BinOp::Le, val, hi),
377 RangeEnd::Excluded => self.compare(block, fail, test.span, BinOp::Lt, val, hi),
383 TestKind::Len { len, op } => {
384 let (usize_ty, bool_ty) = (self.hir.usize_ty(), self.hir.bool_ty());
385 let (actual, result) = (self.temp(usize_ty, test.span),
386 self.temp(bool_ty, test.span));
388 // actual = len(place)
389 self.cfg.push_assign(block, source_info,
390 &actual, Rvalue::Len(place.clone()));
393 let expected = self.push_usize(block, source_info, len);
395 // result = actual == expected OR result = actual < expected
396 self.cfg.push_assign(block, source_info, &result,
398 Operand::Move(actual),
399 Operand::Move(expected)));
401 // branch based on result
402 let (false_bb, true_bb) = (self.cfg.start_new_block(),
403 self.cfg.start_new_block());
404 self.cfg.terminate(block, source_info,
405 TerminatorKind::if_(self.hir.tcx(), Operand::Move(result),
407 vec![true_bb, false_bb]
412 fn compare(&mut self,
414 fail_block: BasicBlock,
418 right: Operand<'tcx>) -> BasicBlock {
419 let bool_ty = self.hir.bool_ty();
420 let result = self.temp(bool_ty, span);
422 // result = op(left, right)
423 let source_info = self.source_info(span);
424 self.cfg.push_assign(block, source_info, &result,
425 Rvalue::BinaryOp(op, left, right));
427 // branch based on result
428 let target_block = self.cfg.start_new_block();
429 self.cfg.terminate(block, source_info,
430 TerminatorKind::if_(self.hir.tcx(), Operand::Move(result),
431 target_block, fail_block));
435 /// Given that we are performing `test` against `test_place`,
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
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
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
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_place: &Place<'tcx>,
468 candidate: &Candidate<'pat, 'tcx>,
469 resulting_candidates: &mut [Vec<Candidate<'pat, 'tcx>>])
471 // Find the match_pair for this place (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
477 let tested_match_pair = candidate.match_pairs.iter()
479 .filter(|&(_, mp)| mp.place == *test_place)
481 let (match_pair_index, match_pair) = match tested_match_pair {
484 // We are not testing this place. Therefore, this
485 // candidate applies to ALL outcomes.
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);
497 self.candidate_after_variant_switch(match_pair_index,
502 resulting_candidates[variant_index].push(new_candidate);
505 (&TestKind::Switch { .. }, _) => false,
507 // If we are performing a switch over integers, then this informs integer
508 // equality, but nothing else.
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,
518 resulting_candidates[index].push(new_candidate);
521 (&TestKind::SwitchInt { .. }, _) => false,
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,
540 (Ordering::Less, _) => {
541 // test_len < pat_len. If $actual_len = test_len,
542 // then $actual_len < pat_len and we don't have
544 resulting_candidates[1].push(candidate.clone());
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.
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());
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,
569 resulting_candidates[0].push(
570 self.candidate_after_slice_test(match_pair_index,
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());
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());
591 (Ordering::Greater, &Some(_)) => {
592 // test_len < pat_len, and is therefore less
593 // strict. This can still go both ways.
599 (&TestKind::Eq { .. }, _) |
600 (&TestKind::Range { .. }, _) |
601 (&TestKind::Len { .. }, _) => {
602 // These are all binary tests.
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,
609 resulting_candidates[0].push(new_candidate);
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()
625 .filter(|&(index, _)| index != match_pair_index)
626 .map(|(_, mp)| mp.clone())
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 pat_index: candidate.pat_index,
635 pre_binding_block: candidate.pre_binding_block,
636 next_candidate_pre_binding_block: candidate.next_candidate_pre_binding_block,
640 fn candidate_after_slice_test<'pat>(&mut self,
641 match_pair_index: usize,
642 candidate: &Candidate<'pat, 'tcx>,
643 prefix: &'pat [Pattern<'tcx>],
644 opt_slice: Option<&'pat Pattern<'tcx>>,
645 suffix: &'pat [Pattern<'tcx>])
646 -> Candidate<'pat, 'tcx> {
647 let mut new_candidate =
648 self.candidate_without_match_pair(match_pair_index, candidate);
649 self.prefix_slice_suffix(
650 &mut new_candidate.match_pairs,
651 &candidate.match_pairs[match_pair_index].place,
659 fn candidate_after_variant_switch<'pat>(&mut self,
660 match_pair_index: usize,
661 adt_def: &'tcx ty::AdtDef,
662 variant_index: usize,
663 subpatterns: &'pat [FieldPattern<'tcx>],
664 candidate: &Candidate<'pat, 'tcx>)
665 -> Candidate<'pat, 'tcx> {
666 let match_pair = &candidate.match_pairs[match_pair_index];
668 // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`,
669 // we want to create a set of derived match-patterns like
670 // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`.
671 let elem = ProjectionElem::Downcast(adt_def, variant_index);
672 let downcast_place = match_pair.place.clone().elem(elem); // `(x as Variant)`
673 let consequent_match_pairs =
676 // e.g., `(x as Variant).0`
677 let place = downcast_place.clone().field(subpattern.field,
678 subpattern.pattern.ty);
679 // e.g., `(x as Variant).0 @ P1`
680 MatchPair::new(place, &subpattern.pattern)
683 // In addition, we need all the other match pairs from the old candidate.
684 let other_match_pairs =
685 candidate.match_pairs.iter()
687 .filter(|&(index, _)| index != match_pair_index)
688 .map(|(_, mp)| mp.clone());
690 let all_match_pairs = consequent_match_pairs.chain(other_match_pairs).collect();
693 span: candidate.span,
694 match_pairs: all_match_pairs,
695 bindings: candidate.bindings.clone(),
696 guard: candidate.guard.clone(),
697 arm_index: candidate.arm_index,
698 pat_index: candidate.pat_index,
699 pre_binding_block: candidate.pre_binding_block,
700 next_candidate_pre_binding_block: candidate.next_candidate_pre_binding_block,
704 fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! {
705 span_bug!(match_pair.pattern.span,
706 "simplifyable pattern found: {:?}",
711 fn is_switch_ty<'tcx>(ty: Ty<'tcx>) -> bool {
712 ty.is_integral() || ty.is_char() || ty.is_bool()