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.
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::util::IntTypeExt;
18 use rustc_middle::ty::GenericArg;
19 use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
20 use rustc_span::def_id::DefId;
21 use rustc_span::symbol::{sym, Symbol};
23 use rustc_target::abi::VariantIdx;
25 use std::cmp::Ordering;
27 impl<'a, 'tcx> Builder<'a, 'tcx> {
28 /// Identifies what test is needed to decide if `match_pair` is applicable.
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 {
37 variants: BitSet::new_empty(adt_def.variants().len()),
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.
45 span: match_pair.pattern.span,
46 kind: TestKind::SwitchInt {
47 switch_ty: match_pair.pattern.ty,
49 // these maps are empty to start; cases are
50 // added below in add_cases_to_switch
51 options: Default::default(),
56 PatKind::Constant { value } => Test {
57 span: match_pair.pattern.span,
58 kind: TestKind::Eq { value, ty: match_pair.pattern.ty },
61 PatKind::Range(ref 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.clone()) }
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 } }
73 PatKind::Or { .. } => bug!("or-patterns should have already been handled"),
75 PatKind::AscribeUserType { .. }
76 | PatKind::Array { .. }
78 | PatKind::Binding { .. }
79 | PatKind::Leaf { .. }
80 | PatKind::Deref { .. } => self.error_simplifyable(match_pair),
84 pub(super) fn add_cases_to_switch<'pat>(
86 test_place: &PlaceBuilder<'tcx>,
87 candidate: &Candidate<'pat, 'tcx>,
89 options: &mut FxIndexMap<ConstantKind<'tcx>, u128>,
91 let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else {
95 match match_pair.pattern.kind {
96 PatKind::Constant { value } => {
99 .or_insert_with(|| value.eval_bits(self.tcx, self.param_env, switch_ty));
102 PatKind::Variant { .. } => {
103 panic!("you should have called add_variants_to_switch instead!");
105 PatKind::Range(ref 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)
109 PatKind::Slice { .. }
110 | PatKind::Array { .. }
113 | PatKind::Binding { .. }
114 | PatKind::AscribeUserType { .. }
115 | PatKind::Leaf { .. }
116 | PatKind::Deref { .. } => {
117 // don't know how to add these patterns to a switch
123 pub(super) fn add_variants_to_switch<'pat>(
125 test_place: &PlaceBuilder<'tcx>,
126 candidate: &Candidate<'pat, 'tcx>,
127 variants: &mut BitSet<VariantIdx>,
129 let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else {
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);
141 // don't know how to add these patterns to a switch
147 #[instrument(skip(self, make_target_blocks, place_builder), level = "debug")]
148 pub(super) fn perform_test(
150 match_start_span: Span,
151 scrutinee_span: Span,
153 place_builder: &PlaceBuilder<'tcx>,
155 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
157 let place = place_builder.to_place(self);
158 let place_ty = place.ty(&self.local_decls, self.tcx);
159 debug!(?place, ?place_ty,);
161 let source_info = self.source_info(test.span);
163 TestKind::Switch { adt_def, ref variants } => {
164 let target_blocks = make_target_blocks(self);
165 // Variants is a BitVec of indexes into adt_def.variants.
166 let num_enum_variants = adt_def.variants().len();
167 debug_assert_eq!(target_blocks.len(), num_enum_variants + 1);
168 let otherwise_block = *target_blocks.last().unwrap();
170 let switch_targets = SwitchTargets::new(
171 adt_def.discriminants(tcx).filter_map(|(idx, discr)| {
172 if variants.contains(idx) {
174 target_blocks[idx.index()],
176 "no canididates for tested discriminant: {:?}",
179 Some((discr.val, target_blocks[idx.index()]))
182 target_blocks[idx.index()],
184 "found canididates for untested discriminant: {:?}",
192 debug!("num_enum_variants: {}, variants: {:?}", num_enum_variants, variants);
193 let discr_ty = adt_def.repr().discr_type().to_ty(tcx);
194 let discr = self.temp(discr_ty, test.span);
195 self.cfg.push_assign(
197 self.source_info(scrutinee_span),
199 Rvalue::Discriminant(place),
203 self.source_info(match_start_span),
204 TerminatorKind::SwitchInt {
205 discr: Operand::Move(discr),
207 targets: switch_targets,
212 TestKind::SwitchInt { switch_ty, ref options } => {
213 let target_blocks = make_target_blocks(self);
214 let terminator = if *switch_ty.kind() == ty::Bool {
215 assert!(!options.is_empty() && options.len() <= 2);
216 let [first_bb, second_bb] = *target_blocks else {
217 bug!("`TestKind::SwitchInt` on `bool` should have two targets")
219 let (true_bb, false_bb) = match options[0] {
220 1 => (first_bb, second_bb),
221 0 => (second_bb, first_bb),
222 v => span_bug!(test.span, "expected boolean value but got {:?}", v),
224 TerminatorKind::if_(self.tcx, Operand::Copy(place), true_bb, false_bb)
226 // The switch may be inexhaustive so we have a catch all block
227 debug_assert_eq!(options.len() + 1, target_blocks.len());
228 let otherwise_block = *target_blocks.last().unwrap();
229 let switch_targets = SwitchTargets::new(
230 options.values().copied().zip(target_blocks),
233 TerminatorKind::SwitchInt {
234 discr: Operand::Copy(place),
236 targets: switch_targets,
239 self.cfg.terminate(block, self.source_info(match_start_span), terminator);
242 TestKind::Eq { value, ty } => {
244 if let ty::Adt(def, _) = ty.kind() && Some(def.did()) == tcx.lang_items().string() {
245 if !tcx.features().string_deref_patterns {
246 bug!("matching on `String` went through without enabling string_deref_patterns");
248 let re_erased = tcx.lifetimes.re_erased;
249 let ref_string = self.temp(tcx.mk_imm_ref(re_erased, ty), test.span);
250 let ref_str_ty = tcx.mk_imm_ref(re_erased, tcx.types.str_);
251 let ref_str = self.temp(ref_str_ty, test.span);
252 let deref = tcx.require_lang_item(LangItem::Deref, None);
253 let method = trait_method(tcx, deref, sym::deref, [ty]);
254 let eq_block = self.cfg.start_new_block();
255 self.cfg.push_assign(block, source_info, ref_string, Rvalue::Ref(re_erased, BorrowKind::Shared, place));
259 TerminatorKind::Call {
260 func: Operand::Constant(Box::new(Constant {
265 args: vec![Operand::Move(ref_string)],
266 destination: ref_str,
267 target: Some(eq_block),
269 from_hir_call: false,
270 fn_span: source_info.span
273 self.non_scalar_compare(eq_block, make_target_blocks, source_info, value, ref_str, ref_str_ty);
277 // Use `PartialEq::eq` instead of `BinOp::Eq`
278 // (the binop can only handle primitives)
279 self.non_scalar_compare(
287 } else if let [success, fail] = *make_target_blocks(self) {
288 assert_eq!(value.ty(), ty);
289 let expect = self.literal_operand(test.span, value);
290 let val = Operand::Copy(place);
291 self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
293 bug!("`TestKind::Eq` should have two target blocks");
297 TestKind::Range(box PatRange { lo, hi, ref end }) => {
298 let lower_bound_success = self.cfg.start_new_block();
299 let target_blocks = make_target_blocks(self);
301 // Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
302 let lo = self.literal_operand(test.span, lo);
303 let hi = self.literal_operand(test.span, hi);
304 let val = Operand::Copy(place);
306 let [success, fail] = *target_blocks else {
307 bug!("`TestKind::Range` should have two target blocks");
318 let op = match *end {
319 RangeEnd::Included => BinOp::Le,
320 RangeEnd::Excluded => BinOp::Lt,
322 self.compare(lower_bound_success, success, fail, source_info, op, val, hi);
325 TestKind::Len { len, op } => {
326 let target_blocks = make_target_blocks(self);
328 let usize_ty = self.tcx.types.usize;
329 let actual = self.temp(usize_ty, test.span);
331 // actual = len(place)
332 self.cfg.push_assign(block, source_info, actual, Rvalue::Len(place));
335 let expected = self.push_usize(block, source_info, len);
337 let [true_bb, false_bb] = *target_blocks else {
338 bug!("`TestKind::Len` should have two target blocks");
340 // result = actual == expected OR result = actual < expected
341 // branch based on result
348 Operand::Move(actual),
349 Operand::Move(expected),
355 /// Compare using the provided built-in comparison operator
359 success_block: BasicBlock,
360 fail_block: BasicBlock,
361 source_info: SourceInfo,
364 right: Operand<'tcx>,
366 let bool_ty = self.tcx.types.bool;
367 let result = self.temp(bool_ty, source_info.span);
369 // result = op(left, right)
370 self.cfg.push_assign(
374 Rvalue::BinaryOp(op, Box::new((left, right))),
377 // branch based on result
381 TerminatorKind::if_(self.tcx, Operand::Move(result), success_block, fail_block),
385 /// Compare two `&T` values using `<T as std::compare::PartialEq>::eq`
386 fn non_scalar_compare(
389 make_target_blocks: impl FnOnce(&mut Self) -> Vec<BasicBlock>,
390 source_info: SourceInfo,
391 value: ConstantKind<'tcx>,
395 let mut expect = self.literal_operand(source_info.span, value);
396 let mut val = Operand::Copy(place);
398 // If we're using `b"..."` as a pattern, we need to insert an
399 // unsizing coercion, as the byte string has the type `&[u8; N]`.
401 // We want to do this even when the scrutinee is a reference to an
402 // array, so we can call `<[u8]>::eq` rather than having to find an
404 let unsize = |ty: Ty<'tcx>| match ty.kind() {
405 ty::Ref(region, rty, _) => match rty.kind() {
406 ty::Array(inner_ty, n) => Some((region, inner_ty, n)),
411 let opt_ref_ty = unsize(ty);
412 let opt_ref_test_ty = unsize(value.ty());
413 match (opt_ref_ty, opt_ref_test_ty) {
414 // nothing to do, neither is an array
416 (Some((region, elem_ty, _)), _) | (None, Some((region, elem_ty, _))) => {
419 ty = tcx.mk_imm_ref(*region, tcx.mk_slice(*elem_ty));
420 if opt_ref_ty.is_some() {
421 let temp = self.temp(ty, source_info.span);
422 self.cfg.push_assign(
426 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), val, ty),
428 val = Operand::Move(temp);
430 if opt_ref_test_ty.is_some() {
431 let slice = self.temp(ty, source_info.span);
432 self.cfg.push_assign(
436 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), expect, ty),
438 expect = Operand::Move(slice);
443 let ty::Ref(_, deref_ty, _) = *ty.kind() else {
444 bug!("non_scalar_compare called on non-reference type: {}", ty);
447 let eq_def_id = self.tcx.require_lang_item(LangItem::PartialEq, Some(source_info.span));
448 let method = trait_method(self.tcx, eq_def_id, sym::eq, [deref_ty, deref_ty]);
450 let bool_ty = self.tcx.types.bool;
451 let eq_result = self.temp(bool_ty, source_info.span);
452 let eq_block = self.cfg.start_new_block();
456 TerminatorKind::Call {
457 func: Operand::Constant(Box::new(Constant {
458 span: source_info.span,
460 // FIXME(#54571): This constant comes from user input (a
461 // constant in a pattern). Are there forms where users can add
462 // type annotations here? For example, an associated constant?
463 // Need to experiment.
468 args: vec![val, expect],
469 destination: eq_result,
470 target: Some(eq_block),
472 from_hir_call: false,
473 fn_span: source_info.span,
476 self.diverge_from(block);
478 let [success_block, fail_block] = *make_target_blocks(self) else {
479 bug!("`TestKind::Eq` should have two target blocks")
485 TerminatorKind::if_(self.tcx, Operand::Move(eq_result), success_block, fail_block),
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 returned index is
492 /// the index that this candidate should be placed in the
493 /// `target_candidates` vec. The candidate may be modified to update its
496 /// So, for example, if this candidate is `x @ Some(P0)` and the `Test` is
497 /// a variant test, then we would modify the candidate to be `(x as
498 /// Option).0 @ P0` and return the index corresponding to the variant
501 /// However, in some cases, the test may just not be relevant to candidate.
502 /// For example, suppose we are testing whether `foo.x == 22`, but in one
503 /// match arm we have `Foo { x: _, ... }`... in that case, the test for
504 /// what value `x` has has no particular relevance to this candidate. In
505 /// such cases, this function just returns None without doing anything.
506 /// This is used by the overall `match_candidates` algorithm to structure
507 /// the match as a whole. See `match_candidates` for more details.
509 /// FIXME(#29623). In some cases, we have some tricky choices to make. for
510 /// example, if we are testing that `x == 22`, but the candidate is `x @
511 /// 13..55`, what should we do? In the event that the test is true, we know
512 /// that the candidate applies, but in the event of false, we don't know
513 /// that it *doesn't* apply. For now, we return false, indicate that the
514 /// test does not apply to this candidate, but it might be we can get
515 /// tighter match code if we do something a bit different.
516 pub(super) fn sort_candidate<'pat>(
518 test_place: &PlaceBuilder<'tcx>,
520 candidate: &mut Candidate<'pat, 'tcx>,
522 // Find the match_pair for this place (if any). At present,
523 // afaik, there can be at most one. (In the future, if we
524 // adopted a more general `@` operator, there might be more
525 // than one, but it'd be very unusual to have two sides that
526 // both require tests; you'd expect one side to be simplified
528 let (match_pair_index, match_pair) =
529 candidate.match_pairs.iter().enumerate().find(|&(_, mp)| mp.place == *test_place)?;
531 match (&test.kind, &match_pair.pattern.kind) {
532 // If we are performing a variant switch, then this
533 // informs variant patterns, but nothing else.
535 &TestKind::Switch { adt_def: tested_adt_def, .. },
536 &PatKind::Variant { adt_def, variant_index, ref subpatterns, .. },
538 assert_eq!(adt_def, tested_adt_def);
539 self.candidate_after_variant_switch(
546 Some(variant_index.as_usize())
549 (&TestKind::Switch { .. }, _) => None,
551 // If we are performing a switch over integers, then this informs integer
552 // equality, but nothing else.
554 // FIXME(#29623) we could use PatKind::Range to rule
555 // things out here, in some cases.
557 &TestKind::SwitchInt { switch_ty: _, ref options },
558 &PatKind::Constant { ref value },
559 ) if is_switch_ty(match_pair.pattern.ty) => {
560 let index = options.get_index_of(value).unwrap();
561 self.candidate_without_match_pair(match_pair_index, candidate);
565 (&TestKind::SwitchInt { switch_ty: _, ref options }, &PatKind::Range(ref range)) => {
567 self.values_not_contained_in_range(&*range, options).unwrap_or(false);
570 // No switch values are contained in the pattern range,
571 // so the pattern can be matched only if this test fails.
572 let otherwise = options.len();
579 (&TestKind::SwitchInt { .. }, _) => None,
582 &TestKind::Len { len: test_len, op: BinOp::Eq },
583 &PatKind::Slice { ref prefix, ref slice, ref suffix },
585 let pat_len = (prefix.len() + suffix.len()) as u64;
586 match (test_len.cmp(&pat_len), slice) {
587 (Ordering::Equal, &None) => {
588 // on true, min_len = len = $actual_length,
589 // on false, len != $actual_length
590 self.candidate_after_slice_test(
599 (Ordering::Less, _) => {
600 // test_len < pat_len. If $actual_len = test_len,
601 // then $actual_len < pat_len and we don't have
605 (Ordering::Equal | Ordering::Greater, &Some(_)) => {
606 // This can match both if $actual_len = test_len >= pat_len,
607 // and if $actual_len > test_len. We can't advance.
610 (Ordering::Greater, &None) => {
611 // test_len != pat_len, so if $actual_len = test_len, then
612 // $actual_len != pat_len.
619 &TestKind::Len { len: test_len, op: BinOp::Ge },
620 &PatKind::Slice { ref prefix, ref slice, ref suffix },
622 // the test is `$actual_len >= test_len`
623 let pat_len = (prefix.len() + suffix.len()) as u64;
624 match (test_len.cmp(&pat_len), slice) {
625 (Ordering::Equal, &Some(_)) => {
626 // $actual_len >= test_len = pat_len,
628 self.candidate_after_slice_test(
637 (Ordering::Less, _) | (Ordering::Equal, &None) => {
638 // test_len <= pat_len. If $actual_len < test_len,
639 // then it is also < pat_len, so the test passing is
640 // necessary (but insufficient).
643 (Ordering::Greater, &None) => {
644 // test_len > pat_len. If $actual_len >= test_len > pat_len,
645 // then we know we won't have a match.
648 (Ordering::Greater, &Some(_)) => {
649 // test_len < pat_len, and is therefore less
650 // strict. This can still go both ways.
656 (&TestKind::Range(ref test), &PatKind::Range(ref pat)) => {
657 use std::cmp::Ordering::*;
660 self.candidate_without_match_pair(match_pair_index, candidate);
664 // For performance, it's important to only do the second
665 // `compare_const_vals` if necessary.
666 let no_overlap = if matches!(
667 (compare_const_vals(self.tcx, test.hi, pat.lo, self.param_env)?, test.end),
668 (Less, _) | (Equal, RangeEnd::Excluded) // test < pat
670 (compare_const_vals(self.tcx, test.lo, pat.hi, self.param_env)?, pat.end),
671 (Greater, _) | (Equal, RangeEnd::Excluded) // test > pat
678 // If the testing range does not overlap with pattern range,
679 // the pattern can be matched only if this test fails.
683 (&TestKind::Range(ref range), &PatKind::Constant { value }) => {
684 if let Some(false) = self.const_range_contains(&*range, value) {
685 // `value` is not contained in the testing range,
686 // so `value` can be matched only if this test fails.
693 (&TestKind::Range { .. }, _) => None,
695 (&TestKind::Eq { .. } | &TestKind::Len { .. }, _) => {
696 // The call to `self.test(&match_pair)` below is not actually used to generate any
697 // MIR. Instead, we just want to compare with `test` (the parameter of the method)
698 // to see if it is the same.
700 // However, at this point we can still encounter or-patterns that were extracted
701 // from previous calls to `sort_candidate`, so we need to manually address that
702 // case to avoid panicking in `self.test()`.
703 if let PatKind::Or { .. } = &match_pair.pattern.kind {
707 // These are all binary tests.
709 // FIXME(#29623) we can be more clever here
710 let pattern_test = self.test(&match_pair);
711 if pattern_test.kind == test.kind {
712 self.candidate_without_match_pair(match_pair_index, candidate);
721 fn candidate_without_match_pair(
723 match_pair_index: usize,
724 candidate: &mut Candidate<'_, 'tcx>,
726 candidate.match_pairs.remove(match_pair_index);
729 fn candidate_after_slice_test<'pat>(
731 match_pair_index: usize,
732 candidate: &mut Candidate<'pat, 'tcx>,
733 prefix: &'pat [Box<Pat<'tcx>>],
734 opt_slice: &'pat Option<Box<Pat<'tcx>>>,
735 suffix: &'pat [Box<Pat<'tcx>>],
737 let removed_place = candidate.match_pairs.remove(match_pair_index).place;
738 self.prefix_slice_suffix(
739 &mut candidate.match_pairs,
747 fn candidate_after_variant_switch<'pat>(
749 match_pair_index: usize,
750 adt_def: ty::AdtDef<'tcx>,
751 variant_index: VariantIdx,
752 subpatterns: &'pat [FieldPat<'tcx>],
753 candidate: &mut Candidate<'pat, 'tcx>,
755 let match_pair = candidate.match_pairs.remove(match_pair_index);
757 // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`,
758 // we want to create a set of derived match-patterns like
759 // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`.
760 let downcast_place = match_pair.place.downcast(adt_def, variant_index); // `(x as Variant)`
761 let consequent_match_pairs = subpatterns.iter().map(|subpattern| {
762 // e.g., `(x as Variant).0`
763 let place = downcast_place
764 .clone_project(PlaceElem::Field(subpattern.field, subpattern.pattern.ty));
765 // e.g., `(x as Variant).0 @ P1`
766 MatchPair::new(place, &subpattern.pattern, self)
769 candidate.match_pairs.extend(consequent_match_pairs);
772 fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! {
773 span_bug!(match_pair.pattern.span, "simplifyable pattern found: {:?}", match_pair.pattern)
776 fn const_range_contains(
778 range: &PatRange<'tcx>,
779 value: ConstantKind<'tcx>,
781 use std::cmp::Ordering::*;
783 // For performance, it's important to only do the second
784 // `compare_const_vals` if necessary.
786 matches!(compare_const_vals(self.tcx, range.lo, value, self.param_env)?, Less | Equal)
788 (compare_const_vals(self.tcx, value, range.hi, self.param_env)?, range.end),
789 (Less, _) | (Equal, RangeEnd::Included)
794 fn values_not_contained_in_range(
796 range: &PatRange<'tcx>,
797 options: &FxIndexMap<ConstantKind<'tcx>, u128>,
799 for &val in options.keys() {
800 if self.const_range_contains(range, val)? {
810 pub(super) fn targets(&self) -> usize {
812 TestKind::Eq { .. } | TestKind::Range(_) | TestKind::Len { .. } => 2,
813 TestKind::Switch { adt_def, .. } => {
814 // While the switch that we generate doesn't test for all
815 // variants, we have a target for each variant and the
816 // otherwise case, and we make sure that all of the cases not
817 // specified have the same block.
818 adt_def.variants().len() + 1
820 TestKind::SwitchInt { switch_ty, ref options, .. } => {
821 if switch_ty.is_bool() {
822 // `bool` is special cased in `perform_test` to always
823 // branch to two blocks.
833 fn is_switch_ty(ty: Ty<'_>) -> bool {
834 ty.is_integral() || ty.is_char() || ty.is_bool()
837 fn trait_method<'tcx>(
841 substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
842 ) -> ConstantKind<'tcx> {
843 let substs = tcx.mk_substs(substs.into_iter().map(Into::into));
845 // The unhygienic comparison here is acceptable because this is only
846 // used on known traits.
848 .associated_items(trait_def_id)
849 .filter_by_name_unhygienic(method_name)
850 .find(|item| item.kind == ty::AssocKind::Fn)
851 .expect("trait method not found");
853 let method_ty = tcx.mk_fn_def(item.def_id, substs);
855 ConstantKind::zero_sized(method_ty)