rustc_mir_build/builder/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
8use std::cmp::Ordering;
9use std::sync::Arc;
10
11use rustc_data_structures::fx::FxIndexMap;
12use rustc_hir::{LangItem, RangeEnd};
13use rustc_middle::mir::*;
14use rustc_middle::ty::util::IntTypeExt;
15use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt};
16use rustc_middle::{bug, span_bug};
17use rustc_span::def_id::DefId;
18use rustc_span::source_map::Spanned;
19use rustc_span::{DUMMY_SP, Span, Symbol, sym};
20use tracing::{debug, instrument};
21
22use crate::builder::Builder;
23use crate::builder::matches::{Candidate, MatchPairTree, Test, TestBranch, TestCase, TestKind};
24
25impl<'a, 'tcx> Builder<'a, 'tcx> {
26 /// Identifies what test is needed to decide if `match_pair` is applicable.
27 ///
28 /// It is a bug to call this with a not-fully-simplified pattern.
29 pub(super) fn pick_test_for_match_pair(
30 &mut self,
31 match_pair: &MatchPairTree<'tcx>,
32 ) -> Test<'tcx> {
33 let kind = match match_pair.test_case {
34 TestCase::Variant { adt_def, variant_index: _ } => TestKind::Switch { adt_def },
35
36 TestCase::Constant { .. } if match_pair.pattern_ty.is_bool() => TestKind::If,
37 TestCase::Constant { .. } if is_switch_ty(match_pair.pattern_ty) => TestKind::SwitchInt,
38 TestCase::Constant { value } => TestKind::Eq { value, ty: match_pair.pattern_ty },
39
40 TestCase::Range(ref range) => {
41 assert_eq!(range.ty, match_pair.pattern_ty);
42 TestKind::Range(Arc::clone(range))
43 }
44
45 TestCase::Slice { len, variable_length } => {
46 let op = if variable_length { BinOp::Ge } else { BinOp::Eq };
47 TestKind::Len { len: len as u64, op }
48 }
49
50 TestCase::Deref { temp, mutability } => TestKind::Deref { temp, mutability },
51
52 TestCase::Never => TestKind::Never,
53
54 // Or-patterns are not tested directly; instead they are expanded into subcandidates,
55 // which are then distinguished by testing whatever non-or patterns they contain.
56 TestCase::Or { .. } => bug!("or-patterns should have already been handled"),
57 };
58
59 Test { span: match_pair.pattern_span, kind }
60 }
61
62 #[instrument(skip(self, target_blocks, place), level = "debug")]
63 pub(super) fn perform_test(
64 &mut self,
65 match_start_span: Span,
66 scrutinee_span: Span,
67 block: BasicBlock,
68 otherwise_block: BasicBlock,
69 place: Place<'tcx>,
70 test: &Test<'tcx>,
71 target_blocks: FxIndexMap<TestBranch<'tcx>, BasicBlock>,
72 ) {
73 let place_ty = place.ty(&self.local_decls, self.tcx);
74 debug!(?place, ?place_ty);
75 let target_block = |branch| target_blocks.get(&branch).copied().unwrap_or(otherwise_block);
76
77 let source_info = self.source_info(test.span);
78 match test.kind {
79 TestKind::Switch { adt_def } => {
80 let otherwise_block = target_block(TestBranch::Failure);
81 let switch_targets = SwitchTargets::new(
82 adt_def.discriminants(self.tcx).filter_map(|(idx, discr)| {
83 if let Some(&block) = target_blocks.get(&TestBranch::Variant(idx)) {
84 Some((discr.val, block))
85 } else {
86 None
87 }
88 }),
89 otherwise_block,
90 );
91 debug!("num_enum_variants: {}", adt_def.variants().len());
92 let discr_ty = adt_def.repr().discr_type().to_ty(self.tcx);
93 let discr = self.temp(discr_ty, test.span);
94 self.cfg.push_assign(
95 block,
96 self.source_info(scrutinee_span),
97 discr,
98 Rvalue::Discriminant(place),
99 );
100 self.cfg.terminate(
101 block,
102 self.source_info(match_start_span),
103 TerminatorKind::SwitchInt {
104 discr: Operand::Move(discr),
105 targets: switch_targets,
106 },
107 );
108 }
109
110 TestKind::SwitchInt => {
111 // The switch may be inexhaustive so we have a catch-all block
112 let otherwise_block = target_block(TestBranch::Failure);
113 let switch_targets = SwitchTargets::new(
114 target_blocks.iter().filter_map(|(&branch, &block)| {
115 if let TestBranch::Constant(_, bits) = branch {
116 Some((bits, block))
117 } else {
118 None
119 }
120 }),
121 otherwise_block,
122 );
123 let terminator = TerminatorKind::SwitchInt {
124 discr: Operand::Copy(place),
125 targets: switch_targets,
126 };
127 self.cfg.terminate(block, self.source_info(match_start_span), terminator);
128 }
129
130 TestKind::If => {
131 let success_block = target_block(TestBranch::Success);
132 let fail_block = target_block(TestBranch::Failure);
133 let terminator =
134 TerminatorKind::if_(Operand::Copy(place), success_block, fail_block);
135 self.cfg.terminate(block, self.source_info(match_start_span), terminator);
136 }
137
138 TestKind::Eq { value, mut ty } => {
139 let tcx = self.tcx;
140 let success_block = target_block(TestBranch::Success);
141 let fail_block = target_block(TestBranch::Failure);
142
143 let mut expect_ty = value.ty();
144 let mut expect = self.literal_operand(test.span, value);
145
146 let mut place = place;
147 let mut block = block;
148 match ty.kind() {
149 ty::Str => {
150 // String literal patterns may have type `str` if `deref_patterns` is
151 // enabled, in order to allow `deref!("..."): String`. In this case, `value`
152 // is of type `&str`, so we compare it to `&place`.
153 if !tcx.features().deref_patterns() {
154 span_bug!(
155 test.span,
156 "matching on `str` went through without enabling deref_patterns"
157 );
158 }
159 let re_erased = tcx.lifetimes.re_erased;
160 let ref_str_ty = Ty::new_imm_ref(tcx, re_erased, tcx.types.str_);
161 let ref_place = self.temp(ref_str_ty, test.span);
162 // `let ref_place: &str = &place;`
163 self.cfg.push_assign(
164 block,
165 self.source_info(test.span),
166 ref_place,
167 Rvalue::Ref(re_erased, BorrowKind::Shared, place),
168 );
169 place = ref_place;
170 ty = ref_str_ty;
171 }
172 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => {
173 if !tcx.features().string_deref_patterns() {
174 span_bug!(
175 test.span,
176 "matching on `String` went through without enabling string_deref_patterns"
177 );
178 }
179 let re_erased = tcx.lifetimes.re_erased;
180 let ref_str_ty = Ty::new_imm_ref(tcx, re_erased, tcx.types.str_);
181 let ref_str = self.temp(ref_str_ty, test.span);
182 let eq_block = self.cfg.start_new_block();
183 // `let ref_str: &str = <String as Deref>::deref(&place);`
184 self.call_deref(
185 block,
186 eq_block,
187 place,
188 Mutability::Not,
189 ty,
190 ref_str,
191 test.span,
192 );
193 // Since we generated a `ref_str = <String as Deref>::deref(&place) -> eq_block` terminator,
194 // we need to add all further statements to `eq_block`.
195 // Similarly, the normal test code should be generated for the `&str`, instead of the `String`.
196 block = eq_block;
197 place = ref_str;
198 ty = ref_str_ty;
199 }
200 &ty::Pat(base, _) => {
201 assert_eq!(ty, value.ty());
202 assert!(base.is_trivially_pure_clone_copy());
203
204 let transmuted_place = self.temp(base, test.span);
205 self.cfg.push_assign(
206 block,
207 self.source_info(scrutinee_span),
208 transmuted_place,
209 Rvalue::Cast(CastKind::Transmute, Operand::Copy(place), base),
210 );
211
212 let transmuted_expect = self.temp(base, test.span);
213 self.cfg.push_assign(
214 block,
215 self.source_info(test.span),
216 transmuted_expect,
217 Rvalue::Cast(CastKind::Transmute, expect, base),
218 );
219
220 place = transmuted_place;
221 expect = Operand::Copy(transmuted_expect);
222 ty = base;
223 expect_ty = base;
224 }
225 _ => {}
226 }
227
228 assert_eq!(expect_ty, ty);
229 if !ty.is_scalar() {
230 // Use `PartialEq::eq` instead of `BinOp::Eq`
231 // (the binop can only handle primitives)
232 // Make sure that we do *not* call any user-defined code here.
233 // The only type that can end up here is string literals, which have their
234 // comparison defined in `core`.
235 // (Interestingly this means that exhaustiveness analysis relies, for soundness,
236 // on the `PartialEq` impl for `str` to b correct!)
237 match *ty.kind() {
238 ty::Ref(_, deref_ty, _) if deref_ty == self.tcx.types.str_ => {}
239 _ => {
240 span_bug!(source_info.span, "invalid type for non-scalar compare: {ty}")
241 }
242 };
243 self.string_compare(
244 block,
245 success_block,
246 fail_block,
247 source_info,
248 expect,
249 Operand::Copy(place),
250 );
251 } else {
252 self.compare(
253 block,
254 success_block,
255 fail_block,
256 source_info,
257 BinOp::Eq,
258 expect,
259 Operand::Copy(place),
260 );
261 }
262 }
263
264 TestKind::Range(ref range) => {
265 let success = target_block(TestBranch::Success);
266 let fail = target_block(TestBranch::Failure);
267 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
268 let val = Operand::Copy(place);
269
270 let intermediate_block = if !range.lo.is_finite() {
271 block
272 } else if !range.hi.is_finite() {
273 success
274 } else {
275 self.cfg.start_new_block()
276 };
277
278 if let Some(lo) = range.lo.as_finite() {
279 let lo = self.literal_operand(test.span, lo);
280 self.compare(
281 block,
282 intermediate_block,
283 fail,
284 source_info,
285 BinOp::Le,
286 lo,
287 val.clone(),
288 );
289 };
290
291 if let Some(hi) = range.hi.as_finite() {
292 let hi = self.literal_operand(test.span, hi);
293 let op = match range.end {
294 RangeEnd::Included => BinOp::Le,
295 RangeEnd::Excluded => BinOp::Lt,
296 };
297 self.compare(intermediate_block, success, fail, source_info, op, val, hi);
298 }
299 }
300
301 TestKind::Len { len, op } => {
302 let usize_ty = self.tcx.types.usize;
303 let actual = self.temp(usize_ty, test.span);
304
305 // actual = len(place)
306 self.cfg.push_assign(block, source_info, actual, Rvalue::Len(place));
307
308 // expected = <N>
309 let expected = self.push_usize(block, source_info, len);
310
311 let success_block = target_block(TestBranch::Success);
312 let fail_block = target_block(TestBranch::Failure);
313 // result = actual == expected OR result = actual < expected
314 // branch based on result
315 self.compare(
316 block,
317 success_block,
318 fail_block,
319 source_info,
320 op,
321 Operand::Move(actual),
322 Operand::Move(expected),
323 );
324 }
325
326 TestKind::Deref { temp, mutability } => {
327 let ty = place_ty.ty;
328 let target = target_block(TestBranch::Success);
329 self.call_deref(block, target, place, mutability, ty, temp, test.span);
330 }
331
332 TestKind::Never => {
333 // Check that the place is initialized.
334 // FIXME(never_patterns): Also assert validity of the data at `place`.
335 self.cfg.push_fake_read(
336 block,
337 source_info,
338 FakeReadCause::ForMatchedPlace(None),
339 place,
340 );
341 // A never pattern is only allowed on an uninhabited type, so validity of the data
342 // implies unreachability.
343 self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
344 }
345 }
346 }
347
348 /// Perform `let temp = <ty as Deref>::deref(&place)`.
349 /// or `let temp = <ty as DerefMut>::deref_mut(&mut place)`.
350 pub(super) fn call_deref(
351 &mut self,
352 block: BasicBlock,
353 target_block: BasicBlock,
354 place: Place<'tcx>,
355 mutability: Mutability,
356 ty: Ty<'tcx>,
357 temp: Place<'tcx>,
358 span: Span,
359 ) {
360 let (trait_item, method) = match mutability {
361 Mutability::Not => (LangItem::Deref, sym::deref),
362 Mutability::Mut => (LangItem::DerefMut, sym::deref_mut),
363 };
364 let borrow_kind = super::util::ref_pat_borrow_kind(mutability);
365 let source_info = self.source_info(span);
366 let re_erased = self.tcx.lifetimes.re_erased;
367 let trait_item = self.tcx.require_lang_item(trait_item, None);
368 let method = trait_method(self.tcx, trait_item, method, [ty]);
369 let ref_src = self.temp(Ty::new_ref(self.tcx, re_erased, ty, mutability), span);
370 // `let ref_src = &src_place;`
371 // or `let ref_src = &mut src_place;`
372 self.cfg.push_assign(
373 block,
374 source_info,
375 ref_src,
376 Rvalue::Ref(re_erased, borrow_kind, place),
377 );
378 // `let temp = <Ty as Deref>::deref(ref_src);`
379 // or `let temp = <Ty as DerefMut>::deref_mut(ref_src);`
380 self.cfg.terminate(
381 block,
382 source_info,
383 TerminatorKind::Call {
384 func: Operand::Constant(Box::new(ConstOperand {
385 span,
386 user_ty: None,
387 const_: method,
388 })),
389 args: [Spanned { node: Operand::Move(ref_src), span }].into(),
390 destination: temp,
391 target: Some(target_block),
392 unwind: UnwindAction::Continue,
393 call_source: CallSource::Misc,
394 fn_span: source_info.span,
395 },
396 );
397 }
398
399 /// Compare using the provided built-in comparison operator
400 fn compare(
401 &mut self,
402 block: BasicBlock,
403 success_block: BasicBlock,
404 fail_block: BasicBlock,
405 source_info: SourceInfo,
406 op: BinOp,
407 left: Operand<'tcx>,
408 right: Operand<'tcx>,
409 ) {
410 let bool_ty = self.tcx.types.bool;
411 let result = self.temp(bool_ty, source_info.span);
412
413 // result = op(left, right)
414 self.cfg.push_assign(
415 block,
416 source_info,
417 result,
418 Rvalue::BinaryOp(op, Box::new((left, right))),
419 );
420
421 // branch based on result
422 self.cfg.terminate(
423 block,
424 source_info,
425 TerminatorKind::if_(Operand::Move(result), success_block, fail_block),
426 );
427 }
428
429 /// Compare two values of type `&str` using `<str as std::cmp::PartialEq>::eq`.
430 fn string_compare(
431 &mut self,
432 block: BasicBlock,
433 success_block: BasicBlock,
434 fail_block: BasicBlock,
435 source_info: SourceInfo,
436 expect: Operand<'tcx>,
437 val: Operand<'tcx>,
438 ) {
439 let str_ty = self.tcx.types.str_;
440 let eq_def_id = self.tcx.require_lang_item(LangItem::PartialEq, Some(source_info.span));
441 let method = trait_method(self.tcx, eq_def_id, sym::eq, [str_ty, str_ty]);
442
443 let bool_ty = self.tcx.types.bool;
444 let eq_result = self.temp(bool_ty, source_info.span);
445 let eq_block = self.cfg.start_new_block();
446 self.cfg.terminate(
447 block,
448 source_info,
449 TerminatorKind::Call {
450 func: Operand::Constant(Box::new(ConstOperand {
451 span: source_info.span,
452
453 // FIXME(#54571): This constant comes from user input (a
454 // constant in a pattern). Are there forms where users can add
455 // type annotations here? For example, an associated constant?
456 // Need to experiment.
457 user_ty: None,
458
459 const_: method,
460 })),
461 args: [
462 Spanned { node: val, span: DUMMY_SP },
463 Spanned { node: expect, span: DUMMY_SP },
464 ]
465 .into(),
466 destination: eq_result,
467 target: Some(eq_block),
468 unwind: UnwindAction::Continue,
469 call_source: CallSource::MatchCmp,
470 fn_span: source_info.span,
471 },
472 );
473 self.diverge_from(block);
474
475 // check the result
476 self.cfg.terminate(
477 eq_block,
478 source_info,
479 TerminatorKind::if_(Operand::Move(eq_result), success_block, fail_block),
480 );
481 }
482
483 /// Given that we are performing `test` against `test_place`, this job
484 /// sorts out what the status of `candidate` will be after the test. See
485 /// `test_candidates` for the usage of this function. The candidate may
486 /// be modified to update its `match_pairs`.
487 ///
488 /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
489 /// a variant test, then we would modify the candidate to be `(x as
490 /// Option).0 @ P0` and return the index corresponding to the variant
491 /// `Some`.
492 ///
493 /// However, in some cases, the test may just not be relevant to candidate.
494 /// For example, suppose we are testing whether `foo.x == 22`, but in one
495 /// match arm we have `Foo { x: _, ... }`... in that case, the test for
496 /// the value of `x` has no particular relevance to this candidate. In
497 /// such cases, this function just returns None without doing anything.
498 /// This is used by the overall `match_candidates` algorithm to structure
499 /// the match as a whole. See `match_candidates` for more details.
500 ///
501 /// FIXME(#29623). In some cases, we have some tricky choices to make. for
502 /// example, if we are testing that `x == 22`, but the candidate is `x @
503 /// 13..55`, what should we do? In the event that the test is true, we know
504 /// that the candidate applies, but in the event of false, we don't know
505 /// that it *doesn't* apply. For now, we return false, indicate that the
506 /// test does not apply to this candidate, but it might be we can get
507 /// tighter match code if we do something a bit different.
508 pub(super) fn sort_candidate(
509 &mut self,
510 test_place: Place<'tcx>,
511 test: &Test<'tcx>,
512 candidate: &mut Candidate<'tcx>,
513 sorted_candidates: &FxIndexMap<TestBranch<'tcx>, Vec<&mut Candidate<'tcx>>>,
514 ) -> Option<TestBranch<'tcx>> {
515 // Find the match_pair for this place (if any). At present,
516 // afaik, there can be at most one. (In the future, if we
517 // adopted a more general `@` operator, there might be more
518 // than one, but it'd be very unusual to have two sides that
519 // both require tests; you'd expect one side to be simplified
520 // away.)
521 let (match_pair_index, match_pair) = candidate
522 .match_pairs
523 .iter()
524 .enumerate()
525 .find(|&(_, mp)| mp.place == Some(test_place))?;
526
527 // If true, the match pair is completely entailed by its corresponding test
528 // branch, so it can be removed. If false, the match pair is _compatible_
529 // with its test branch, but still needs a more specific test.
530 let fully_matched;
531 let ret = match (&test.kind, &match_pair.test_case) {
532 // If we are performing a variant switch, then this
533 // informs variant patterns, but nothing else.
534 (
535 &TestKind::Switch { adt_def: tested_adt_def },
536 &TestCase::Variant { adt_def, variant_index },
537 ) => {
538 assert_eq!(adt_def, tested_adt_def);
539 fully_matched = true;
540 Some(TestBranch::Variant(variant_index))
541 }
542
543 // If we are performing a switch over integers, then this informs integer
544 // equality, but nothing else.
545 //
546 // FIXME(#29623) we could use PatKind::Range to rule
547 // things out here, in some cases.
548 (TestKind::SwitchInt, &TestCase::Constant { value })
549 if is_switch_ty(match_pair.pattern_ty) =>
550 {
551 // An important invariant of candidate sorting is that a candidate
552 // must not match in multiple branches. For `SwitchInt` tests, adding
553 // a new value might invalidate that property for range patterns that
554 // have already been sorted into the failure arm, so we must take care
555 // not to add such values here.
556 let is_covering_range = |test_case: &TestCase<'tcx>| {
557 test_case.as_range().is_some_and(|range| {
558 matches!(
559 range.contains(value, self.tcx, self.typing_env()),
560 None | Some(true)
561 )
562 })
563 };
564 let is_conflicting_candidate = |candidate: &&mut Candidate<'tcx>| {
565 candidate
566 .match_pairs
567 .iter()
568 .any(|mp| mp.place == Some(test_place) && is_covering_range(&mp.test_case))
569 };
570 if sorted_candidates
571 .get(&TestBranch::Failure)
572 .is_some_and(|candidates| candidates.iter().any(is_conflicting_candidate))
573 {
574 fully_matched = false;
575 None
576 } else {
577 fully_matched = true;
578 let bits = value.eval_bits(self.tcx, self.typing_env());
579 Some(TestBranch::Constant(value, bits))
580 }
581 }
582 (TestKind::SwitchInt, TestCase::Range(range)) => {
583 // When performing a `SwitchInt` test, a range pattern can be
584 // sorted into the failure arm if it doesn't contain _any_ of
585 // the values being tested. (This restricts what values can be
586 // added to the test by subsequent candidates.)
587 fully_matched = false;
588 let not_contained =
589 sorted_candidates.keys().filter_map(|br| br.as_constant()).copied().all(
590 |val| {
591 matches!(range.contains(val, self.tcx, self.typing_env()), Some(false))
592 },
593 );
594
595 not_contained.then(|| {
596 // No switch values are contained in the pattern range,
597 // so the pattern can be matched only if this test fails.
598 TestBranch::Failure
599 })
600 }
601
602 (TestKind::If, TestCase::Constant { value }) => {
603 fully_matched = true;
604 let value = value.try_eval_bool(self.tcx, self.typing_env()).unwrap_or_else(|| {
605 span_bug!(test.span, "expected boolean value but got {value:?}")
606 });
607 Some(if value { TestBranch::Success } else { TestBranch::Failure })
608 }
609
610 (
611 &TestKind::Len { len: test_len, op: BinOp::Eq },
612 &TestCase::Slice { len, variable_length },
613 ) => {
614 match (test_len.cmp(&(len as u64)), variable_length) {
615 (Ordering::Equal, false) => {
616 // on true, min_len = len = $actual_length,
617 // on false, len != $actual_length
618 fully_matched = true;
619 Some(TestBranch::Success)
620 }
621 (Ordering::Less, _) => {
622 // test_len < pat_len. If $actual_len = test_len,
623 // then $actual_len < pat_len and we don't have
624 // enough elements.
625 fully_matched = false;
626 Some(TestBranch::Failure)
627 }
628 (Ordering::Equal | Ordering::Greater, true) => {
629 // This can match both if $actual_len = test_len >= pat_len,
630 // and if $actual_len > test_len. We can't advance.
631 fully_matched = false;
632 None
633 }
634 (Ordering::Greater, false) => {
635 // test_len != pat_len, so if $actual_len = test_len, then
636 // $actual_len != pat_len.
637 fully_matched = false;
638 Some(TestBranch::Failure)
639 }
640 }
641 }
642 (
643 &TestKind::Len { len: test_len, op: BinOp::Ge },
644 &TestCase::Slice { len, variable_length },
645 ) => {
646 // the test is `$actual_len >= test_len`
647 match (test_len.cmp(&(len as u64)), variable_length) {
648 (Ordering::Equal, true) => {
649 // $actual_len >= test_len = pat_len,
650 // so we can match.
651 fully_matched = true;
652 Some(TestBranch::Success)
653 }
654 (Ordering::Less, _) | (Ordering::Equal, false) => {
655 // test_len <= pat_len. If $actual_len < test_len,
656 // then it is also < pat_len, so the test passing is
657 // necessary (but insufficient).
658 fully_matched = false;
659 Some(TestBranch::Success)
660 }
661 (Ordering::Greater, false) => {
662 // test_len > pat_len. If $actual_len >= test_len > pat_len,
663 // then we know we won't have a match.
664 fully_matched = false;
665 Some(TestBranch::Failure)
666 }
667 (Ordering::Greater, true) => {
668 // test_len < pat_len, and is therefore less
669 // strict. This can still go both ways.
670 fully_matched = false;
671 None
672 }
673 }
674 }
675
676 (TestKind::Range(test), TestCase::Range(pat)) => {
677 if test == pat {
678 fully_matched = true;
679 Some(TestBranch::Success)
680 } else {
681 fully_matched = false;
682 // If the testing range does not overlap with pattern range,
683 // the pattern can be matched only if this test fails.
684 if !test.overlaps(pat, self.tcx, self.typing_env())? {
685 Some(TestBranch::Failure)
686 } else {
687 None
688 }
689 }
690 }
691 (TestKind::Range(range), &TestCase::Constant { value }) => {
692 fully_matched = false;
693 if !range.contains(value, self.tcx, self.typing_env())? {
694 // `value` is not contained in the testing range,
695 // so `value` can be matched only if this test fails.
696 Some(TestBranch::Failure)
697 } else {
698 None
699 }
700 }
701
702 (TestKind::Eq { value: test_val, .. }, TestCase::Constant { value: case_val }) => {
703 if test_val == case_val {
704 fully_matched = true;
705 Some(TestBranch::Success)
706 } else {
707 fully_matched = false;
708 Some(TestBranch::Failure)
709 }
710 }
711
712 (TestKind::Deref { temp: test_temp, .. }, TestCase::Deref { temp, .. })
713 if test_temp == temp =>
714 {
715 fully_matched = true;
716 Some(TestBranch::Success)
717 }
718
719 (TestKind::Never, _) => {
720 fully_matched = true;
721 Some(TestBranch::Success)
722 }
723
724 (
725 TestKind::Switch { .. }
726 | TestKind::SwitchInt { .. }
727 | TestKind::If
728 | TestKind::Len { .. }
729 | TestKind::Range { .. }
730 | TestKind::Eq { .. }
731 | TestKind::Deref { .. },
732 _,
733 ) => {
734 fully_matched = false;
735 None
736 }
737 };
738
739 if fully_matched {
740 // Replace the match pair by its sub-pairs.
741 let match_pair = candidate.match_pairs.remove(match_pair_index);
742 candidate.match_pairs.extend(match_pair.subpairs);
743 // Move or-patterns to the end.
744 candidate.sort_match_pairs();
745 }
746
747 ret
748 }
749}
750
751fn is_switch_ty(ty: Ty<'_>) -> bool {
752 ty.is_integral() || ty.is_char()
753}
754
755fn trait_method<'tcx>(
756 tcx: TyCtxt<'tcx>,
757 trait_def_id: DefId,
758 method_name: Symbol,
759 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
760) -> Const<'tcx> {
761 // The unhygienic comparison here is acceptable because this is only
762 // used on known traits.
763 let item = tcx
764 .associated_items(trait_def_id)
765 .filter_by_name_unhygienic(method_name)
766 .find(|item| item.is_fn())
767 .expect("trait method not found");
768
769 let method_ty = Ty::new_fn_def(tcx, item.def_id, args);
770
771 Const::zero_sized(method_ty)
772}