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