]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir_build/build/matches/test.rs
Merge branch 'master' into feature/incorporate-tracing
[rust.git] / src / librustc_mir_build / build / matches / test.rs
1 // Testing candidates
2 //
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.
7
8 use crate::build::matches::{Candidate, MatchPair, Test, TestKind};
9 use crate::build::Builder;
10 use crate::thir::pattern::compare_const_vals;
11 use crate::thir::*;
12 use rustc_data_structures::fx::FxIndexMap;
13 use rustc_hir::RangeEnd;
14 use rustc_index::bit_set::BitSet;
15 use rustc_middle::mir::*;
16 use rustc_middle::ty::util::IntTypeExt;
17 use rustc_middle::ty::{self, adjustment::PointerCast, Ty};
18 use rustc_span::symbol::sym;
19 use rustc_target::abi::VariantIdx;
20
21 use std::cmp::Ordering;
22
23 impl<'a, 'tcx> Builder<'a, 'tcx> {
24     /// Identifies what test is needed to decide if `match_pair` is applicable.
25     ///
26     /// It is a bug to call this with a simplifiable pattern.
27     pub(super) 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: _ } => Test {
30                 span: match_pair.pattern.span,
31                 kind: TestKind::Switch {
32                     adt_def,
33                     variants: BitSet::new_empty(adt_def.variants.len()),
34                 },
35             },
36
37             PatKind::Constant { .. } if is_switch_ty(match_pair.pattern.ty) => {
38                 // For integers, we use a `SwitchInt` match, which allows
39                 // us to handle more cases.
40                 Test {
41                     span: match_pair.pattern.span,
42                     kind: TestKind::SwitchInt {
43                         switch_ty: match_pair.pattern.ty,
44
45                         // these maps are empty to start; cases are
46                         // added below in add_cases_to_switch
47                         options: Default::default(),
48                     },
49                 }
50             }
51
52             PatKind::Constant { value } => Test {
53                 span: match_pair.pattern.span,
54                 kind: TestKind::Eq { value, ty: match_pair.pattern.ty.clone() },
55             },
56
57             PatKind::Range(range) => {
58                 assert_eq!(range.lo.ty, match_pair.pattern.ty);
59                 assert_eq!(range.hi.ty, match_pair.pattern.ty);
60                 Test { span: match_pair.pattern.span, kind: TestKind::Range(range) }
61             }
62
63             PatKind::Slice { ref prefix, ref slice, ref suffix } => {
64                 let len = prefix.len() + suffix.len();
65                 let op = if slice.is_some() { BinOp::Ge } else { BinOp::Eq };
66                 Test { span: match_pair.pattern.span, kind: TestKind::Len { len: len as u64, op } }
67             }
68
69             PatKind::Or { .. } => bug!("or-patterns should have already been handled"),
70
71             PatKind::AscribeUserType { .. }
72             | PatKind::Array { .. }
73             | PatKind::Wild
74             | PatKind::Binding { .. }
75             | PatKind::Leaf { .. }
76             | PatKind::Deref { .. } => self.error_simplifyable(match_pair),
77         }
78     }
79
80     pub(super) fn add_cases_to_switch<'pat>(
81         &mut self,
82         test_place: &Place<'tcx>,
83         candidate: &Candidate<'pat, 'tcx>,
84         switch_ty: Ty<'tcx>,
85         options: &mut FxIndexMap<&'tcx ty::Const<'tcx>, u128>,
86     ) -> bool {
87         let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
88             Some(match_pair) => match_pair,
89             _ => {
90                 return false;
91             }
92         };
93
94         match *match_pair.pattern.kind {
95             PatKind::Constant { value } => {
96                 options.entry(value).or_insert_with(|| {
97                     value.eval_bits(self.hir.tcx(), self.hir.param_env, switch_ty)
98                 });
99                 true
100             }
101             PatKind::Variant { .. } => {
102                 panic!("you should have called add_variants_to_switch instead!");
103             }
104             PatKind::Range(range) => {
105                 // Check that none of the switch values are in the range.
106                 self.values_not_contained_in_range(range, options).unwrap_or(false)
107             }
108             PatKind::Slice { .. }
109             | PatKind::Array { .. }
110             | PatKind::Wild
111             | PatKind::Or { .. }
112             | PatKind::Binding { .. }
113             | PatKind::AscribeUserType { .. }
114             | PatKind::Leaf { .. }
115             | PatKind::Deref { .. } => {
116                 // don't know how to add these patterns to a switch
117                 false
118             }
119         }
120     }
121
122     pub(super) fn add_variants_to_switch<'pat>(
123         &mut self,
124         test_place: &Place<'tcx>,
125         candidate: &Candidate<'pat, 'tcx>,
126         variants: &mut BitSet<VariantIdx>,
127     ) -> bool {
128         let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
129             Some(match_pair) => match_pair,
130             _ => {
131                 return false;
132             }
133         };
134
135         match *match_pair.pattern.kind {
136             PatKind::Variant { adt_def: _, variant_index, .. } => {
137                 // We have a pattern testing for variant `variant_index`
138                 // set the corresponding index to true
139                 variants.insert(variant_index);
140                 true
141             }
142             _ => {
143                 // don't know how to add these patterns to a switch
144                 false
145             }
146         }
147     }
148
149     pub(super) fn perform_test(
150         &mut self,
151         block: BasicBlock,
152         place: Place<'tcx>,
153         test: &Test<'tcx>,
154         make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
155     ) {
156         debug!(
157             "perform_test({:?}, {:?}: {:?}, {:?})",
158             block,
159             place,
160             place.ty(&self.local_decls, self.hir.tcx()),
161             test
162         );
163
164         let source_info = self.source_info(test.span);
165         match test.kind {
166             TestKind::Switch { adt_def, ref variants } => {
167                 let target_blocks = make_target_blocks(self);
168                 // Variants is a BitVec of indexes into adt_def.variants.
169                 let num_enum_variants = adt_def.variants.len();
170                 let used_variants = variants.count();
171                 debug_assert_eq!(target_blocks.len(), num_enum_variants + 1);
172                 let otherwise_block = *target_blocks.last().unwrap();
173                 let mut targets = Vec::with_capacity(used_variants + 1);
174                 let mut values = Vec::with_capacity(used_variants);
175                 let tcx = self.hir.tcx();
176                 for (idx, discr) in adt_def.discriminants(tcx) {
177                     if variants.contains(idx) {
178                         debug_assert_ne!(
179                             target_blocks[idx.index()],
180                             otherwise_block,
181                             "no canididates for tested discriminant: {:?}",
182                             discr,
183                         );
184                         values.push(discr.val);
185                         targets.push(target_blocks[idx.index()]);
186                     } else {
187                         debug_assert_eq!(
188                             target_blocks[idx.index()],
189                             otherwise_block,
190                             "found canididates for untested discriminant: {:?}",
191                             discr,
192                         );
193                     }
194                 }
195                 targets.push(otherwise_block);
196                 debug!(
197                     "num_enum_variants: {}, tested variants: {:?}, variants: {:?}",
198                     num_enum_variants, values, variants
199                 );
200                 let discr_ty = adt_def.repr.discr_type().to_ty(tcx);
201                 let discr = self.temp(discr_ty, test.span);
202                 self.cfg.push_assign(block, source_info, discr, Rvalue::Discriminant(place));
203                 assert_eq!(values.len() + 1, targets.len());
204                 self.cfg.terminate(
205                     block,
206                     source_info,
207                     TerminatorKind::SwitchInt {
208                         discr: Operand::Move(discr),
209                         switch_ty: discr_ty,
210                         values: From::from(values),
211                         targets,
212                     },
213                 );
214             }
215
216             TestKind::SwitchInt { switch_ty, ref options } => {
217                 let target_blocks = make_target_blocks(self);
218                 let terminator = if switch_ty.kind == ty::Bool {
219                     assert!(!options.is_empty() && options.len() <= 2);
220                     if let [first_bb, second_bb] = *target_blocks {
221                         let (true_bb, false_bb) = match options[0] {
222                             1 => (first_bb, second_bb),
223                             0 => (second_bb, first_bb),
224                             v => span_bug!(test.span, "expected boolean value but got {:?}", v),
225                         };
226                         TerminatorKind::if_(self.hir.tcx(), Operand::Copy(place), true_bb, false_bb)
227                     } else {
228                         bug!("`TestKind::SwitchInt` on `bool` should have two targets")
229                     }
230                 } else {
231                     // The switch may be inexhaustive so we have a catch all block
232                     debug_assert_eq!(options.len() + 1, target_blocks.len());
233                     TerminatorKind::SwitchInt {
234                         discr: Operand::Copy(place),
235                         switch_ty,
236                         values: options.values().copied().collect(),
237                         targets: target_blocks,
238                     }
239                 };
240                 self.cfg.terminate(block, source_info, terminator);
241             }
242
243             TestKind::Eq { value, ty } => {
244                 if !ty.is_scalar() {
245                     // Use `PartialEq::eq` instead of `BinOp::Eq`
246                     // (the binop can only handle primitives)
247                     self.non_scalar_compare(
248                         block,
249                         make_target_blocks,
250                         source_info,
251                         value,
252                         place,
253                         ty,
254                     );
255                 } else {
256                     if let [success, fail] = *make_target_blocks(self) {
257                         assert_eq!(value.ty, ty);
258                         let expect = self.literal_operand(test.span, value);
259                         let val = Operand::Copy(place);
260                         self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
261                     } else {
262                         bug!("`TestKind::Eq` should have two target blocks");
263                     }
264                 }
265             }
266
267             TestKind::Range(PatRange { ref lo, ref hi, ref end }) => {
268                 let lower_bound_success = self.cfg.start_new_block();
269                 let target_blocks = make_target_blocks(self);
270
271                 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
272                 let lo = self.literal_operand(test.span, lo);
273                 let hi = self.literal_operand(test.span, hi);
274                 let val = Operand::Copy(place);
275
276                 if let [success, fail] = *target_blocks {
277                     self.compare(
278                         block,
279                         lower_bound_success,
280                         fail,
281                         source_info,
282                         BinOp::Le,
283                         lo,
284                         val.clone(),
285                     );
286                     let op = match *end {
287                         RangeEnd::Included => BinOp::Le,
288                         RangeEnd::Excluded => BinOp::Lt,
289                     };
290                     self.compare(lower_bound_success, success, fail, source_info, op, val, hi);
291                 } else {
292                     bug!("`TestKind::Range` should have two target blocks");
293                 }
294             }
295
296             TestKind::Len { len, op } => {
297                 let target_blocks = make_target_blocks(self);
298
299                 let usize_ty = self.hir.usize_ty();
300                 let actual = self.temp(usize_ty, test.span);
301
302                 // actual = len(place)
303                 self.cfg.push_assign(block, source_info, actual, Rvalue::Len(place));
304
305                 // expected = <N>
306                 let expected = self.push_usize(block, source_info, len);
307
308                 if let [true_bb, false_bb] = *target_blocks {
309                     // result = actual == expected OR result = actual < expected
310                     // branch based on result
311                     self.compare(
312                         block,
313                         true_bb,
314                         false_bb,
315                         source_info,
316                         op,
317                         Operand::Move(actual),
318                         Operand::Move(expected),
319                     );
320                 } else {
321                     bug!("`TestKind::Len` should have two target blocks");
322                 }
323             }
324         }
325     }
326
327     /// Compare using the provided built-in comparison operator
328     fn compare(
329         &mut self,
330         block: BasicBlock,
331         success_block: BasicBlock,
332         fail_block: BasicBlock,
333         source_info: SourceInfo,
334         op: BinOp,
335         left: Operand<'tcx>,
336         right: Operand<'tcx>,
337     ) {
338         let bool_ty = self.hir.bool_ty();
339         let result = self.temp(bool_ty, source_info.span);
340
341         // result = op(left, right)
342         self.cfg.push_assign(block, source_info, result, Rvalue::BinaryOp(op, left, right));
343
344         // branch based on result
345         self.cfg.terminate(
346             block,
347             source_info,
348             TerminatorKind::if_(self.hir.tcx(), Operand::Move(result), success_block, fail_block),
349         );
350     }
351
352     /// Compare two `&T` values using `<T as std::compare::PartialEq>::eq`
353     fn non_scalar_compare(
354         &mut self,
355         block: BasicBlock,
356         make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
357         source_info: SourceInfo,
358         value: &'tcx ty::Const<'tcx>,
359         place: Place<'tcx>,
360         mut ty: Ty<'tcx>,
361     ) {
362         use rustc_hir::lang_items::EqTraitLangItem;
363
364         let mut expect = self.literal_operand(source_info.span, value);
365         let mut val = Operand::Copy(place);
366
367         // If we're using `b"..."` as a pattern, we need to insert an
368         // unsizing coercion, as the byte string has the type `&[u8; N]`.
369         //
370         // We want to do this even when the scrutinee is a reference to an
371         // array, so we can call `<[u8]>::eq` rather than having to find an
372         // `<[u8; N]>::eq`.
373         let unsize = |ty: Ty<'tcx>| match ty.kind {
374             ty::Ref(region, rty, _) => match rty.kind {
375                 ty::Array(inner_ty, n) => Some((region, inner_ty, n)),
376                 _ => None,
377             },
378             _ => None,
379         };
380         let opt_ref_ty = unsize(ty);
381         let opt_ref_test_ty = unsize(value.ty);
382         match (opt_ref_ty, opt_ref_test_ty) {
383             // nothing to do, neither is an array
384             (None, None) => {}
385             (Some((region, elem_ty, _)), _) | (None, Some((region, elem_ty, _))) => {
386                 let tcx = self.hir.tcx();
387                 // make both a slice
388                 ty = tcx.mk_imm_ref(region, tcx.mk_slice(elem_ty));
389                 if opt_ref_ty.is_some() {
390                     let temp = self.temp(ty, source_info.span);
391                     self.cfg.push_assign(
392                         block,
393                         source_info,
394                         temp,
395                         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), val, ty),
396                     );
397                     val = Operand::Move(temp);
398                 }
399                 if opt_ref_test_ty.is_some() {
400                     let slice = self.temp(ty, source_info.span);
401                     self.cfg.push_assign(
402                         block,
403                         source_info,
404                         slice,
405                         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), expect, ty),
406                     );
407                     expect = Operand::Move(slice);
408                 }
409             }
410         }
411
412         let deref_ty = match ty.kind {
413             ty::Ref(_, deref_ty, _) => deref_ty,
414             _ => bug!("non_scalar_compare called on non-reference type: {}", ty),
415         };
416
417         let eq_def_id = self.hir.tcx().require_lang_item(EqTraitLangItem, None);
418         let method = self.hir.trait_method(eq_def_id, sym::eq, deref_ty, &[deref_ty.into()]);
419
420         let bool_ty = self.hir.bool_ty();
421         let eq_result = self.temp(bool_ty, source_info.span);
422         let eq_block = self.cfg.start_new_block();
423         let cleanup = self.diverge_cleanup();
424         self.cfg.terminate(
425             block,
426             source_info,
427             TerminatorKind::Call {
428                 func: Operand::Constant(box Constant {
429                     span: source_info.span,
430
431                     // FIXME(#54571): This constant comes from user input (a
432                     // constant in a pattern).  Are there forms where users can add
433                     // type annotations here?  For example, an associated constant?
434                     // Need to experiment.
435                     user_ty: None,
436
437                     literal: method,
438                 }),
439                 args: vec![val, expect],
440                 destination: Some((eq_result, eq_block)),
441                 cleanup: Some(cleanup),
442                 from_hir_call: false,
443                 fn_span: source_info.span,
444             },
445         );
446
447         if let [success_block, fail_block] = *make_target_blocks(self) {
448             // check the result
449             self.cfg.terminate(
450                 eq_block,
451                 source_info,
452                 TerminatorKind::if_(
453                     self.hir.tcx(),
454                     Operand::Move(eq_result),
455                     success_block,
456                     fail_block,
457                 ),
458             );
459         } else {
460             bug!("`TestKind::Eq` should have two target blocks")
461         }
462     }
463
464     /// Given that we are performing `test` against `test_place`, this job
465     /// sorts out what the status of `candidate` will be after the test. See
466     /// `test_candidates` for the usage of this function. The returned index is
467     /// the index that this candidate should be placed in the
468     /// `target_candidates` vec. The candidate may be modified to update its
469     /// `match_pairs`.
470     ///
471     /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
472     /// a variant test, then we would modify the candidate to be `(x as
473     /// Option).0 @ P0` and return the index corresponding to the variant
474     /// `Some`.
475     ///
476     /// However, in some cases, the test may just not be relevant to candidate.
477     /// For example, suppose we are testing whether `foo.x == 22`, but in one
478     /// match arm we have `Foo { x: _, ... }`... in that case, the test for
479     /// what value `x` has has no particular relevance to this candidate. In
480     /// such cases, this function just returns None without doing anything.
481     /// This is used by the overall `match_candidates` algorithm to structure
482     /// the match as a whole. See `match_candidates` for more details.
483     ///
484     /// FIXME(#29623). In some cases, we have some tricky choices to make.  for
485     /// example, if we are testing that `x == 22`, but the candidate is `x @
486     /// 13..55`, what should we do? In the event that the test is true, we know
487     /// that the candidate applies, but in the event of false, we don't know
488     /// that it *doesn't* apply. For now, we return false, indicate that the
489     /// test does not apply to this candidate, but it might be we can get
490     /// tighter match code if we do something a bit different.
491     pub(super) fn sort_candidate<'pat>(
492         &mut self,
493         test_place: &Place<'tcx>,
494         test: &Test<'tcx>,
495         candidate: &mut Candidate<'pat, 'tcx>,
496     ) -> Option<usize> {
497         // Find the match_pair for this place (if any). At present,
498         // afaik, there can be at most one. (In the future, if we
499         // adopted a more general `@` operator, there might be more
500         // than one, but it'd be very unusual to have two sides that
501         // both require tests; you'd expect one side to be simplified
502         // away.)
503         let (match_pair_index, match_pair) =
504             candidate.match_pairs.iter().enumerate().find(|&(_, mp)| mp.place == *test_place)?;
505
506         match (&test.kind, &*match_pair.pattern.kind) {
507             // If we are performing a variant switch, then this
508             // informs variant patterns, but nothing else.
509             (
510                 &TestKind::Switch { adt_def: tested_adt_def, .. },
511                 &PatKind::Variant { adt_def, variant_index, ref subpatterns, .. },
512             ) => {
513                 assert_eq!(adt_def, tested_adt_def);
514                 self.candidate_after_variant_switch(
515                     match_pair_index,
516                     adt_def,
517                     variant_index,
518                     subpatterns,
519                     candidate,
520                 );
521                 Some(variant_index.as_usize())
522             }
523
524             (&TestKind::Switch { .. }, _) => None,
525
526             // If we are performing a switch over integers, then this informs integer
527             // equality, but nothing else.
528             //
529             // FIXME(#29623) we could use PatKind::Range to rule
530             // things out here, in some cases.
531             (
532                 &TestKind::SwitchInt { switch_ty: _, ref options },
533                 &PatKind::Constant { ref value },
534             ) if is_switch_ty(match_pair.pattern.ty) => {
535                 let index = options.get_index_of(value).unwrap();
536                 self.candidate_without_match_pair(match_pair_index, candidate);
537                 Some(index)
538             }
539
540             (
541                 &TestKind::SwitchInt { switch_ty: _, ref options },
542                 &PatKind::Range(range),
543             ) => {
544                 let not_contained =
545                     self.values_not_contained_in_range(range, options).unwrap_or(false);
546
547                 if not_contained {
548                     // No switch values are contained in the pattern range,
549                     // so the pattern can be matched only if this test fails.
550                     let otherwise = options.len();
551                     Some(otherwise)
552                 } else {
553                     None
554                 }
555             }
556
557             (&TestKind::SwitchInt { .. }, _) => None,
558
559             (
560                 &TestKind::Len { len: test_len, op: BinOp::Eq },
561                 &PatKind::Slice { ref prefix, ref slice, ref suffix },
562             ) => {
563                 let pat_len = (prefix.len() + suffix.len()) as u64;
564                 match (test_len.cmp(&pat_len), slice) {
565                     (Ordering::Equal, &None) => {
566                         // on true, min_len = len = $actual_length,
567                         // on false, len != $actual_length
568                         self.candidate_after_slice_test(
569                             match_pair_index,
570                             candidate,
571                             prefix,
572                             slice.as_ref(),
573                             suffix,
574                         );
575                         Some(0)
576                     }
577                     (Ordering::Less, _) => {
578                         // test_len < pat_len. If $actual_len = test_len,
579                         // then $actual_len < pat_len and we don't have
580                         // enough elements.
581                         Some(1)
582                     }
583                     (Ordering::Equal | Ordering::Greater, &Some(_)) => {
584                         // This can match both if $actual_len = test_len >= pat_len,
585                         // and if $actual_len > test_len. We can't advance.
586                         None
587                     }
588                     (Ordering::Greater, &None) => {
589                         // test_len != pat_len, so if $actual_len = test_len, then
590                         // $actual_len != pat_len.
591                         Some(1)
592                     }
593                 }
594             }
595
596             (
597                 &TestKind::Len { len: test_len, op: BinOp::Ge },
598                 &PatKind::Slice { ref prefix, ref slice, ref suffix },
599             ) => {
600                 // the test is `$actual_len >= test_len`
601                 let pat_len = (prefix.len() + suffix.len()) as u64;
602                 match (test_len.cmp(&pat_len), slice) {
603                     (Ordering::Equal, &Some(_)) => {
604                         // $actual_len >= test_len = pat_len,
605                         // so we can match.
606                         self.candidate_after_slice_test(
607                             match_pair_index,
608                             candidate,
609                             prefix,
610                             slice.as_ref(),
611                             suffix,
612                         );
613                         Some(0)
614                     }
615                     (Ordering::Less, _) | (Ordering::Equal, &None) => {
616                         // test_len <= pat_len. If $actual_len < test_len,
617                         // then it is also < pat_len, so the test passing is
618                         // necessary (but insufficient).
619                         Some(0)
620                     }
621                     (Ordering::Greater, &None) => {
622                         // test_len > pat_len. If $actual_len >= test_len > pat_len,
623                         // then we know we won't have a match.
624                         Some(1)
625                     }
626                     (Ordering::Greater, &Some(_)) => {
627                         // test_len < pat_len, and is therefore less
628                         // strict. This can still go both ways.
629                         None
630                     }
631                 }
632             }
633
634             (&TestKind::Range(test), &PatKind::Range(pat)) => {
635                 if test == pat {
636                     self.candidate_without_match_pair(match_pair_index, candidate);
637                     return Some(0);
638                 }
639
640                 let no_overlap = (|| {
641                     use rustc_hir::RangeEnd::*;
642                     use std::cmp::Ordering::*;
643
644                     let tcx = self.hir.tcx();
645
646                     let test_ty = test.lo.ty;
647                     let lo = compare_const_vals(tcx, test.lo, pat.hi, self.hir.param_env, test_ty)?;
648                     let hi = compare_const_vals(tcx, test.hi, pat.lo, self.hir.param_env, test_ty)?;
649
650                     match (test.end, pat.end, lo, hi) {
651                         // pat < test
652                         (_, _, Greater, _) |
653                         (_, Excluded, Equal, _) |
654                         // pat > test
655                         (_, _, _, Less) |
656                         (Excluded, _, _, Equal) => Some(true),
657                         _ => Some(false),
658                     }
659                 })();
660
661                 if let Some(true) = no_overlap {
662                     // Testing range does not overlap with pattern range,
663                     // so the pattern can be matched only if this test fails.
664                     Some(1)
665                 } else {
666                     None
667                 }
668             }
669
670             (&TestKind::Range(range), &PatKind::Constant { value }) => {
671                 if let Some(false) = self.const_range_contains(range, value) {
672                     // `value` is not contained in the testing range,
673                     // so `value` can be matched only if this test fails.
674                     Some(1)
675                 } else {
676                     None
677                 }
678             }
679
680             (&TestKind::Range { .. }, _) => None,
681
682             (&TestKind::Eq { .. } | &TestKind::Len { .. }, _) => {
683                 // These are all binary tests.
684                 //
685                 // FIXME(#29623) we can be more clever here
686                 let pattern_test = self.test(&match_pair);
687                 if pattern_test.kind == test.kind {
688                     self.candidate_without_match_pair(match_pair_index, candidate);
689                     Some(0)
690                 } else {
691                     None
692                 }
693             }
694         }
695     }
696
697     fn candidate_without_match_pair(
698         &mut self,
699         match_pair_index: usize,
700         candidate: &mut Candidate<'_, 'tcx>,
701     ) {
702         candidate.match_pairs.remove(match_pair_index);
703     }
704
705     fn candidate_after_slice_test<'pat>(
706         &mut self,
707         match_pair_index: usize,
708         candidate: &mut Candidate<'pat, 'tcx>,
709         prefix: &'pat [Pat<'tcx>],
710         opt_slice: Option<&'pat Pat<'tcx>>,
711         suffix: &'pat [Pat<'tcx>],
712     ) {
713         let removed_place = candidate.match_pairs.remove(match_pair_index).place;
714         self.prefix_slice_suffix(
715             &mut candidate.match_pairs,
716             &removed_place,
717             prefix,
718             opt_slice,
719             suffix,
720         );
721     }
722
723     fn candidate_after_variant_switch<'pat>(
724         &mut self,
725         match_pair_index: usize,
726         adt_def: &'tcx ty::AdtDef,
727         variant_index: VariantIdx,
728         subpatterns: &'pat [FieldPat<'tcx>],
729         candidate: &mut Candidate<'pat, 'tcx>,
730     ) {
731         let match_pair = candidate.match_pairs.remove(match_pair_index);
732         let tcx = self.hir.tcx();
733
734         // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`,
735         // we want to create a set of derived match-patterns like
736         // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`.
737         let elem = ProjectionElem::Downcast(
738             Some(adt_def.variants[variant_index].ident.name),
739             variant_index,
740         );
741         let downcast_place = tcx.mk_place_elem(match_pair.place, elem); // `(x as Variant)`
742         let consequent_match_pairs = subpatterns.iter().map(|subpattern| {
743             // e.g., `(x as Variant).0`
744             let place = tcx.mk_place_field(downcast_place, subpattern.field, subpattern.pattern.ty);
745             // e.g., `(x as Variant).0 @ P1`
746             MatchPair::new(place, &subpattern.pattern)
747         });
748
749         candidate.match_pairs.extend(consequent_match_pairs);
750     }
751
752     fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! {
753         span_bug!(match_pair.pattern.span, "simplifyable pattern found: {:?}", match_pair.pattern)
754     }
755
756     fn const_range_contains(
757         &self,
758         range: PatRange<'tcx>,
759         value: &'tcx ty::Const<'tcx>,
760     ) -> Option<bool> {
761         use std::cmp::Ordering::*;
762
763         let tcx = self.hir.tcx();
764
765         let a = compare_const_vals(tcx, range.lo, value, self.hir.param_env, range.lo.ty)?;
766         let b = compare_const_vals(tcx, value, range.hi, self.hir.param_env, range.lo.ty)?;
767
768         match (b, range.end) {
769             (Less, _) | (Equal, RangeEnd::Included) if a != Greater => Some(true),
770             _ => Some(false),
771         }
772     }
773
774     fn values_not_contained_in_range(
775         &self,
776         range: PatRange<'tcx>,
777         options: &FxIndexMap<&'tcx ty::Const<'tcx>, u128>,
778     ) -> Option<bool> {
779         for &val in options.keys() {
780             if self.const_range_contains(range, val)? {
781                 return Some(false);
782             }
783         }
784
785         Some(true)
786     }
787 }
788
789 impl Test<'_> {
790     pub(super) fn targets(&self) -> usize {
791         match self.kind {
792             TestKind::Eq { .. } | TestKind::Range(_) | TestKind::Len { .. } => 2,
793             TestKind::Switch { adt_def, .. } => {
794                 // While the switch that we generate doesn't test for all
795                 // variants, we have a target for each variant and the
796                 // otherwise case, and we make sure that all of the cases not
797                 // specified have the same block.
798                 adt_def.variants.len() + 1
799             }
800             TestKind::SwitchInt { switch_ty, ref options, .. } => {
801                 if switch_ty.is_bool() {
802                     // `bool` is special cased in `perform_test` to always
803                     // branch to two blocks.
804                     2
805                 } else {
806                     options.len() + 1
807                 }
808             }
809         }
810     }
811 }
812
813 fn is_switch_ty(ty: Ty<'_>) -> bool {
814     ty.is_integral() || ty.is_char() || ty.is_bool()
815 }