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