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_index::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::Or { .. } => {
88 self.hir.tcx().sess.span_fatal(
89 match_pair.pattern.span,
90 "or-patterns are not fully implemented yet"
94 PatKind::AscribeUserType { .. } |
95 PatKind::Array { .. } |
97 PatKind::Binding { .. } |
98 PatKind::Leaf { .. } |
99 PatKind::Deref { .. } => {
100 self.error_simplifyable(match_pair)
105 pub fn add_cases_to_switch<'pat>(&mut self,
106 test_place: &Place<'tcx>,
107 candidate: &Candidate<'pat, 'tcx>,
109 options: &mut Vec<u128>,
110 indices: &mut FxHashMap<&'tcx ty::Const<'tcx>, usize>)
113 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
114 Some(match_pair) => match_pair,
115 _ => { return false; }
118 match *match_pair.pattern.kind {
119 PatKind::Constant { value } => {
122 options.push(value.eval_bits(
123 self.hir.tcx(), self.hir.param_env, switch_ty,
129 PatKind::Variant { .. } => {
130 panic!("you should have called add_variants_to_switch instead!");
132 PatKind::Range(range) => {
133 // Check that none of the switch values are in the range.
134 self.values_not_contained_in_range(range, indices)
137 PatKind::Slice { .. } |
138 PatKind::Array { .. } |
141 PatKind::Binding { .. } |
142 PatKind::AscribeUserType { .. } |
143 PatKind::Leaf { .. } |
144 PatKind::Deref { .. } => {
145 // don't know how to add these patterns to a switch
151 pub fn add_variants_to_switch<'pat>(&mut self,
152 test_place: &Place<'tcx>,
153 candidate: &Candidate<'pat, 'tcx>,
154 variants: &mut BitSet<VariantIdx>)
157 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
158 Some(match_pair) => match_pair,
159 _ => { return false; }
162 match *match_pair.pattern.kind {
163 PatKind::Variant { adt_def: _ , variant_index, .. } => {
164 // We have a pattern testing for variant `variant_index`
165 // set the corresponding index to true
166 variants.insert(variant_index);
170 // don't know how to add these patterns to a switch
181 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
183 debug!("perform_test({:?}, {:?}: {:?}, {:?})",
186 place.ty(&self.local_decls, self.hir.tcx()),
189 let source_info = self.source_info(test.span);
191 TestKind::Switch { adt_def, ref variants } => {
192 let target_blocks = make_target_blocks(self);
193 // Variants is a BitVec of indexes into adt_def.variants.
194 let num_enum_variants = adt_def.variants.len();
195 let used_variants = variants.count();
196 debug_assert_eq!(target_blocks.len(), num_enum_variants + 1);
197 let otherwise_block = *target_blocks.last().unwrap();
198 let mut targets = Vec::with_capacity(used_variants + 1);
199 let mut values = Vec::with_capacity(used_variants);
200 let tcx = self.hir.tcx();
201 for (idx, discr) in adt_def.discriminants(tcx) {
202 if variants.contains(idx) {
204 target_blocks[idx.index()],
206 "no canididates for tested discriminant: {:?}",
209 values.push(discr.val);
210 targets.push(target_blocks[idx.index()]);
213 target_blocks[idx.index()],
215 "found canididates for untested discriminant: {:?}",
220 targets.push(otherwise_block);
221 debug!("num_enum_variants: {}, tested variants: {:?}, variants: {:?}",
222 num_enum_variants, values, variants);
223 let discr_ty = adt_def.repr.discr_type().to_ty(tcx);
224 let discr = self.temp(discr_ty, test.span);
225 self.cfg.push_assign(block, source_info, &discr,
226 Rvalue::Discriminant(place.clone()));
227 assert_eq!(values.len() + 1, targets.len());
228 self.cfg.terminate(block, source_info, TerminatorKind::SwitchInt {
229 discr: Operand::Move(discr),
231 values: From::from(values),
236 TestKind::SwitchInt { switch_ty, ref options, indices: _ } => {
237 let target_blocks = make_target_blocks(self);
238 let terminator = if switch_ty.kind == ty::Bool {
239 assert!(options.len() > 0 && options.len() <= 2);
240 if let [first_bb, second_bb] = *target_blocks {
241 let (true_bb, false_bb) = match options[0] {
242 1 => (first_bb, second_bb),
243 0 => (second_bb, first_bb),
244 v => span_bug!(test.span, "expected boolean value but got {:?}", v)
248 Operand::Copy(place.clone()),
253 bug!("`TestKind::SwitchInt` on `bool` should have two targets")
256 // The switch may be inexhaustive so we have a catch all block
257 debug_assert_eq!(options.len() + 1, target_blocks.len());
258 TerminatorKind::SwitchInt {
259 discr: Operand::Copy(place.clone()),
261 values: options.clone().into(),
262 targets: target_blocks,
265 self.cfg.terminate(block, source_info, terminator);
268 TestKind::Eq { value, ty } => {
270 // Use `PartialEq::eq` instead of `BinOp::Eq`
271 // (the binop can only handle primitives)
272 self.non_scalar_compare(
281 if let [success, fail] = *make_target_blocks(self) {
282 assert_eq!(value.ty, ty);
283 let expect = self.literal_operand(test.span, value);
284 let val = Operand::Copy(place.clone());
285 self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
287 bug!("`TestKind::Eq` should have two target blocks");
292 TestKind::Range(PatRange { ref lo, ref hi, ref end }) => {
293 let lower_bound_success = self.cfg.start_new_block();
294 let target_blocks = make_target_blocks(self);
296 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
297 let lo = self.literal_operand(test.span, lo);
298 let hi = self.literal_operand(test.span, hi);
299 let val = Operand::Copy(place.clone());
301 if let [success, fail] = *target_blocks {
311 let op = match *end {
312 RangeEnd::Included => BinOp::Le,
313 RangeEnd::Excluded => BinOp::Lt,
315 self.compare(lower_bound_success, success, fail, source_info, op, val, hi);
317 bug!("`TestKind::Range` should have two target blocks");
321 TestKind::Len { len, op } => {
322 let target_blocks = make_target_blocks(self);
324 let usize_ty = self.hir.usize_ty();
325 let actual = self.temp(usize_ty, test.span);
327 // actual = len(place)
328 self.cfg.push_assign(block, source_info,
329 &actual, Rvalue::Len(place.clone()));
332 let expected = self.push_usize(block, source_info, len);
334 if let [true_bb, false_bb] = *target_blocks {
335 // result = actual == expected OR result = actual < expected
336 // branch based on result
343 Operand::Move(actual),
344 Operand::Move(expected),
347 bug!("`TestKind::Len` should have two target blocks");
353 /// Compare using the provided built-in comparison operator
357 success_block: BasicBlock,
358 fail_block: BasicBlock,
359 source_info: SourceInfo,
362 right: Operand<'tcx>,
364 let bool_ty = self.hir.bool_ty();
365 let result = self.temp(bool_ty, source_info.span);
367 // result = op(left, right)
368 self.cfg.push_assign(
372 Rvalue::BinaryOp(op, left, right),
375 // branch based on result
381 Operand::Move(result),
388 /// Compare two `&T` values using `<T as std::compare::PartialEq>::eq`
389 fn non_scalar_compare(
392 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
393 source_info: SourceInfo,
394 value: &'tcx ty::Const<'tcx>,
398 use rustc::middle::lang_items::EqTraitLangItem;
400 let mut expect = self.literal_operand(source_info.span, value);
401 let mut val = Operand::Copy(place.clone());
403 // If we're using `b"..."` as a pattern, we need to insert an
404 // unsizing coercion, as the byte string has the type `&[u8; N]`.
406 // We want to do this even when the scrutinee is a reference to an
407 // array, so we can call `<[u8]>::eq` rather than having to find an
409 let unsize = |ty: Ty<'tcx>| match ty.kind {
410 ty::Ref(region, rty, _) => match rty.kind {
411 ty::Array(inner_ty, n) => Some((region, inner_ty, n)),
416 let opt_ref_ty = unsize(ty);
417 let opt_ref_test_ty = unsize(value.ty);
418 match (opt_ref_ty, opt_ref_test_ty) {
419 // nothing to do, neither is an array
421 (Some((region, elem_ty, _)), _) |
422 (None, Some((region, elem_ty, _))) => {
423 let tcx = self.hir.tcx();
425 ty = tcx.mk_imm_ref(region, tcx.mk_slice(elem_ty));
426 if opt_ref_ty.is_some() {
427 let temp = self.temp(ty, source_info.span);
428 self.cfg.push_assign(
429 block, source_info, &temp, Rvalue::Cast(
430 CastKind::Pointer(PointerCast::Unsize), val, ty
433 val = Operand::Move(temp);
435 if opt_ref_test_ty.is_some() {
436 let slice = self.temp(ty, source_info.span);
437 self.cfg.push_assign(
438 block, source_info, &slice, Rvalue::Cast(
439 CastKind::Pointer(PointerCast::Unsize), expect, ty
442 expect = Operand::Move(slice);
447 let deref_ty = match ty.kind {
448 ty::Ref(_, deref_ty, _) => deref_ty,
449 _ => bug!("non_scalar_compare called on non-reference type: {}", ty),
452 let eq_def_id = self.hir.tcx().require_lang_item(EqTraitLangItem, None);
453 let method = self.hir.trait_method(eq_def_id, sym::eq, deref_ty, &[deref_ty.into()]);
455 let bool_ty = self.hir.bool_ty();
456 let eq_result = self.temp(bool_ty, source_info.span);
457 let eq_block = self.cfg.start_new_block();
458 let cleanup = self.diverge_cleanup();
459 self.cfg.terminate(block, source_info, TerminatorKind::Call {
460 func: Operand::Constant(box Constant {
461 span: source_info.span,
463 // FIXME(#54571): This constant comes from user input (a
464 // constant in a pattern). Are there forms where users can add
465 // type annotations here? For example, an associated constant?
466 // Need to experiment.
471 args: vec![val, expect],
472 destination: Some((eq_result.clone(), eq_block)),
473 cleanup: Some(cleanup),
474 from_hir_call: false,
477 if let [success_block, fail_block] = *make_target_blocks(self) {
484 Operand::Move(eq_result),
490 bug!("`TestKind::Eq` should have two target blocks")
494 /// Given that we are performing `test` against `test_place`, this job
495 /// sorts out what the status of `candidate` will be after the test. See
496 /// `test_candidates` for the usage of this function. The returned index is
497 /// the index that this candidate should be placed in the
498 /// `target_candidates` vec. The candidate may be modified to update its
501 /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
502 /// a variant test, then we would modify the candidate to be `(x as
503 /// Option).0 @ P0` and return the index corresponding to the variant
506 /// However, in some cases, the test may just not be relevant to candidate.
507 /// For example, suppose we are testing whether `foo.x == 22`, but in one
508 /// match arm we have `Foo { x: _, ... }`... in that case, the test for
509 /// what value `x` has has no particular relevance to this candidate. In
510 /// such cases, this function just returns None without doing anything.
511 /// This is used by the overall `match_candidates` algorithm to structure
512 /// the match as a whole. See `match_candidates` for more details.
514 /// FIXME(#29623). In some cases, we have some tricky choices to make. for
515 /// example, if we are testing that `x == 22`, but the candidate is `x @
516 /// 13..55`, what should we do? In the event that the test is true, we know
517 /// that the candidate applies, but in the event of false, we don't know
518 /// that it *doesn't* apply. For now, we return false, indicate that the
519 /// test does not apply to this candidate, but it might be we can get
520 /// tighter match code if we do something a bit different.
521 pub fn sort_candidate<'pat>(
523 test_place: &Place<'tcx>,
525 candidate: &mut Candidate<'pat, 'tcx>,
527 // Find the match_pair for this place (if any). At present,
528 // afaik, there can be at most one. (In the future, if we
529 // adopted a more general `@` operator, there might be more
530 // than one, but it'd be very unusual to have two sides that
531 // both require tests; you'd expect one side to be simplified
533 let (match_pair_index, match_pair) = candidate.match_pairs
536 .find(|&(_, mp)| mp.place == *test_place)?;
538 match (&test.kind, &*match_pair.pattern.kind) {
539 // If we are performing a variant switch, then this
540 // informs variant patterns, but nothing else.
541 (&TestKind::Switch { adt_def: tested_adt_def, .. },
542 &PatKind::Variant { adt_def, variant_index, ref subpatterns, .. }) => {
543 assert_eq!(adt_def, tested_adt_def);
544 self.candidate_after_variant_switch(match_pair_index,
549 Some(variant_index.as_usize())
552 (&TestKind::Switch { .. }, _) => None,
554 // If we are performing a switch over integers, then this informs integer
555 // equality, but nothing else.
557 // FIXME(#29623) we could use PatKind::Range to rule
558 // things out here, in some cases.
559 (&TestKind::SwitchInt { switch_ty: _, options: _, ref indices },
560 &PatKind::Constant { ref value })
561 if is_switch_ty(match_pair.pattern.ty) => {
562 let index = indices[value];
563 self.candidate_without_match_pair(match_pair_index, candidate);
567 (&TestKind::SwitchInt { switch_ty: _, ref options, ref indices },
568 &PatKind::Range(range)) => {
569 let not_contained = self
570 .values_not_contained_in_range(range, indices)
574 // No switch values are contained in the pattern range,
575 // so the pattern can be matched only if this test fails.
576 let otherwise = options.len();
583 (&TestKind::SwitchInt { .. }, _) => None,
585 (&TestKind::Len { len: test_len, op: BinOp::Eq },
586 &PatKind::Slice { ref prefix, ref slice, ref suffix }) => {
587 let pat_len = (prefix.len() + suffix.len()) as u64;
588 match (test_len.cmp(&pat_len), slice) {
589 (Ordering::Equal, &None) => {
590 // on true, min_len = len = $actual_length,
591 // on false, len != $actual_length
592 self.candidate_after_slice_test(match_pair_index,
599 (Ordering::Less, _) => {
600 // test_len < pat_len. If $actual_len = test_len,
601 // then $actual_len < pat_len and we don't have
605 (Ordering::Equal, &Some(_)) | (Ordering::Greater, &Some(_)) => {
606 // This can match both if $actual_len = test_len >= pat_len,
607 // and if $actual_len > test_len. We can't advance.
610 (Ordering::Greater, &None) => {
611 // test_len != pat_len, so if $actual_len = test_len, then
612 // $actual_len != pat_len.
618 (&TestKind::Len { len: test_len, op: BinOp::Ge },
619 &PatKind::Slice { ref prefix, ref slice, ref suffix }) => {
620 // the test is `$actual_len >= test_len`
621 let pat_len = (prefix.len() + suffix.len()) as u64;
622 match (test_len.cmp(&pat_len), slice) {
623 (Ordering::Equal, &Some(_)) => {
624 // $actual_len >= test_len = pat_len,
626 self.candidate_after_slice_test(match_pair_index,
633 (Ordering::Less, _) | (Ordering::Equal, &None) => {
634 // test_len <= pat_len. If $actual_len < test_len,
635 // then it is also < pat_len, so the test passing is
636 // necessary (but insufficient).
639 (Ordering::Greater, &None) => {
640 // test_len > pat_len. If $actual_len >= test_len > pat_len,
641 // then we know we won't have a match.
644 (Ordering::Greater, &Some(_)) => {
645 // test_len < pat_len, and is therefore less
646 // strict. This can still go both ways.
652 (&TestKind::Range(test),
653 &PatKind::Range(pat)) => {
655 self.candidate_without_match_pair(
662 let no_overlap = (|| {
663 use std::cmp::Ordering::*;
664 use rustc::hir::RangeEnd::*;
666 let tcx = self.hir.tcx();
668 let test_ty = test.lo.ty;
669 let lo = compare_const_vals(tcx, test.lo, pat.hi, self.hir.param_env, test_ty)?;
670 let hi = compare_const_vals(tcx, test.hi, pat.lo, self.hir.param_env, test_ty)?;
672 match (test.end, pat.end, lo, hi) {
675 (_, Excluded, Equal, _) |
678 (Excluded, _, _, Equal) => Some(true),
683 if let Some(true) = no_overlap {
684 // Testing range does not overlap with pattern range,
685 // so the pattern can be matched only if this test fails.
692 (&TestKind::Range(range), &PatKind::Constant { value }) => {
693 if let Some(false) = self.const_range_contains(range, value) {
694 // `value` is not contained in the testing range,
695 // so `value` can be matched only if this test fails.
702 (&TestKind::Range { .. }, _) => None,
704 (&TestKind::Eq { .. }, _) |
705 (&TestKind::Len { .. }, _) => {
706 // These are all binary tests.
708 // FIXME(#29623) we can be more clever here
709 let pattern_test = self.test(&match_pair);
710 if pattern_test.kind == test.kind {
711 self.candidate_without_match_pair(match_pair_index, candidate);
720 fn candidate_without_match_pair(
722 match_pair_index: usize,
723 candidate: &mut Candidate<'_, 'tcx>,
725 candidate.match_pairs.remove(match_pair_index);
728 fn candidate_after_slice_test<'pat>(&mut self,
729 match_pair_index: usize,
730 candidate: &mut Candidate<'pat, 'tcx>,
731 prefix: &'pat [Pat<'tcx>],
732 opt_slice: Option<&'pat Pat<'tcx>>,
733 suffix: &'pat [Pat<'tcx>]) {
734 let removed_place = candidate.match_pairs.remove(match_pair_index).place;
735 self.prefix_slice_suffix(
736 &mut candidate.match_pairs,
743 fn candidate_after_variant_switch<'pat>(
745 match_pair_index: usize,
746 adt_def: &'tcx ty::AdtDef,
747 variant_index: VariantIdx,
748 subpatterns: &'pat [FieldPat<'tcx>],
749 candidate: &mut Candidate<'pat, 'tcx>,
751 let match_pair = candidate.match_pairs.remove(match_pair_index);
752 let tcx = self.hir.tcx();
754 // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`,
755 // we want to create a set of derived match-patterns like
756 // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`.
757 let elem = ProjectionElem::Downcast(
758 Some(adt_def.variants[variant_index].ident.name), variant_index);
759 let downcast_place = tcx.mk_place_elem(match_pair.place, elem); // `(x as Variant)`
760 let consequent_match_pairs = subpatterns.iter().map(|subpattern| {
761 // e.g., `(x as Variant).0`
763 tcx.mk_place_field(downcast_place.clone(), subpattern.field, subpattern.pattern.ty);
764 // e.g., `(x as Variant).0 @ P1`
765 MatchPair::new(place, &subpattern.pattern)
768 candidate.match_pairs.extend(consequent_match_pairs);
771 fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! {
772 span_bug!(match_pair.pattern.span,
773 "simplifyable pattern found: {:?}",
777 fn const_range_contains(
779 range: PatRange<'tcx>,
780 value: &'tcx ty::Const<'tcx>,
782 use std::cmp::Ordering::*;
784 let tcx = self.hir.tcx();
786 let a = compare_const_vals(tcx, range.lo, value, self.hir.param_env, range.lo.ty)?;
787 let b = compare_const_vals(tcx, value, range.hi, self.hir.param_env, range.lo.ty)?;
789 match (b, range.end) {
791 (Equal, RangeEnd::Included) if a != Greater => Some(true),
796 fn values_not_contained_in_range(
798 range: PatRange<'tcx>,
799 indices: &FxHashMap<&'tcx ty::Const<'tcx>, usize>,
801 for &val in indices.keys() {
802 if self.const_range_contains(range, val)? {
812 pub(super) fn targets(&self) -> usize {
814 TestKind::Eq { .. } | TestKind::Range(_) | TestKind::Len { .. } => {
817 TestKind::Switch { adt_def, .. } => {
818 // While the switch that we generate doesn't test for all
819 // variants, we have a target for each variant and the
820 // otherwise case, and we make sure that all of the cases not
821 // specified have the same block.
822 adt_def.variants.len() + 1
824 TestKind::SwitchInt { switch_ty, ref options, .. } => {
825 if switch_ty.is_bool() {
826 // `bool` is special cased in `perform_test` to always
827 // branch to two blocks.
837 fn is_switch_ty(ty: Ty<'_>) -> bool {
838 ty.is_integral() || ty.is_char() || ty.is_bool()