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