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