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