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