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, cast_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(value) = branch {
116 let bits = value.valtree.unwrap_leaf().to_bits_unchecked();
117 Some((bits, block))
118 } else {
119 None
120 }
121 }),
122 otherwise_block,
123 );
124 let terminator = TerminatorKind::SwitchInt {
125 discr: Operand::Copy(place),
126 targets: switch_targets,
127 };
128 self.cfg.terminate(block, self.source_info(match_start_span), terminator);
129 }
130
131 TestKind::If => {
132 let success_block = target_block(TestBranch::Success);
133 let fail_block = target_block(TestBranch::Failure);
134 let terminator =
135 TerminatorKind::if_(Operand::Copy(place), success_block, fail_block);
136 self.cfg.terminate(block, self.source_info(match_start_span), terminator);
137 }
138
139 TestKind::Eq { value, mut cast_ty } => {
140 let tcx = self.tcx;
141 let success_block = target_block(TestBranch::Success);
142 let fail_block = target_block(TestBranch::Failure);
143
144 let mut expect_ty = value.ty;
145 let mut expect = self.literal_operand(test.span, Const::from_ty_value(tcx, value));
146
147 let mut place = place;
148 let mut block = block;
149 match cast_ty.kind() {
150 ty::Str => {
151 // String literal patterns may have type `str` if `deref_patterns` is
152 // enabled, in order to allow `deref!("..."): String`. In this case, `value`
153 // is of type `&str`, so we compare it to `&place`.
154 if !tcx.features().deref_patterns() {
155 span_bug!(
156 test.span,
157 "matching on `str` went through without enabling deref_patterns"
158 );
159 }
160 let re_erased = tcx.lifetimes.re_erased;
161 let ref_str_ty = Ty::new_imm_ref(tcx, re_erased, tcx.types.str_);
162 let ref_place = self.temp(ref_str_ty, test.span);
163 // `let ref_place: &str = &place;`
164 self.cfg.push_assign(
165 block,
166 self.source_info(test.span),
167 ref_place,
168 Rvalue::Ref(re_erased, BorrowKind::Shared, place),
169 );
170 place = ref_place;
171 cast_ty = ref_str_ty;
172 }
173 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => {
174 if !tcx.features().string_deref_patterns() {
175 span_bug!(
176 test.span,
177 "matching on `String` went through without enabling string_deref_patterns"
178 );
179 }
180 let re_erased = tcx.lifetimes.re_erased;
181 let ref_str_ty = Ty::new_imm_ref(tcx, re_erased, tcx.types.str_);
182 let ref_str = self.temp(ref_str_ty, test.span);
183 let eq_block = self.cfg.start_new_block();
184 // `let ref_str: &str = <String as Deref>::deref(&place);`
185 self.call_deref(
186 block,
187 eq_block,
188 place,
189 Mutability::Not,
190 cast_ty,
191 ref_str,
192 test.span,
193 );
194 // Since we generated a `ref_str = <String as Deref>::deref(&place) -> eq_block` terminator,
195 // we need to add all further statements to `eq_block`.
196 // Similarly, the normal test code should be generated for the `&str`, instead of the `String`.
197 block = eq_block;
198 place = ref_str;
199 cast_ty = ref_str_ty;
200 }
201 &ty::Pat(base, _) => {
202 assert_eq!(cast_ty, value.ty);
203 assert!(base.is_trivially_pure_clone_copy());
204
205 let transmuted_place = self.temp(base, test.span);
206 self.cfg.push_assign(
207 block,
208 self.source_info(scrutinee_span),
209 transmuted_place,
210 Rvalue::Cast(CastKind::Transmute, Operand::Copy(place), base),
211 );
212
213 let transmuted_expect = self.temp(base, test.span);
214 self.cfg.push_assign(
215 block,
216 self.source_info(test.span),
217 transmuted_expect,
218 Rvalue::Cast(CastKind::Transmute, expect, base),
219 );
220
221 place = transmuted_place;
222 expect = Operand::Copy(transmuted_expect);
223 cast_ty = base;
224 expect_ty = base;
225 }
226 _ => {}
227 }
228
229 assert_eq!(expect_ty, cast_ty);
230 if !cast_ty.is_scalar() {
231 // Use `PartialEq::eq` instead of `BinOp::Eq`
232 // (the binop can only handle primitives)
233 // Make sure that we do *not* call any user-defined code here.
234 // The only type that can end up here is string literals, which have their
235 // comparison defined in `core`.
236 // (Interestingly this means that exhaustiveness analysis relies, for soundness,
237 // on the `PartialEq` impl for `str` to b correct!)
238 match *cast_ty.kind() {
239 ty::Ref(_, deref_ty, _) if deref_ty == self.tcx.types.str_ => {}
240 _ => {
241 span_bug!(
242 source_info.span,
243 "invalid type for non-scalar compare: {cast_ty}"
244 )
245 }
246 };
247 self.string_compare(
248 block,
249 success_block,
250 fail_block,
251 source_info,
252 expect,
253 Operand::Copy(place),
254 );
255 } else {
256 self.compare(
257 block,
258 success_block,
259 fail_block,
260 source_info,
261 BinOp::Eq,
262 expect,
263 Operand::Copy(place),
264 );
265 }
266 }
267
268 TestKind::Range(ref range) => {
269 let success = target_block(TestBranch::Success);
270 let fail = target_block(TestBranch::Failure);
271 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
272 let val = Operand::Copy(place);
273
274 let intermediate_block = if !range.lo.is_finite() {
275 block
276 } else if !range.hi.is_finite() {
277 success
278 } else {
279 self.cfg.start_new_block()
280 };
281
282 if let Some(lo) = range.lo.as_finite() {
283 let lo = ty::Value { ty: range.ty, valtree: lo };
284 let lo = self.literal_operand(test.span, Const::from_ty_value(self.tcx, lo));
285 self.compare(
286 block,
287 intermediate_block,
288 fail,
289 source_info,
290 BinOp::Le,
291 lo,
292 val.clone(),
293 );
294 };
295
296 if let Some(hi) = range.hi.as_finite() {
297 let hi = ty::Value { ty: range.ty, valtree: hi };
298 let hi = self.literal_operand(test.span, Const::from_ty_value(self.tcx, hi));
299 let op = match range.end {
300 RangeEnd::Included => BinOp::Le,
301 RangeEnd::Excluded => BinOp::Lt,
302 };
303 self.compare(intermediate_block, success, fail, source_info, op, val, hi);
304 }
305 }
306
307 TestKind::Len { len, op } => {
308 let usize_ty = self.tcx.types.usize;
309 let actual = self.temp(usize_ty, test.span);
310
311 // actual = len(place)
312 self.cfg.push_assign(block, source_info, actual, Rvalue::Len(place));
313
314 // expected = <N>
315 let expected = self.push_usize(block, source_info, len);
316
317 let success_block = target_block(TestBranch::Success);
318 let fail_block = target_block(TestBranch::Failure);
319 // result = actual == expected OR result = actual < expected
320 // branch based on result
321 self.compare(
322 block,
323 success_block,
324 fail_block,
325 source_info,
326 op,
327 Operand::Move(actual),
328 Operand::Move(expected),
329 );
330 }
331
332 TestKind::Deref { temp, mutability } => {
333 let ty = place_ty.ty;
334 let target = target_block(TestBranch::Success);
335 self.call_deref(block, target, place, mutability, ty, temp, test.span);
336 }
337
338 TestKind::Never => {
339 // Check that the place is initialized.
340 // FIXME(never_patterns): Also assert validity of the data at `place`.
341 self.cfg.push_fake_read(
342 block,
343 source_info,
344 FakeReadCause::ForMatchedPlace(None),
345 place,
346 );
347 // A never pattern is only allowed on an uninhabited type, so validity of the data
348 // implies unreachability.
349 self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
350 }
351 }
352 }
353
354 /// Perform `let temp = <ty as Deref>::deref(&place)`.
355 /// or `let temp = <ty as DerefMut>::deref_mut(&mut place)`.
356 pub(super) fn call_deref(
357 &mut self,
358 block: BasicBlock,
359 target_block: BasicBlock,
360 place: Place<'tcx>,
361 mutability: Mutability,
362 ty: Ty<'tcx>,
363 temp: Place<'tcx>,
364 span: Span,
365 ) {
366 let (trait_item, method) = match mutability {
367 Mutability::Not => (LangItem::Deref, sym::deref),
368 Mutability::Mut => (LangItem::DerefMut, sym::deref_mut),
369 };
370 let borrow_kind = super::util::ref_pat_borrow_kind(mutability);
371 let source_info = self.source_info(span);
372 let re_erased = self.tcx.lifetimes.re_erased;
373 let trait_item = self.tcx.require_lang_item(trait_item, span);
374 let method = trait_method(self.tcx, trait_item, method, [ty]);
375 let ref_src = self.temp(Ty::new_ref(self.tcx, re_erased, ty, mutability), span);
376 // `let ref_src = &src_place;`
377 // or `let ref_src = &mut src_place;`
378 self.cfg.push_assign(
379 block,
380 source_info,
381 ref_src,
382 Rvalue::Ref(re_erased, borrow_kind, place),
383 );
384 // `let temp = <Ty as Deref>::deref(ref_src);`
385 // or `let temp = <Ty as DerefMut>::deref_mut(ref_src);`
386 self.cfg.terminate(
387 block,
388 source_info,
389 TerminatorKind::Call {
390 func: Operand::Constant(Box::new(ConstOperand {
391 span,
392 user_ty: None,
393 const_: method,
394 })),
395 args: [Spanned { node: Operand::Move(ref_src), span }].into(),
396 destination: temp,
397 target: Some(target_block),
398 unwind: UnwindAction::Continue,
399 call_source: CallSource::Misc,
400 fn_span: source_info.span,
401 },
402 );
403 }
404
405 /// Compare using the provided built-in comparison operator
406 fn compare(
407 &mut self,
408 block: BasicBlock,
409 success_block: BasicBlock,
410 fail_block: BasicBlock,
411 source_info: SourceInfo,
412 op: BinOp,
413 left: Operand<'tcx>,
414 right: Operand<'tcx>,
415 ) {
416 let bool_ty = self.tcx.types.bool;
417 let result = self.temp(bool_ty, source_info.span);
418
419 // result = op(left, right)
420 self.cfg.push_assign(
421 block,
422 source_info,
423 result,
424 Rvalue::BinaryOp(op, Box::new((left, right))),
425 );
426
427 // branch based on result
428 self.cfg.terminate(
429 block,
430 source_info,
431 TerminatorKind::if_(Operand::Move(result), success_block, fail_block),
432 );
433 }
434
435 /// Compare two values of type `&str` using `<str as std::cmp::PartialEq>::eq`.
436 fn string_compare(
437 &mut self,
438 block: BasicBlock,
439 success_block: BasicBlock,
440 fail_block: BasicBlock,
441 source_info: SourceInfo,
442 expect: Operand<'tcx>,
443 val: Operand<'tcx>,
444 ) {
445 let str_ty = self.tcx.types.str_;
446 let eq_def_id = self.tcx.require_lang_item(LangItem::PartialEq, source_info.span);
447 let method = trait_method(self.tcx, eq_def_id, sym::eq, [str_ty, str_ty]);
448
449 let bool_ty = self.tcx.types.bool;
450 let eq_result = self.temp(bool_ty, source_info.span);
451 let eq_block = self.cfg.start_new_block();
452 self.cfg.terminate(
453 block,
454 source_info,
455 TerminatorKind::Call {
456 func: Operand::Constant(Box::new(ConstOperand {
457 span: source_info.span,
458
459 // FIXME(#54571): This constant comes from user input (a
460 // constant in a pattern). Are there forms where users can add
461 // type annotations here? For example, an associated constant?
462 // Need to experiment.
463 user_ty: None,
464
465 const_: method,
466 })),
467 args: [
468 Spanned { node: val, span: DUMMY_SP },
469 Spanned { node: expect, span: DUMMY_SP },
470 ]
471 .into(),
472 destination: eq_result,
473 target: Some(eq_block),
474 unwind: UnwindAction::Continue,
475 call_source: CallSource::MatchCmp,
476 fn_span: source_info.span,
477 },
478 );
479 self.diverge_from(block);
480
481 // check the result
482 self.cfg.terminate(
483 eq_block,
484 source_info,
485 TerminatorKind::if_(Operand::Move(eq_result), success_block, fail_block),
486 );
487 }
488
489 /// Given that we are performing `test` against `test_place`, this job
490 /// sorts out what the status of `candidate` will be after the test. See
491 /// `test_candidates` for the usage of this function. The candidate may
492 /// be modified to update its `match_pairs`.
493 ///
494 /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
495 /// a variant test, then we would modify the candidate to be `(x as
496 /// Option).0 @ P0` and return the index corresponding to the variant
497 /// `Some`.
498 ///
499 /// However, in some cases, the test may just not be relevant to candidate.
500 /// For example, suppose we are testing whether `foo.x == 22`, but in one
501 /// match arm we have `Foo { x: _, ... }`... in that case, the test for
502 /// the value of `x` has no particular relevance to this candidate. In
503 /// such cases, this function just returns None without doing anything.
504 /// This is used by the overall `match_candidates` algorithm to structure
505 /// the match as a whole. See `match_candidates` for more details.
506 ///
507 /// FIXME(#29623). In some cases, we have some tricky choices to make. for
508 /// example, if we are testing that `x == 22`, but the candidate is `x @
509 /// 13..55`, what should we do? In the event that the test is true, we know
510 /// that the candidate applies, but in the event of false, we don't know
511 /// that it *doesn't* apply. For now, we return false, indicate that the
512 /// test does not apply to this candidate, but it might be we can get
513 /// tighter match code if we do something a bit different.
514 pub(super) fn sort_candidate(
515 &mut self,
516 test_place: Place<'tcx>,
517 test: &Test<'tcx>,
518 candidate: &mut Candidate<'tcx>,
519 sorted_candidates: &FxIndexMap<TestBranch<'tcx>, Vec<&mut Candidate<'tcx>>>,
520 ) -> Option<TestBranch<'tcx>> {
521 // Find the match_pair for this place (if any). At present,
522 // afaik, there can be at most one. (In the future, if we
523 // adopted a more general `@` operator, there might be more
524 // than one, but it'd be very unusual to have two sides that
525 // both require tests; you'd expect one side to be simplified
526 // away.)
527 let (match_pair_index, match_pair) = candidate
528 .match_pairs
529 .iter()
530 .enumerate()
531 .find(|&(_, mp)| mp.place == Some(test_place))?;
532
533 // If true, the match pair is completely entailed by its corresponding test
534 // branch, so it can be removed. If false, the match pair is _compatible_
535 // with its test branch, but still needs a more specific test.
536 let fully_matched;
537 let ret = match (&test.kind, &match_pair.test_case) {
538 // If we are performing a variant switch, then this
539 // informs variant patterns, but nothing else.
540 (
541 &TestKind::Switch { adt_def: tested_adt_def },
542 &TestCase::Variant { adt_def, variant_index },
543 ) => {
544 assert_eq!(adt_def, tested_adt_def);
545 fully_matched = true;
546 Some(TestBranch::Variant(variant_index))
547 }
548
549 // If we are performing a switch over integers, then this informs integer
550 // equality, but nothing else.
551 //
552 // FIXME(#29623) we could use PatKind::Range to rule
553 // things out here, in some cases.
554 (TestKind::SwitchInt, &TestCase::Constant { value })
555 if is_switch_ty(match_pair.pattern_ty) =>
556 {
557 // An important invariant of candidate sorting is that a candidate
558 // must not match in multiple branches. For `SwitchInt` tests, adding
559 // a new value might invalidate that property for range patterns that
560 // have already been sorted into the failure arm, so we must take care
561 // not to add such values here.
562 let is_covering_range = |test_case: &TestCase<'tcx>| {
563 test_case.as_range().is_some_and(|range| {
564 matches!(range.contains(value, self.tcx), None | Some(true))
565 })
566 };
567 let is_conflicting_candidate = |candidate: &&mut Candidate<'tcx>| {
568 candidate
569 .match_pairs
570 .iter()
571 .any(|mp| mp.place == Some(test_place) && is_covering_range(&mp.test_case))
572 };
573 if sorted_candidates
574 .get(&TestBranch::Failure)
575 .is_some_and(|candidates| candidates.iter().any(is_conflicting_candidate))
576 {
577 fully_matched = false;
578 None
579 } else {
580 fully_matched = true;
581 Some(TestBranch::Constant(value))
582 }
583 }
584 (TestKind::SwitchInt, TestCase::Range(range)) => {
585 // When performing a `SwitchInt` test, a range pattern can be
586 // sorted into the failure arm if it doesn't contain _any_ of
587 // the values being tested. (This restricts what values can be
588 // added to the test by subsequent candidates.)
589 fully_matched = false;
590 let not_contained = sorted_candidates
591 .keys()
592 .filter_map(|br| br.as_constant())
593 .all(|val| matches!(range.contains(val, self.tcx), Some(false)));
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_to_bool().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)? { Some(TestBranch::Failure) } else { None }
685 }
686 }
687 (TestKind::Range(range), &TestCase::Constant { value }) => {
688 fully_matched = false;
689 if !range.contains(value, self.tcx)? {
690 // `value` is not contained in the testing range,
691 // so `value` can be matched only if this test fails.
692 Some(TestBranch::Failure)
693 } else {
694 None
695 }
696 }
697
698 (TestKind::Eq { value: test_val, .. }, TestCase::Constant { value: case_val }) => {
699 if test_val == case_val {
700 fully_matched = true;
701 Some(TestBranch::Success)
702 } else {
703 fully_matched = false;
704 Some(TestBranch::Failure)
705 }
706 }
707
708 (TestKind::Deref { temp: test_temp, .. }, TestCase::Deref { temp, .. })
709 if test_temp == temp =>
710 {
711 fully_matched = true;
712 Some(TestBranch::Success)
713 }
714
715 (TestKind::Never, _) => {
716 fully_matched = true;
717 Some(TestBranch::Success)
718 }
719
720 (
721 TestKind::Switch { .. }
722 | TestKind::SwitchInt { .. }
723 | TestKind::If
724 | TestKind::Len { .. }
725 | TestKind::Range { .. }
726 | TestKind::Eq { .. }
727 | TestKind::Deref { .. },
728 _,
729 ) => {
730 fully_matched = false;
731 None
732 }
733 };
734
735 if fully_matched {
736 // Replace the match pair by its sub-pairs.
737 let match_pair = candidate.match_pairs.remove(match_pair_index);
738 candidate.match_pairs.extend(match_pair.subpairs);
739 // Move or-patterns to the end.
740 candidate.sort_match_pairs();
741 }
742
743 ret
744 }
745}
746
747fn is_switch_ty(ty: Ty<'_>) -> bool {
748 ty.is_integral() || ty.is_char()
749}
750
751fn trait_method<'tcx>(
752 tcx: TyCtxt<'tcx>,
753 trait_def_id: DefId,
754 method_name: Symbol,
755 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
756) -> Const<'tcx> {
757 // The unhygienic comparison here is acceptable because this is only
758 // used on known traits.
759 let item = tcx
760 .associated_items(trait_def_id)
761 .filter_by_name_unhygienic(method_name)
762 .find(|item| item.is_fn())
763 .expect("trait method not found");
764
765 let method_ty = Ty::new_fn_def(tcx, item.def_id, args);
766
767 Const::zero_sized(method_ty)
768}