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 PatternKind::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 PatternKind::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 PatternKind::Constant { value } => {
57 span: match_pair.pattern.span,
60 ty: match_pair.pattern.ty.clone()
65 PatternKind::Range(range) => {
66 assert!(range.ty == match_pair.pattern.ty);
68 span: match_pair.pattern.span,
69 kind: TestKind::Range(range),
73 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
74 let len = prefix.len() + suffix.len();
75 let op = if slice.is_some() {
81 span: match_pair.pattern.span,
82 kind: TestKind::Len { len: len as u64, op: op },
86 PatternKind::AscribeUserType { .. } |
87 PatternKind::Array { .. } |
89 PatternKind::Binding { .. } |
90 PatternKind::Leaf { .. } |
91 PatternKind::Deref { .. } => {
92 self.error_simplifyable(match_pair)
97 pub fn add_cases_to_switch<'pat>(&mut self,
98 test_place: &Place<'tcx>,
99 candidate: &Candidate<'pat, 'tcx>,
101 options: &mut Vec<u128>,
102 indices: &mut FxHashMap<&'tcx ty::Const<'tcx>, usize>)
105 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
106 Some(match_pair) => match_pair,
107 _ => { return false; }
110 match *match_pair.pattern.kind {
111 PatternKind::Constant { value } => {
114 options.push(value.eval_bits(
115 self.hir.tcx(), self.hir.param_env, switch_ty,
121 PatternKind::Variant { .. } => {
122 panic!("you should have called add_variants_to_switch instead!");
124 PatternKind::Range(range) => {
125 // Check that none of the switch values are in the range.
126 self.values_not_contained_in_range(range, indices)
129 PatternKind::Slice { .. } |
130 PatternKind::Array { .. } |
132 PatternKind::Binding { .. } |
133 PatternKind::AscribeUserType { .. } |
134 PatternKind::Leaf { .. } |
135 PatternKind::Deref { .. } => {
136 // don't know how to add these patterns to a switch
142 pub fn add_variants_to_switch<'pat>(&mut self,
143 test_place: &Place<'tcx>,
144 candidate: &Candidate<'pat, 'tcx>,
145 variants: &mut BitSet<VariantIdx>)
148 let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
149 Some(match_pair) => match_pair,
150 _ => { return false; }
153 match *match_pair.pattern.kind {
154 PatternKind::Variant { adt_def: _ , variant_index, .. } => {
155 // We have a pattern testing for variant `variant_index`
156 // set the corresponding index to true
157 variants.insert(variant_index);
161 // don't know how to add these patterns to a switch
172 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
174 debug!("perform_test({:?}, {:?}: {:?}, {:?})",
177 place.ty(&self.local_decls, self.hir.tcx()),
180 let source_info = self.source_info(test.span);
182 TestKind::Switch { adt_def, ref variants } => {
183 let target_blocks = make_target_blocks(self);
184 // Variants is a BitVec of indexes into adt_def.variants.
185 let num_enum_variants = adt_def.variants.len();
186 let used_variants = variants.count();
187 debug_assert_eq!(target_blocks.len(), num_enum_variants + 1);
188 let otherwise_block = *target_blocks.last().unwrap();
189 let mut targets = Vec::with_capacity(used_variants + 1);
190 let mut values = Vec::with_capacity(used_variants);
191 let tcx = self.hir.tcx();
192 for (idx, discr) in adt_def.discriminants(tcx) {
193 if variants.contains(idx) {
195 target_blocks[idx.index()],
197 "no canididates for tested discriminant: {:?}",
200 values.push(discr.val);
201 targets.push(target_blocks[idx.index()]);
204 target_blocks[idx.index()],
206 "found canididates for untested discriminant: {:?}",
211 targets.push(otherwise_block);
212 debug!("num_enum_variants: {}, tested variants: {:?}, variants: {:?}",
213 num_enum_variants, values, variants);
214 let discr_ty = adt_def.repr.discr_type().to_ty(tcx);
215 let discr = self.temp(discr_ty, test.span);
216 self.cfg.push_assign(block, source_info, &discr,
217 Rvalue::Discriminant(place.clone()));
218 assert_eq!(values.len() + 1, targets.len());
219 self.cfg.terminate(block, source_info, TerminatorKind::SwitchInt {
220 discr: Operand::Move(discr),
222 values: From::from(values),
227 TestKind::SwitchInt { switch_ty, ref options, indices: _ } => {
228 let target_blocks = make_target_blocks(self);
229 let terminator = if switch_ty.sty == ty::Bool {
230 assert!(options.len() > 0 && options.len() <= 2);
231 if let [first_bb, second_bb] = *target_blocks {
232 let (true_bb, false_bb) = match options[0] {
233 1 => (first_bb, second_bb),
234 0 => (second_bb, first_bb),
235 v => span_bug!(test.span, "expected boolean value but got {:?}", v)
239 Operand::Copy(place.clone()),
244 bug!("`TestKind::SwitchInt` on `bool` should have two targets")
247 // The switch may be inexhaustive so we have a catch all block
248 debug_assert_eq!(options.len() + 1, target_blocks.len());
249 TerminatorKind::SwitchInt {
250 discr: Operand::Copy(place.clone()),
252 values: options.clone().into(),
253 targets: target_blocks,
256 self.cfg.terminate(block, source_info, terminator);
259 TestKind::Eq { value, ty } => {
261 // Use `PartialEq::eq` instead of `BinOp::Eq`
262 // (the binop can only handle primitives)
263 self.non_scalar_compare(
272 if let [success, fail] = *make_target_blocks(self) {
273 let val = Operand::Copy(place.clone());
274 let expect = self.literal_operand(test.span, ty, value);
275 self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
277 bug!("`TestKind::Eq` should have two target blocks");
282 TestKind::Range(PatternRange { ref lo, ref hi, ty, ref end }) => {
283 let lower_bound_success = self.cfg.start_new_block();
284 let target_blocks = make_target_blocks(self);
286 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
287 let lo = self.literal_operand(test.span, ty, lo);
288 let hi = self.literal_operand(test.span, ty, hi);
289 let val = Operand::Copy(place.clone());
291 if let [success, fail] = *target_blocks {
301 let op = match *end {
302 RangeEnd::Included => BinOp::Le,
303 RangeEnd::Excluded => BinOp::Lt,
305 self.compare(lower_bound_success, success, fail, source_info, op, val, hi);
307 bug!("`TestKind::Range` should have two target blocks");
311 TestKind::Len { len, op } => {
312 let target_blocks = make_target_blocks(self);
314 let usize_ty = self.hir.usize_ty();
315 let actual = self.temp(usize_ty, test.span);
317 // actual = len(place)
318 self.cfg.push_assign(block, source_info,
319 &actual, Rvalue::Len(place.clone()));
322 let expected = self.push_usize(block, source_info, len);
324 if let [true_bb, false_bb] = *target_blocks {
325 // result = actual == expected OR result = actual < expected
326 // branch based on result
333 Operand::Move(actual),
334 Operand::Move(expected),
337 bug!("`TestKind::Len` should have two target blocks");
343 /// Compare using the provided built-in comparison operator
347 success_block: BasicBlock,
348 fail_block: BasicBlock,
349 source_info: SourceInfo,
352 right: Operand<'tcx>,
354 let bool_ty = self.hir.bool_ty();
355 let result = self.temp(bool_ty, source_info.span);
357 // result = op(left, right)
358 self.cfg.push_assign(
362 Rvalue::BinaryOp(op, left, right),
365 // branch based on result
371 Operand::Move(result),
378 /// Compare two `&T` values using `<T as std::compare::PartialEq>::eq`
379 fn non_scalar_compare(
382 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
383 source_info: SourceInfo,
384 value: &'tcx ty::Const<'tcx>,
388 use rustc::middle::lang_items::EqTraitLangItem;
390 let mut expect = self.literal_operand(source_info.span, value.ty, value);
391 let mut val = Operand::Copy(place.clone());
393 // If we're using `b"..."` as a pattern, we need to insert an
394 // unsizing coercion, as the byte string has the type `&[u8; N]`.
396 // We want to do this even when the scrutinee is a reference to an
397 // array, so we can call `<[u8]>::eq` rather than having to find an
399 let unsize = |ty: Ty<'tcx>| match ty.sty {
400 ty::Ref(region, rty, _) => match rty.sty {
401 ty::Array(inner_ty, n) => Some((region, inner_ty, n)),
406 let opt_ref_ty = unsize(ty);
407 let opt_ref_test_ty = unsize(value.ty);
408 match (opt_ref_ty, opt_ref_test_ty) {
409 // nothing to do, neither is an array
411 (Some((region, elem_ty, _)), _) |
412 (None, Some((region, elem_ty, _))) => {
413 let tcx = self.hir.tcx();
415 ty = tcx.mk_imm_ref(region, tcx.mk_slice(elem_ty));
416 if opt_ref_ty.is_some() {
417 let temp = self.temp(ty, source_info.span);
418 self.cfg.push_assign(
419 block, source_info, &temp, Rvalue::Cast(
420 CastKind::Pointer(PointerCast::Unsize), val, ty
423 val = Operand::Move(temp);
425 if opt_ref_test_ty.is_some() {
426 let slice = self.temp(ty, source_info.span);
427 self.cfg.push_assign(
428 block, source_info, &slice, Rvalue::Cast(
429 CastKind::Pointer(PointerCast::Unsize), expect, ty
432 expect = Operand::Move(slice);
437 let deref_ty = match ty.sty {
438 ty::Ref(_, deref_ty, _) => deref_ty,
439 _ => bug!("non_scalar_compare called on non-reference type: {}", ty),
442 let eq_def_id = self.hir.tcx().require_lang_item(EqTraitLangItem);
443 let (mty, method) = self.hir.trait_method(eq_def_id, sym::eq, deref_ty, &[deref_ty.into()]);
445 let bool_ty = self.hir.bool_ty();
446 let eq_result = self.temp(bool_ty, source_info.span);
447 let eq_block = self.cfg.start_new_block();
448 let cleanup = self.diverge_cleanup();
449 self.cfg.terminate(block, source_info, TerminatorKind::Call {
450 func: Operand::Constant(box Constant {
451 span: source_info.span,
454 // FIXME(#54571): This constant comes from user input (a
455 // constant in a pattern). Are there forms where users can add
456 // type annotations here? For example, an associated constant?
457 // Need to experiment.
462 args: vec![val, expect],
463 destination: Some((eq_result.clone(), eq_block)),
464 cleanup: Some(cleanup),
465 from_hir_call: false,
468 if let [success_block, fail_block] = *make_target_blocks(self) {
475 Operand::Move(eq_result),
481 bug!("`TestKind::Eq` should have two target blocks")
485 /// Given that we are performing `test` against `test_place`, this job
486 /// sorts out what the status of `candidate` will be after the test. See
487 /// `test_candidates` for the usage of this function. The returned index is
488 /// the index that this candiate should be placed in the
489 /// `target_candidates` vec. The candidate may be modified to update its
492 /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
493 /// a variant test, then we would modify the candidate to be `(x as
494 /// Option).0 @ P0` and return the index corresponding to the variant
497 /// However, in some cases, the test may just not be relevant to candidate.
498 /// For example, suppose we are testing whether `foo.x == 22`, but in one
499 /// match arm we have `Foo { x: _, ... }`... in that case, the test for
500 /// what value `x` has has no particular relevance to this candidate. In
501 /// such cases, this function just returns None without doing anything.
502 /// This is used by the overall `match_candidates` algorithm to structure
503 /// the match as a whole. See `match_candidates` for more details.
505 /// FIXME(#29623). In some cases, we have some tricky choices to make. for
506 /// example, if we are testing that `x == 22`, but the candidate is `x @
507 /// 13..55`, what should we do? In the event that the test is true, we know
508 /// that the candidate applies, but in the event of false, we don't know
509 /// that it *doesn't* apply. For now, we return false, indicate that the
510 /// test does not apply to this candidate, but it might be we can get
511 /// tighter match code if we do something a bit different.
512 pub fn sort_candidate<'pat>(
514 test_place: &Place<'tcx>,
516 candidate: &mut Candidate<'pat, 'tcx>,
518 // Find the match_pair for this place (if any). At present,
519 // afaik, there can be at most one. (In the future, if we
520 // adopted a more general `@` operator, there might be more
521 // than one, but it'd be very unusual to have two sides that
522 // both require tests; you'd expect one side to be simplified
524 let (match_pair_index, match_pair) = candidate.match_pairs
527 .find(|&(_, mp)| mp.place == *test_place)?;
529 match (&test.kind, &*match_pair.pattern.kind) {
530 // If we are performing a variant switch, then this
531 // informs variant patterns, but nothing else.
532 (&TestKind::Switch { adt_def: tested_adt_def, .. },
533 &PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. }) => {
534 assert_eq!(adt_def, tested_adt_def);
535 self.candidate_after_variant_switch(match_pair_index,
540 Some(variant_index.as_usize())
543 (&TestKind::Switch { .. }, _) => None,
545 // If we are performing a switch over integers, then this informs integer
546 // equality, but nothing else.
548 // FIXME(#29623) we could use PatternKind::Range to rule
549 // things out here, in some cases.
550 (&TestKind::SwitchInt { switch_ty: _, options: _, ref indices },
551 &PatternKind::Constant { ref value })
552 if is_switch_ty(match_pair.pattern.ty) => {
553 let index = indices[value];
554 self.candidate_without_match_pair(match_pair_index, candidate);
558 (&TestKind::SwitchInt { switch_ty: _, ref options, ref indices },
559 &PatternKind::Range(range)) => {
560 let not_contained = self
561 .values_not_contained_in_range(range, indices)
565 // No switch values are contained in the pattern range,
566 // so the pattern can be matched only if this test fails.
567 let otherwise = options.len();
574 (&TestKind::SwitchInt { .. }, _) => None,
576 (&TestKind::Len { len: test_len, op: BinOp::Eq },
577 &PatternKind::Slice { ref prefix, ref slice, ref suffix }) => {
578 let pat_len = (prefix.len() + suffix.len()) as u64;
579 match (test_len.cmp(&pat_len), slice) {
580 (Ordering::Equal, &None) => {
581 // on true, min_len = len = $actual_length,
582 // on false, len != $actual_length
583 self.candidate_after_slice_test(match_pair_index,
590 (Ordering::Less, _) => {
591 // test_len < pat_len. If $actual_len = test_len,
592 // then $actual_len < pat_len and we don't have
596 (Ordering::Equal, &Some(_)) | (Ordering::Greater, &Some(_)) => {
597 // This can match both if $actual_len = test_len >= pat_len,
598 // and if $actual_len > test_len. We can't advance.
601 (Ordering::Greater, &None) => {
602 // test_len != pat_len, so if $actual_len = test_len, then
603 // $actual_len != pat_len.
609 (&TestKind::Len { len: test_len, op: BinOp::Ge },
610 &PatternKind::Slice { ref prefix, ref slice, ref suffix }) => {
611 // the test is `$actual_len >= test_len`
612 let pat_len = (prefix.len() + suffix.len()) as u64;
613 match (test_len.cmp(&pat_len), slice) {
614 (Ordering::Equal, &Some(_)) => {
615 // $actual_len >= test_len = pat_len,
617 self.candidate_after_slice_test(match_pair_index,
624 (Ordering::Less, _) | (Ordering::Equal, &None) => {
625 // test_len <= pat_len. If $actual_len < test_len,
626 // then it is also < pat_len, so the test passing is
627 // necessary (but insufficient).
630 (Ordering::Greater, &None) => {
631 // test_len > pat_len. If $actual_len >= test_len > pat_len,
632 // then we know we won't have a match.
635 (Ordering::Greater, &Some(_)) => {
636 // test_len < pat_len, and is therefore less
637 // strict. This can still go both ways.
643 (&TestKind::Range(test),
644 &PatternKind::Range(pat)) => {
646 self.candidate_without_match_pair(
653 let no_overlap = (|| {
654 use std::cmp::Ordering::*;
655 use rustc::hir::RangeEnd::*;
657 let tcx = self.hir.tcx();
659 let lo = compare_const_vals(tcx, test.lo, pat.hi, self.hir.param_env, test.ty)?;
660 let hi = compare_const_vals(tcx, test.hi, pat.lo, self.hir.param_env, test.ty)?;
662 match (test.end, pat.end, lo, hi) {
665 (_, Excluded, Equal, _) |
668 (Excluded, _, _, Equal) => Some(true),
673 if no_overlap == Some(true) {
674 // Testing range does not overlap with pattern range,
675 // so the pattern can be matched only if this test fails.
682 (&TestKind::Range(range), &PatternKind::Constant { value }) => {
683 if self.const_range_contains(range, value) == Some(false) {
684 // `value` is not contained in the testing range,
685 // so `value` can be matched only if this test fails.
692 (&TestKind::Range { .. }, _) => None,
694 (&TestKind::Eq { .. }, _) |
695 (&TestKind::Len { .. }, _) => {
696 // These are all binary tests.
698 // FIXME(#29623) we can be more clever here
699 let pattern_test = self.test(&match_pair);
700 if pattern_test.kind == test.kind {
701 self.candidate_without_match_pair(match_pair_index, candidate);
710 fn candidate_without_match_pair(
712 match_pair_index: usize,
713 candidate: &mut Candidate<'_, 'tcx>,
715 candidate.match_pairs.remove(match_pair_index);
718 fn candidate_after_slice_test<'pat>(&mut self,
719 match_pair_index: usize,
720 candidate: &mut Candidate<'pat, 'tcx>,
721 prefix: &'pat [Pattern<'tcx>],
722 opt_slice: Option<&'pat Pattern<'tcx>>,
723 suffix: &'pat [Pattern<'tcx>]) {
724 let removed_place = candidate.match_pairs.remove(match_pair_index).place;
725 self.prefix_slice_suffix(
726 &mut candidate.match_pairs,
733 fn candidate_after_variant_switch<'pat>(
735 match_pair_index: usize,
736 adt_def: &'tcx ty::AdtDef,
737 variant_index: VariantIdx,
738 subpatterns: &'pat [FieldPattern<'tcx>],
739 candidate: &mut Candidate<'pat, 'tcx>,
741 let match_pair = candidate.match_pairs.remove(match_pair_index);
743 // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`,
744 // we want to create a set of derived match-patterns like
745 // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`.
746 let elem = ProjectionElem::Downcast(
747 Some(adt_def.variants[variant_index].ident.name), variant_index);
748 let downcast_place = match_pair.place.elem(elem); // `(x as Variant)`
749 let consequent_match_pairs =
752 // e.g., `(x as Variant).0`
753 let place = downcast_place.clone().field(subpattern.field,
754 subpattern.pattern.ty);
755 // e.g., `(x as Variant).0 @ P1`
756 MatchPair::new(place, &subpattern.pattern)
759 candidate.match_pairs.extend(consequent_match_pairs);
762 fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! {
763 span_bug!(match_pair.pattern.span,
764 "simplifyable pattern found: {:?}",
768 fn const_range_contains(
770 range: PatternRange<'tcx>,
771 value: &'tcx ty::Const<'tcx>,
773 use std::cmp::Ordering::*;
775 let tcx = self.hir.tcx();
777 let a = compare_const_vals(tcx, range.lo, value, self.hir.param_env, range.ty)?;
778 let b = compare_const_vals(tcx, value, range.hi, self.hir.param_env, range.ty)?;
780 match (b, range.end) {
782 (Equal, RangeEnd::Included) if a != Greater => Some(true),
787 fn values_not_contained_in_range(
789 range: PatternRange<'tcx>,
790 indices: &FxHashMap<&'tcx ty::Const<'tcx>, usize>,
792 for &val in indices.keys() {
793 if self.const_range_contains(range, val)? {
803 pub(super) fn targets(&self) -> usize {
805 TestKind::Eq { .. } | TestKind::Range(_) | TestKind::Len { .. } => {
808 TestKind::Switch { adt_def, .. } => {
809 // While the switch that we generate doesn't test for all
810 // variants, we have a target for each variant and the
811 // otherwise case, and we make sure that all of the cases not
812 // specified have the same block.
813 adt_def.variants.len() + 1
815 TestKind::SwitchInt { switch_ty, ref options, .. } => {
816 if switch_ty.is_bool() {
817 // `bool` is special cased in `perform_test` to always
818 // branch to two blocks.
828 fn is_switch_ty(ty: Ty<'_>) -> bool {
829 ty.is_integral() || ty.is_char() || ty.is_bool()