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