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