3 // After candidates have been simplified, the only match pairs that
4 // remain are those that require some sort of test. The functions here
5 // identify what tests are needed, perform the tests, and then filter
6 // the candidates based on the result.
8 use crate::build::Builder;
9 use crate::build::matches::{Candidate, MatchPair, Test, TestKind};
11 use crate::hair::pattern::compare_const_vals;
12 use rustc_data_structures::bit_set::BitSet;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc::ty::{self, Ty, adjustment::{PointerCast}};
15 use rustc::ty::util::IntTypeExt;
16 use rustc::ty::layout::VariantIdx;
18 use rustc::hir::RangeEnd;
19 use syntax_pos::symbol::sym;
21 use std::cmp::Ordering;
23 impl<'a, 'tcx> Builder<'a, 'tcx> {
24 /// Identifies what test is needed to decide if `match_pair` is applicable.
26 /// It is a bug to call this with a simplifiable pattern.
27 pub fn test<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> Test<'tcx> {
28 match *match_pair.pattern.kind {
29 PatKind::Variant { ref adt_def, substs: _, variant_index: _, subpatterns: _ } => {
31 span: match_pair.pattern.span,
32 kind: TestKind::Switch {
33 adt_def: adt_def.clone(),
34 variants: BitSet::new_empty(adt_def.variants.len()),
39 PatKind::Constant { .. } if is_switch_ty(match_pair.pattern.ty) => {
40 // For integers, we use a `SwitchInt` match, which allows
41 // us to handle more cases.
43 span: match_pair.pattern.span,
44 kind: TestKind::SwitchInt {
45 switch_ty: match_pair.pattern.ty,
47 // these maps are empty to start; cases are
48 // added below in add_cases_to_switch
50 indices: Default::default(),
55 PatKind::Constant { value } => {
57 span: match_pair.pattern.span,
60 ty: match_pair.pattern.ty.clone()
65 PatKind::Range(range) => {
66 assert_eq!(range.lo.ty, match_pair.pattern.ty);
67 assert_eq!(range.hi.ty, match_pair.pattern.ty);
69 span: match_pair.pattern.span,
70 kind: TestKind::Range(range),
74 PatKind::Slice { ref prefix, ref slice, ref suffix } => {
75 let len = prefix.len() + suffix.len();
76 let op = if slice.is_some() {
82 span: match_pair.pattern.span,
83 kind: TestKind::Len { len: len as u64, op: op },
87 PatKind::AscribeUserType { .. } |
88 PatKind::Array { .. } |
91 PatKind::Binding { .. } |
92 PatKind::Leaf { .. } |
93 PatKind::Deref { .. } => {
94 self.error_simplifyable(match_pair)
99 pub fn add_cases_to_switch<'pat>(&mut self,
100 test_place: &Place<'tcx>,
101 candidate: &Candidate<'pat, 'tcx>,
103 options: &mut Vec<u128>,
104 indices: &mut FxHashMap<&'tcx ty::Const<'tcx>, usize>)
107 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
108 Some(match_pair) => match_pair,
109 _ => { return false; }
112 match *match_pair.pattern.kind {
113 PatKind::Constant { value } => {
116 options.push(value.eval_bits(
117 self.hir.tcx(), self.hir.param_env, switch_ty,
123 PatKind::Variant { .. } => {
124 panic!("you should have called add_variants_to_switch instead!");
126 PatKind::Range(range) => {
127 // Check that none of the switch values are in the range.
128 self.values_not_contained_in_range(range, indices)
131 PatKind::Slice { .. } |
132 PatKind::Array { .. } |
135 PatKind::Binding { .. } |
136 PatKind::AscribeUserType { .. } |
137 PatKind::Leaf { .. } |
138 PatKind::Deref { .. } => {
139 // don't know how to add these patterns to a switch
145 pub fn add_variants_to_switch<'pat>(&mut self,
146 test_place: &Place<'tcx>,
147 candidate: &Candidate<'pat, 'tcx>,
148 variants: &mut BitSet<VariantIdx>)
151 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
152 Some(match_pair) => match_pair,
153 _ => { return false; }
156 match *match_pair.pattern.kind {
157 PatKind::Variant { adt_def: _ , variant_index, .. } => {
158 // We have a pattern testing for variant `variant_index`
159 // set the corresponding index to true
160 variants.insert(variant_index);
164 // don't know how to add these patterns to a switch
175 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
177 debug!("perform_test({:?}, {:?}: {:?}, {:?})",
180 place.ty(&self.local_decls, self.hir.tcx()),
183 let source_info = self.source_info(test.span);
185 TestKind::Switch { adt_def, ref variants } => {
186 let target_blocks = make_target_blocks(self);
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 debug_assert_eq!(target_blocks.len(), num_enum_variants + 1);
191 let otherwise_block = *target_blocks.last().unwrap();
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) {
196 if variants.contains(idx) {
198 target_blocks[idx.index()],
200 "no canididates for tested discriminant: {:?}",
203 values.push(discr.val);
204 targets.push(target_blocks[idx.index()]);
207 target_blocks[idx.index()],
209 "found canididates for untested discriminant: {:?}",
214 targets.push(otherwise_block);
215 debug!("num_enum_variants: {}, tested variants: {:?}, variants: {:?}",
216 num_enum_variants, values, variants);
217 let discr_ty = adt_def.repr.discr_type().to_ty(tcx);
218 let discr = self.temp(discr_ty, test.span);
219 self.cfg.push_assign(block, source_info, &discr,
220 Rvalue::Discriminant(place.clone()));
221 assert_eq!(values.len() + 1, targets.len());
222 self.cfg.terminate(block, source_info, TerminatorKind::SwitchInt {
223 discr: Operand::Move(discr),
225 values: From::from(values),
230 TestKind::SwitchInt { switch_ty, ref options, indices: _ } => {
231 let target_blocks = make_target_blocks(self);
232 let terminator = if switch_ty.kind == ty::Bool {
233 assert!(options.len() > 0 && options.len() <= 2);
234 if let [first_bb, second_bb] = *target_blocks {
235 let (true_bb, false_bb) = match options[0] {
236 1 => (first_bb, second_bb),
237 0 => (second_bb, first_bb),
238 v => span_bug!(test.span, "expected boolean value but got {:?}", v)
242 Operand::Copy(place.clone()),
247 bug!("`TestKind::SwitchInt` on `bool` should have two targets")
250 // The switch may be inexhaustive so we have a catch all block
251 debug_assert_eq!(options.len() + 1, target_blocks.len());
252 TerminatorKind::SwitchInt {
253 discr: Operand::Copy(place.clone()),
255 values: options.clone().into(),
256 targets: target_blocks,
259 self.cfg.terminate(block, source_info, terminator);
262 TestKind::Eq { value, ty } => {
264 // Use `PartialEq::eq` instead of `BinOp::Eq`
265 // (the binop can only handle primitives)
266 self.non_scalar_compare(
275 if let [success, fail] = *make_target_blocks(self) {
276 assert_eq!(value.ty, ty);
277 let expect = self.literal_operand(test.span, value);
278 let val = Operand::Copy(place.clone());
279 self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
281 bug!("`TestKind::Eq` should have two target blocks");
286 TestKind::Range(PatRange { ref lo, ref hi, ref end }) => {
287 let lower_bound_success = self.cfg.start_new_block();
288 let target_blocks = make_target_blocks(self);
290 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
291 let lo = self.literal_operand(test.span, lo);
292 let hi = self.literal_operand(test.span, hi);
293 let val = Operand::Copy(place.clone());
295 if let [success, fail] = *target_blocks {
305 let op = match *end {
306 RangeEnd::Included => BinOp::Le,
307 RangeEnd::Excluded => BinOp::Lt,
309 self.compare(lower_bound_success, success, fail, source_info, op, val, hi);
311 bug!("`TestKind::Range` should have two target blocks");
315 TestKind::Len { len, op } => {
316 let target_blocks = make_target_blocks(self);
318 let usize_ty = self.hir.usize_ty();
319 let actual = self.temp(usize_ty, test.span);
321 // actual = len(place)
322 self.cfg.push_assign(block, source_info,
323 &actual, Rvalue::Len(place.clone()));
326 let expected = self.push_usize(block, source_info, len);
328 if let [true_bb, false_bb] = *target_blocks {
329 // result = actual == expected OR result = actual < expected
330 // branch based on result
337 Operand::Move(actual),
338 Operand::Move(expected),
341 bug!("`TestKind::Len` should have two target blocks");
347 /// Compare using the provided built-in comparison operator
351 success_block: BasicBlock,
352 fail_block: BasicBlock,
353 source_info: SourceInfo,
356 right: Operand<'tcx>,
358 let bool_ty = self.hir.bool_ty();
359 let result = self.temp(bool_ty, source_info.span);
361 // result = op(left, right)
362 self.cfg.push_assign(
366 Rvalue::BinaryOp(op, left, right),
369 // branch based on result
375 Operand::Move(result),
382 /// Compare two `&T` values using `<T as std::compare::PartialEq>::eq`
383 fn non_scalar_compare(
386 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
387 source_info: SourceInfo,
388 value: &'tcx ty::Const<'tcx>,
392 use rustc::middle::lang_items::EqTraitLangItem;
394 let mut expect = self.literal_operand(source_info.span, value);
395 let mut val = Operand::Copy(place.clone());
397 // If we're using `b"..."` as a pattern, we need to insert an
398 // unsizing coercion, as the byte string has the type `&[u8; N]`.
400 // We want to do this even when the scrutinee is a reference to an
401 // array, so we can call `<[u8]>::eq` rather than having to find an
403 let unsize = |ty: Ty<'tcx>| match ty.kind {
404 ty::Ref(region, rty, _) => match rty.kind {
405 ty::Array(inner_ty, n) => Some((region, inner_ty, n)),
410 let opt_ref_ty = unsize(ty);
411 let opt_ref_test_ty = unsize(value.ty);
412 match (opt_ref_ty, opt_ref_test_ty) {
413 // nothing to do, neither is an array
415 (Some((region, elem_ty, _)), _) |
416 (None, Some((region, elem_ty, _))) => {
417 let tcx = self.hir.tcx();
419 ty = tcx.mk_imm_ref(region, tcx.mk_slice(elem_ty));
420 if opt_ref_ty.is_some() {
421 let temp = self.temp(ty, source_info.span);
422 self.cfg.push_assign(
423 block, source_info, &temp, Rvalue::Cast(
424 CastKind::Pointer(PointerCast::Unsize), val, ty
427 val = Operand::Move(temp);
429 if opt_ref_test_ty.is_some() {
430 let slice = self.temp(ty, source_info.span);
431 self.cfg.push_assign(
432 block, source_info, &slice, Rvalue::Cast(
433 CastKind::Pointer(PointerCast::Unsize), expect, ty
436 expect = Operand::Move(slice);
441 let deref_ty = match ty.kind {
442 ty::Ref(_, deref_ty, _) => deref_ty,
443 _ => bug!("non_scalar_compare called on non-reference type: {}", ty),
446 let eq_def_id = self.hir.tcx().require_lang_item(EqTraitLangItem, None);
447 let method = self.hir.trait_method(eq_def_id, sym::eq, deref_ty, &[deref_ty.into()]);
449 let bool_ty = self.hir.bool_ty();
450 let eq_result = self.temp(bool_ty, source_info.span);
451 let eq_block = self.cfg.start_new_block();
452 let cleanup = self.diverge_cleanup();
453 self.cfg.terminate(block, source_info, TerminatorKind::Call {
454 func: Operand::Constant(box Constant {
455 span: source_info.span,
457 // FIXME(#54571): This constant comes from user input (a
458 // constant in a pattern). Are there forms where users can add
459 // type annotations here? For example, an associated constant?
460 // Need to experiment.
465 args: vec![val, expect],
466 destination: Some((eq_result.clone(), eq_block)),
467 cleanup: Some(cleanup),
468 from_hir_call: false,
471 if let [success_block, fail_block] = *make_target_blocks(self) {
478 Operand::Move(eq_result),
484 bug!("`TestKind::Eq` should have two target blocks")
488 /// Given that we are performing `test` against `test_place`, this job
489 /// sorts out what the status of `candidate` will be after the test. See
490 /// `test_candidates` for the usage of this function. The returned index is
491 /// the index that this candiate should be placed in the
492 /// `target_candidates` vec. The candidate may be modified to update its
495 /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
496 /// a variant test, then we would modify the candidate to be `(x as
497 /// Option).0 @ P0` and return the index corresponding to the variant
500 /// However, in some cases, the test may just not be relevant to candidate.
501 /// For example, suppose we are testing whether `foo.x == 22`, but in one
502 /// match arm we have `Foo { x: _, ... }`... in that case, the test for
503 /// what value `x` has has no particular relevance to this candidate. In
504 /// such cases, this function just returns None without doing anything.
505 /// This is used by the overall `match_candidates` algorithm to structure
506 /// the match as a whole. See `match_candidates` for more details.
508 /// FIXME(#29623). In some cases, we have some tricky choices to make. for
509 /// example, if we are testing that `x == 22`, but the candidate is `x @
510 /// 13..55`, what should we do? In the event that the test is true, we know
511 /// that the candidate applies, but in the event of false, we don't know
512 /// that it *doesn't* apply. For now, we return false, indicate that the
513 /// test does not apply to this candidate, but it might be we can get
514 /// tighter match code if we do something a bit different.
515 pub fn sort_candidate<'pat>(
517 test_place: &Place<'tcx>,
519 candidate: &mut Candidate<'pat, 'tcx>,
521 // Find the match_pair for this place (if any). At present,
522 // afaik, there can be at most one. (In the future, if we
523 // adopted a more general `@` operator, there might be more
524 // than one, but it'd be very unusual to have two sides that
525 // both require tests; you'd expect one side to be simplified
527 let (match_pair_index, match_pair) = candidate.match_pairs
530 .find(|&(_, mp)| mp.place == *test_place)?;
532 match (&test.kind, &*match_pair.pattern.kind) {
533 // If we are performing a variant switch, then this
534 // informs variant patterns, but nothing else.
535 (&TestKind::Switch { adt_def: tested_adt_def, .. },
536 &PatKind::Variant { adt_def, variant_index, ref subpatterns, .. }) => {
537 assert_eq!(adt_def, tested_adt_def);
538 self.candidate_after_variant_switch(match_pair_index,
543 Some(variant_index.as_usize())
546 (&TestKind::Switch { .. }, _) => None,
548 // If we are performing a switch over integers, then this informs integer
549 // equality, but nothing else.
551 // FIXME(#29623) we could use PatKind::Range to rule
552 // things out here, in some cases.
553 (&TestKind::SwitchInt { switch_ty: _, options: _, ref indices },
554 &PatKind::Constant { ref value })
555 if is_switch_ty(match_pair.pattern.ty) => {
556 let index = indices[value];
557 self.candidate_without_match_pair(match_pair_index, candidate);
561 (&TestKind::SwitchInt { switch_ty: _, ref options, ref indices },
562 &PatKind::Range(range)) => {
563 let not_contained = self
564 .values_not_contained_in_range(range, indices)
568 // No switch values are contained in the pattern range,
569 // so the pattern can be matched only if this test fails.
570 let otherwise = options.len();
577 (&TestKind::SwitchInt { .. }, _) => None,
579 (&TestKind::Len { len: test_len, op: BinOp::Eq },
580 &PatKind::Slice { ref prefix, ref slice, ref suffix }) => {
581 let pat_len = (prefix.len() + suffix.len()) as u64;
582 match (test_len.cmp(&pat_len), slice) {
583 (Ordering::Equal, &None) => {
584 // on true, min_len = len = $actual_length,
585 // on false, len != $actual_length
586 self.candidate_after_slice_test(match_pair_index,
593 (Ordering::Less, _) => {
594 // test_len < pat_len. If $actual_len = test_len,
595 // then $actual_len < pat_len and we don't have
599 (Ordering::Equal, &Some(_)) | (Ordering::Greater, &Some(_)) => {
600 // This can match both if $actual_len = test_len >= pat_len,
601 // and if $actual_len > test_len. We can't advance.
604 (Ordering::Greater, &None) => {
605 // test_len != pat_len, so if $actual_len = test_len, then
606 // $actual_len != pat_len.
612 (&TestKind::Len { len: test_len, op: BinOp::Ge },
613 &PatKind::Slice { ref prefix, ref slice, ref suffix }) => {
614 // the test is `$actual_len >= test_len`
615 let pat_len = (prefix.len() + suffix.len()) as u64;
616 match (test_len.cmp(&pat_len), slice) {
617 (Ordering::Equal, &Some(_)) => {
618 // $actual_len >= test_len = pat_len,
620 self.candidate_after_slice_test(match_pair_index,
627 (Ordering::Less, _) | (Ordering::Equal, &None) => {
628 // test_len <= pat_len. If $actual_len < test_len,
629 // then it is also < pat_len, so the test passing is
630 // necessary (but insufficient).
633 (Ordering::Greater, &None) => {
634 // test_len > pat_len. If $actual_len >= test_len > pat_len,
635 // then we know we won't have a match.
638 (Ordering::Greater, &Some(_)) => {
639 // test_len < pat_len, and is therefore less
640 // strict. This can still go both ways.
646 (&TestKind::Range(test),
647 &PatKind::Range(pat)) => {
649 self.candidate_without_match_pair(
656 let no_overlap = (|| {
657 use std::cmp::Ordering::*;
658 use rustc::hir::RangeEnd::*;
660 let tcx = self.hir.tcx();
662 let test_ty = test.lo.ty;
663 let lo = compare_const_vals(tcx, test.lo, pat.hi, self.hir.param_env, test_ty)?;
664 let hi = compare_const_vals(tcx, test.hi, pat.lo, self.hir.param_env, test_ty)?;
666 match (test.end, pat.end, lo, hi) {
669 (_, Excluded, Equal, _) |
672 (Excluded, _, _, Equal) => Some(true),
677 if no_overlap == Some(true) {
678 // Testing range does not overlap with pattern range,
679 // so the pattern can be matched only if this test fails.
686 (&TestKind::Range(range), &PatKind::Constant { value }) => {
687 if self.const_range_contains(range, value) == Some(false) {
688 // `value` is not contained in the testing range,
689 // so `value` can be matched only if this test fails.
696 (&TestKind::Range { .. }, _) => None,
698 (&TestKind::Eq { .. }, _) |
699 (&TestKind::Len { .. }, _) => {
700 // These are all binary tests.
702 // FIXME(#29623) we can be more clever here
703 let pattern_test = self.test(&match_pair);
704 if pattern_test.kind == test.kind {
705 self.candidate_without_match_pair(match_pair_index, candidate);
714 fn candidate_without_match_pair(
716 match_pair_index: usize,
717 candidate: &mut Candidate<'_, 'tcx>,
719 candidate.match_pairs.remove(match_pair_index);
722 fn candidate_after_slice_test<'pat>(&mut self,
723 match_pair_index: usize,
724 candidate: &mut Candidate<'pat, 'tcx>,
725 prefix: &'pat [Pat<'tcx>],
726 opt_slice: Option<&'pat Pat<'tcx>>,
727 suffix: &'pat [Pat<'tcx>]) {
728 let removed_place = candidate.match_pairs.remove(match_pair_index).place;
729 self.prefix_slice_suffix(
730 &mut candidate.match_pairs,
737 fn candidate_after_variant_switch<'pat>(
739 match_pair_index: usize,
740 adt_def: &'tcx ty::AdtDef,
741 variant_index: VariantIdx,
742 subpatterns: &'pat [FieldPat<'tcx>],
743 candidate: &mut Candidate<'pat, 'tcx>,
745 let match_pair = candidate.match_pairs.remove(match_pair_index);
747 // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`,
748 // we want to create a set of derived match-patterns like
749 // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`.
750 let elem = ProjectionElem::Downcast(
751 Some(adt_def.variants[variant_index].ident.name), variant_index);
752 let downcast_place = match_pair.place.elem(elem); // `(x as Variant)`
753 let consequent_match_pairs =
756 // e.g., `(x as Variant).0`
757 let place = downcast_place.clone().field(subpattern.field,
758 subpattern.pattern.ty);
759 // e.g., `(x as Variant).0 @ P1`
760 MatchPair::new(place, &subpattern.pattern)
763 candidate.match_pairs.extend(consequent_match_pairs);
766 fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! {
767 span_bug!(match_pair.pattern.span,
768 "simplifyable pattern found: {:?}",
772 fn const_range_contains(
774 range: PatRange<'tcx>,
775 value: &'tcx ty::Const<'tcx>,
777 use std::cmp::Ordering::*;
779 let tcx = self.hir.tcx();
781 let a = compare_const_vals(tcx, range.lo, value, self.hir.param_env, range.lo.ty)?;
782 let b = compare_const_vals(tcx, value, range.hi, self.hir.param_env, range.lo.ty)?;
784 match (b, range.end) {
786 (Equal, RangeEnd::Included) if a != Greater => Some(true),
791 fn values_not_contained_in_range(
793 range: PatRange<'tcx>,
794 indices: &FxHashMap<&'tcx ty::Const<'tcx>, usize>,
796 for &val in indices.keys() {
797 if self.const_range_contains(range, val)? {
807 pub(super) fn targets(&self) -> usize {
809 TestKind::Eq { .. } | TestKind::Range(_) | TestKind::Len { .. } => {
812 TestKind::Switch { adt_def, .. } => {
813 // While the switch that we generate doesn't test for all
814 // variants, we have a target for each variant and the
815 // otherwise case, and we make sure that all of the cases not
816 // specified have the same block.
817 adt_def.variants.len() + 1
819 TestKind::SwitchInt { switch_ty, ref options, .. } => {
820 if switch_ty.is_bool() {
821 // `bool` is special cased in `perform_test` to always
822 // branch to two blocks.
832 fn is_switch_ty(ty: Ty<'_>) -> bool {
833 ty.is_integral() || ty.is_char() || ty.is_bool()