]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/matches/test.rs
Remove leftover AwaitOrigin
[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                 let switch_ty = ty::ParamEnv::empty().and(switch_ty);
113                 indices.entry(value)
114                        .or_insert_with(|| {
115                            options.push(value.unwrap_bits(self.hir.tcx(), switch_ty));
116                            options.len() - 1
117                        });
118                 true
119             }
120             PatternKind::Variant { .. } => {
121                 panic!("you should have called add_variants_to_switch instead!");
122             }
123             PatternKind::Range(range) => {
124                 // Check that none of the switch values are in the range.
125                 self.values_not_contained_in_range(range, indices)
126                     .unwrap_or(false)
127             }
128             PatternKind::Slice { .. } |
129             PatternKind::Array { .. } |
130             PatternKind::Wild |
131             PatternKind::Binding { .. } |
132             PatternKind::AscribeUserType { .. } |
133             PatternKind::Leaf { .. } |
134             PatternKind::Deref { .. } => {
135                 // don't know how to add these patterns to a switch
136                 false
137             }
138         }
139     }
140
141     pub fn add_variants_to_switch<'pat>(&mut self,
142                                         test_place: &Place<'tcx>,
143                                         candidate: &Candidate<'pat, 'tcx>,
144                                         variants: &mut BitSet<VariantIdx>)
145                                         -> bool
146     {
147         let match_pair = match candidate.match_pairs.iter().find(|mp| mp.place == *test_place) {
148             Some(match_pair) => match_pair,
149             _ => { return false; }
150         };
151
152         match *match_pair.pattern.kind {
153             PatternKind::Variant { adt_def: _ , variant_index,  .. } => {
154                 // We have a pattern testing for variant `variant_index`
155                 // set the corresponding index to true
156                 variants.insert(variant_index);
157                 true
158             }
159             _ => {
160                 // don't know how to add these patterns to a switch
161                 false
162             }
163         }
164     }
165
166     pub fn perform_test(
167         &mut self,
168         block: BasicBlock,
169         place: &Place<'tcx>,
170         test: &Test<'tcx>,
171         make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
172     ) {
173         debug!("perform_test({:?}, {:?}: {:?}, {:?})",
174                block,
175                place,
176                place.ty(&self.local_decls, self.hir.tcx()),
177                test);
178
179         let source_info = self.source_info(test.span);
180         match test.kind {
181             TestKind::Switch { adt_def, ref variants } => {
182                 let target_blocks = make_target_blocks(self);
183                 // Variants is a BitVec of indexes into adt_def.variants.
184                 let num_enum_variants = adt_def.variants.len();
185                 let used_variants = variants.count();
186                 debug_assert_eq!(target_blocks.len(), num_enum_variants + 1);
187                 let otherwise_block = *target_blocks.last().unwrap();
188                 let mut targets = Vec::with_capacity(used_variants + 1);
189                 let mut values = Vec::with_capacity(used_variants);
190                 let tcx = self.hir.tcx();
191                 for (idx, discr) in adt_def.discriminants(tcx) {
192                     if variants.contains(idx) {
193                         debug_assert_ne!(
194                             target_blocks[idx.index()],
195                             otherwise_block,
196                             "no canididates for tested discriminant: {:?}",
197                             discr,
198                         );
199                         values.push(discr.val);
200                         targets.push(target_blocks[idx.index()]);
201                     } else {
202                         debug_assert_eq!(
203                             target_blocks[idx.index()],
204                             otherwise_block,
205                             "found canididates for untested discriminant: {:?}",
206                             discr,
207                         );
208                     }
209                 }
210                 targets.push(otherwise_block);
211                 debug!("num_enum_variants: {}, tested variants: {:?}, variants: {:?}",
212                        num_enum_variants, values, variants);
213                 let discr_ty = adt_def.repr.discr_type().to_ty(tcx);
214                 let discr = self.temp(discr_ty, test.span);
215                 self.cfg.push_assign(block, source_info, &discr,
216                                      Rvalue::Discriminant(place.clone()));
217                 assert_eq!(values.len() + 1, targets.len());
218                 self.cfg.terminate(block, source_info, TerminatorKind::SwitchInt {
219                     discr: Operand::Move(discr),
220                     switch_ty: discr_ty,
221                     values: From::from(values),
222                     targets,
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.sty == 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.clone()),
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.clone()),
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                         let val = Operand::Copy(place.clone());
273                         let expect = self.literal_operand(test.span, ty, value);
274                         self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
275                     } else {
276                         bug!("`TestKind::Eq` should have two target blocks");
277                     }
278                 }
279             }
280
281             TestKind::Range(PatternRange { ref lo, ref hi, ty, ref end }) => {
282                 let lower_bound_success = self.cfg.start_new_block();
283                 let target_blocks = make_target_blocks(self);
284
285                 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
286                 let lo = self.literal_operand(test.span, ty, lo);
287                 let hi = self.literal_operand(test.span, ty, hi);
288                 let val = Operand::Copy(place.clone());
289
290                 if let [success, fail] = *target_blocks {
291                     self.compare(
292                         block,
293                         lower_bound_success,
294                         fail,
295                         source_info,
296                         BinOp::Le,
297                         lo,
298                         val.clone(),
299                     );
300                     let op = match *end {
301                         RangeEnd::Included => BinOp::Le,
302                         RangeEnd::Excluded => BinOp::Lt,
303                     };
304                     self.compare(lower_bound_success, success, fail, source_info, op, val, hi);
305                 } else {
306                     bug!("`TestKind::Range` should have two target blocks");
307                 }
308             }
309
310             TestKind::Len { len, op } => {
311                 let target_blocks = make_target_blocks(self);
312
313                 let usize_ty = self.hir.usize_ty();
314                 let actual = self.temp(usize_ty, test.span);
315
316                 // actual = len(place)
317                 self.cfg.push_assign(block, source_info,
318                                      &actual, Rvalue::Len(place.clone()));
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(
358             block,
359             source_info,
360             &result,
361             Rvalue::BinaryOp(op, left, right),
362         );
363
364         // branch based on result
365         self.cfg.terminate(
366             block,
367             source_info,
368             TerminatorKind::if_(
369                 self.hir.tcx(),
370                 Operand::Move(result),
371                 success_block,
372                 fail_block,
373             ),
374         );
375     }
376
377     /// Compare two `&T` values using `<T as std::compare::PartialEq>::eq`
378     fn non_scalar_compare(
379         &mut self,
380         block: BasicBlock,
381         make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
382         source_info: SourceInfo,
383         value: &'tcx ty::Const<'tcx>,
384         place: &Place<'tcx>,
385         mut ty: Ty<'tcx>,
386     ) {
387         use rustc::middle::lang_items::EqTraitLangItem;
388
389         let mut expect = self.literal_operand(source_info.span, value.ty, value);
390         let mut val = Operand::Copy(place.clone());
391
392         // If we're using `b"..."` as a pattern, we need to insert an
393         // unsizing coercion, as the byte string has the type `&[u8; N]`.
394         //
395         // We want to do this even when the scrutinee is a reference to an
396         // array, so we can call `<[u8]>::eq` rather than having to find an
397         // `<[u8; N]>::eq`.
398         let unsize = |ty: Ty<'tcx>| match ty.sty {
399             ty::Ref(region, rty, _) => match rty.sty {
400                 ty::Array(inner_ty, n) => Some((region, inner_ty, n)),
401                 _ => None,
402             },
403             _ => None,
404         };
405         let opt_ref_ty = unsize(ty);
406         let opt_ref_test_ty = unsize(value.ty);
407         match (opt_ref_ty, opt_ref_test_ty) {
408             // nothing to do, neither is an array
409             (None, None) => {},
410             (Some((region, elem_ty, _)), _) |
411             (None, Some((region, elem_ty, _))) => {
412                 let tcx = self.hir.tcx();
413                 // make both a slice
414                 ty = tcx.mk_imm_ref(region, tcx.mk_slice(elem_ty));
415                 if opt_ref_ty.is_some() {
416                     let temp = self.temp(ty, source_info.span);
417                     self.cfg.push_assign(
418                         block, source_info, &temp, Rvalue::Cast(
419                             CastKind::Pointer(PointerCast::Unsize), val, ty
420                         )
421                     );
422                     val = Operand::Move(temp);
423                 }
424                 if opt_ref_test_ty.is_some() {
425                     let slice = self.temp(ty, source_info.span);
426                     self.cfg.push_assign(
427                         block, source_info, &slice, Rvalue::Cast(
428                             CastKind::Pointer(PointerCast::Unsize), expect, ty
429                         )
430                     );
431                     expect = Operand::Move(slice);
432                 }
433             },
434         }
435
436         let deref_ty = match ty.sty {
437             ty::Ref(_, deref_ty, _) => deref_ty,
438             _ => bug!("non_scalar_compare called on non-reference type: {}", ty),
439         };
440
441         let eq_def_id = self.hir.tcx().require_lang_item(EqTraitLangItem);
442         let (mty, method) = self.hir.trait_method(eq_def_id, sym::eq, deref_ty, &[deref_ty.into()]);
443
444         let bool_ty = self.hir.bool_ty();
445         let eq_result = self.temp(bool_ty, source_info.span);
446         let eq_block = self.cfg.start_new_block();
447         let cleanup = self.diverge_cleanup();
448         self.cfg.terminate(block, source_info, TerminatorKind::Call {
449             func: Operand::Constant(box Constant {
450                 span: source_info.span,
451                 ty: mty,
452
453                 // FIXME(#54571): This constant comes from user input (a
454                 // constant in a pattern).  Are there forms where users can add
455                 // type annotations here?  For example, an associated constant?
456                 // Need to experiment.
457                 user_ty: None,
458
459                 literal: method,
460             }),
461             args: vec![val, expect],
462             destination: Some((eq_result.clone(), eq_block)),
463             cleanup: Some(cleanup),
464             from_hir_call: false,
465         });
466
467         if let [success_block, fail_block] = *make_target_blocks(self) {
468             // check the result
469             self.cfg.terminate(
470                 eq_block,
471                 source_info,
472                 TerminatorKind::if_(
473                     self.hir.tcx(),
474                     Operand::Move(eq_result),
475                     success_block,
476                     fail_block,
477                 ),
478             );
479         } else {
480             bug!("`TestKind::Eq` should have two target blocks")
481         }
482     }
483
484     /// Given that we are performing `test` against `test_place`, this job
485     /// sorts out what the status of `candidate` will be after the test. See
486     /// `test_candidates` for the usage of this function. The returned index is
487     /// the index that this candiate should be placed in the
488     /// `target_candidates` vec. The candidate may be modified to update its
489     /// `match_pairs`.
490     ///
491     /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
492     /// a variant test, then we would modify the candidate to be `(x as
493     /// Option).0 @ P0` and return the index corresponding to the variant
494     /// `Some`.
495     ///
496     /// However, in some cases, the test may just not be relevant to candidate.
497     /// For example, suppose we are testing whether `foo.x == 22`, but in one
498     /// match arm we have `Foo { x: _, ... }`... in that case, the test for
499     /// what value `x` has has no particular relevance to this candidate. In
500     /// such cases, this function just returns None without doing anything.
501     /// This is used by the overall `match_candidates` algorithm to structure
502     /// the match as a whole. See `match_candidates` for more details.
503     ///
504     /// FIXME(#29623). In some cases, we have some tricky choices to make.  for
505     /// example, if we are testing that `x == 22`, but the candidate is `x @
506     /// 13..55`, what should we do? In the event that the test is true, we know
507     /// that the candidate applies, but in the event of false, we don't know
508     /// that it *doesn't* apply. For now, we return false, indicate that the
509     /// test does not apply to this candidate, but it might be we can get
510     /// tighter match code if we do something a bit different.
511     pub fn sort_candidate<'pat>(
512         &mut self,
513         test_place: &Place<'tcx>,
514         test: &Test<'tcx>,
515         candidate: &mut Candidate<'pat, 'tcx>,
516     ) -> Option<usize> {
517         // Find the match_pair for this place (if any). At present,
518         // afaik, there can be at most one. (In the future, if we
519         // adopted a more general `@` operator, there might be more
520         // than one, but it'd be very unusual to have two sides that
521         // both require tests; you'd expect one side to be simplified
522         // away.)
523         let (match_pair_index, match_pair) = candidate.match_pairs
524             .iter()
525             .enumerate()
526             .find(|&(_, mp)| mp.place == *test_place)?;
527
528         match (&test.kind, &*match_pair.pattern.kind) {
529             // If we are performing a variant switch, then this
530             // informs variant patterns, but nothing else.
531             (&TestKind::Switch { adt_def: tested_adt_def, .. },
532              &PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. }) => {
533                 assert_eq!(adt_def, tested_adt_def);
534                 self.candidate_after_variant_switch(match_pair_index,
535                                                     adt_def,
536                                                     variant_index,
537                                                     subpatterns,
538                                                     candidate);
539                 Some(variant_index.as_usize())
540             }
541
542             (&TestKind::Switch { .. }, _) => None,
543
544             // If we are performing a switch over integers, then this informs integer
545             // equality, but nothing else.
546             //
547             // FIXME(#29623) we could use PatternKind::Range to rule
548             // things out here, in some cases.
549             (&TestKind::SwitchInt { switch_ty: _, options: _, ref indices },
550              &PatternKind::Constant { ref value })
551             if is_switch_ty(match_pair.pattern.ty) => {
552                 let index = indices[value];
553                 self.candidate_without_match_pair(match_pair_index, candidate);
554                 Some(index)
555             }
556
557             (&TestKind::SwitchInt { switch_ty: _, ref options, ref indices },
558              &PatternKind::Range(range)) => {
559                 let not_contained = self
560                     .values_not_contained_in_range(range, indices)
561                     .unwrap_or(false);
562
563                 if not_contained {
564                     // No switch values are contained in the pattern range,
565                     // so the pattern can be matched only if this test fails.
566                     let otherwise = options.len();
567                     Some(otherwise)
568                 } else {
569                     None
570                 }
571             }
572
573             (&TestKind::SwitchInt { .. }, _) => None,
574
575             (&TestKind::Len { len: test_len, op: BinOp::Eq },
576              &PatternKind::Slice { ref prefix, ref slice, ref suffix }) => {
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(match_pair_index,
583                                                         candidate,
584                                                         prefix,
585                                                         slice.as_ref(),
586                                                         suffix);
587                         Some(0)
588                     }
589                     (Ordering::Less, _) => {
590                         // test_len < pat_len. If $actual_len = test_len,
591                         // then $actual_len < pat_len and we don't have
592                         // enough elements.
593                         Some(1)
594                     }
595                     (Ordering::Equal, &Some(_)) | (Ordering::Greater, &Some(_)) => {
596                         // This can match both if $actual_len = test_len >= pat_len,
597                         // and if $actual_len > test_len. We can't advance.
598                         None
599                     }
600                     (Ordering::Greater, &None) => {
601                         // test_len != pat_len, so if $actual_len = test_len, then
602                         // $actual_len != pat_len.
603                         Some(1)
604                     }
605                 }
606             }
607
608             (&TestKind::Len { len: test_len, op: BinOp::Ge },
609              &PatternKind::Slice { ref prefix, ref slice, ref suffix }) => {
610                 // the test is `$actual_len >= test_len`
611                 let pat_len = (prefix.len() + suffix.len()) as u64;
612                 match (test_len.cmp(&pat_len), slice) {
613                     (Ordering::Equal, &Some(_))  => {
614                         // $actual_len >= test_len = pat_len,
615                         // so we can match.
616                         self.candidate_after_slice_test(match_pair_index,
617                                                         candidate,
618                                                         prefix,
619                                                         slice.as_ref(),
620                                                         suffix);
621                         Some(0)
622                     }
623                     (Ordering::Less, _) | (Ordering::Equal, &None) => {
624                         // test_len <= pat_len. If $actual_len < test_len,
625                         // then it is also < pat_len, so the test passing is
626                         // necessary (but insufficient).
627                         Some(0)
628                     }
629                     (Ordering::Greater, &None) => {
630                         // test_len > pat_len. If $actual_len >= test_len > pat_len,
631                         // then we know we won't have a match.
632                         Some(1)
633                     }
634                     (Ordering::Greater, &Some(_)) => {
635                         // test_len < pat_len, and is therefore less
636                         // strict. This can still go both ways.
637                         None
638                     }
639                 }
640             }
641
642             (&TestKind::Range(test),
643              &PatternKind::Range(pat)) => {
644                 if test == pat {
645                     self.candidate_without_match_pair(
646                         match_pair_index,
647                         candidate,
648                     );
649                     return Some(0);
650                 }
651
652                 let no_overlap = (|| {
653                     use std::cmp::Ordering::*;
654                     use rustc::hir::RangeEnd::*;
655
656                     let param_env = ty::ParamEnv::empty().and(test.ty);
657                     let tcx = self.hir.tcx();
658
659                     let lo = compare_const_vals(tcx, test.lo, pat.hi, param_env)?;
660                     let hi = compare_const_vals(tcx, test.hi, pat.lo, param_env)?;
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 param_env = ty::ParamEnv::empty().and(range.ty);
776         let tcx = self.hir.tcx();
777
778         let a = compare_const_vals(tcx, range.lo, value, param_env)?;
779         let b = compare_const_vals(tcx, value, range.hi, param_env)?;
780
781         match (b, range.end) {
782             (Less, _) |
783             (Equal, RangeEnd::Included) if a != Greater => Some(true),
784             _ => Some(false),
785         }
786     }
787
788     fn values_not_contained_in_range(
789         &self,
790         range: PatternRange<'tcx>,
791         indices: &FxHashMap<&'tcx ty::Const<'tcx>, usize>,
792     ) -> Option<bool> {
793         for &val in indices.keys() {
794             if self.const_range_contains(range, val)? {
795                 return Some(false);
796             }
797         }
798
799         Some(true)
800     }
801 }
802
803 impl Test<'_> {
804     pub(super) fn targets(&self) -> usize {
805         match self.kind {
806             TestKind::Eq { .. } | TestKind::Range(_) | TestKind::Len { .. } => {
807                 2
808             }
809             TestKind::Switch { adt_def, .. } => {
810                 // While the switch that we generate doesn't test for all
811                 // variants, we have a target for each variant and the
812                 // otherwise case, and we make sure that all of the cases not
813                 // specified have the same block.
814                 adt_def.variants.len() + 1
815             }
816             TestKind::SwitchInt { switch_ty, ref options, .. } => {
817                 if switch_ty.is_bool() {
818                     // `bool` is special cased in `perform_test` to always
819                     // branch to two blocks.
820                     2
821                 } else {
822                     options.len() + 1
823                 }
824             }
825         }
826     }
827 }
828
829 fn is_switch_ty(ty: Ty<'_>) -> bool {
830     ty.is_integral() || ty.is_char() || ty.is_bool()
831 }