1 //! Validation of patterns/matches.
8 pub(crate) use self::check_match::check_match;
10 use crate::thir::util::UserAnnotatedTyHelpers;
12 use rustc_errors::struct_span_err;
14 use rustc_hir::def::{CtorOf, DefKind, Res};
15 use rustc_hir::pat_util::EnumerateAndAdjustIterator;
16 use rustc_hir::RangeEnd;
17 use rustc_index::vec::Idx;
18 use rustc_middle::mir::interpret::{
19 ConstValue, ErrorHandled, LitToConstError, LitToConstInput, Scalar,
21 use rustc_middle::mir::{self, UserTypeProjection};
22 use rustc_middle::mir::{BorrowKind, Field, Mutability};
23 use rustc_middle::thir::{Ascription, BindingMode, FieldPat, LocalVarId, Pat, PatKind, PatRange};
24 use rustc_middle::ty::subst::{GenericArg, SubstsRef};
25 use rustc_middle::ty::CanonicalUserTypeAnnotation;
26 use rustc_middle::ty::{self, AdtDef, ConstKind, DefIdTree, Region, Ty, TyCtxt, UserType};
27 use rustc_span::{Span, Symbol};
29 use std::cmp::Ordering;
31 #[derive(Clone, Debug)]
33 AssocConstInPattern(Span),
34 ConstParamInPattern(Span),
35 StaticInPattern(Span),
39 struct PatCtxt<'a, 'tcx> {
41 param_env: ty::ParamEnv<'tcx>,
42 typeck_results: &'a ty::TypeckResults<'tcx>,
43 errors: Vec<PatternError>,
44 include_lint_checks: bool,
47 pub(super) fn pat_from_hir<'a, 'tcx>(
49 param_env: ty::ParamEnv<'tcx>,
50 typeck_results: &'a ty::TypeckResults<'tcx>,
51 pat: &'tcx hir::Pat<'tcx>,
53 let mut pcx = PatCtxt::new(tcx, param_env, typeck_results);
54 let result = pcx.lower_pattern(pat);
55 if !pcx.errors.is_empty() {
56 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
57 tcx.sess.delay_span_bug(pat.span, &msg);
59 debug!("pat_from_hir({:?}) = {:?}", pat, result);
63 impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
66 param_env: ty::ParamEnv<'tcx>,
67 typeck_results: &'a ty::TypeckResults<'tcx>,
69 PatCtxt { tcx, param_env, typeck_results, errors: vec![], include_lint_checks: false }
72 fn include_lint_checks(&mut self) -> &mut Self {
73 self.include_lint_checks = true;
77 fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
78 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
79 // pattern has the type that results *after* dereferencing. For example, in this code:
82 // match &&Some(0i32) {
83 // Some(n) => { ... },
88 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
89 // determined in rustc_typeck::check::match). The adjustments would be
91 // `vec![&&Option<i32>, &Option<i32>]`.
93 // Applying the adjustments, we want to instead output `&&Some(n)` (as a THIR pattern). So
94 // we wrap the unadjusted pattern in `PatKind::Deref` repeatedly, consuming the
95 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
96 // gets the least-dereferenced type).
97 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
98 self.typeck_results.pat_adjustments().get(pat.hir_id).unwrap_or(&vec![]).iter().rev().fold(
100 |pat: Box<_>, ref_ty| {
101 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
105 kind: PatKind::Deref { subpattern: pat },
113 expr: &'tcx hir::Expr<'tcx>,
114 ) -> (PatKind<'tcx>, Option<Ascription<'tcx>>) {
115 match self.lower_lit(expr) {
116 PatKind::AscribeUserType { ascription, subpattern: box Pat { kind, .. } } => {
117 (kind, Some(ascription))
119 kind => (kind, None),
123 fn lower_pattern_range(
126 lo: mir::ConstantKind<'tcx>,
127 hi: mir::ConstantKind<'tcx>,
131 assert_eq!(lo.ty(), ty);
132 assert_eq!(hi.ty(), ty);
133 let cmp = compare_const_vals(self.tcx, lo, hi, self.param_env);
135 // `x..y` where `x < y`.
136 // Non-empty because the range includes at least `x`.
137 (RangeEnd::Excluded, Some(Ordering::Less)) => {
138 PatKind::Range(Box::new(PatRange { lo, hi, end }))
140 // `x..y` where `x >= y`. The range is empty => error.
141 (RangeEnd::Excluded, _) => {
146 "lower range bound must be less than upper"
151 // `x..=y` where `x == y`.
152 (RangeEnd::Included, Some(Ordering::Equal)) => PatKind::Constant { value: lo },
153 // `x..=y` where `x < y`.
154 (RangeEnd::Included, Some(Ordering::Less)) => {
155 PatKind::Range(Box::new(PatRange { lo, hi, end }))
157 // `x..=y` where `x > y` hence the range is empty => error.
158 (RangeEnd::Included, _) => {
159 let mut err = struct_span_err!(
163 "lower range bound must be less than or equal to upper"
165 err.span_label(span, "lower bound larger than upper bound");
166 if self.tcx.sess.teach(&err.get_code().unwrap()) {
168 "When matching against a range, the compiler \
169 verifies that the range is non-empty. Range \
170 patterns include both end-points, so this is \
171 equivalent to requiring the start of the range \
172 to be less than or equal to the end of the range.",
181 fn normalize_range_pattern_ends(
184 lo: Option<&PatKind<'tcx>>,
185 hi: Option<&PatKind<'tcx>>,
186 ) -> Option<(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>)> {
188 (Some(PatKind::Constant { value: lo }), Some(PatKind::Constant { value: hi })) => {
191 (Some(PatKind::Constant { value: lo }), None) => {
192 let hi = ty.numeric_max_val(self.tcx)?;
193 Some((*lo, mir::ConstantKind::from_const(hi, self.tcx)))
195 (None, Some(PatKind::Constant { value: hi })) => {
196 let lo = ty.numeric_min_val(self.tcx)?;
197 Some((mir::ConstantKind::from_const(lo, self.tcx), *hi))
203 #[instrument(skip(self), level = "debug")]
204 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
205 let mut ty = self.typeck_results.node_type(pat.hir_id);
206 let mut span = pat.span;
208 let kind = match pat.kind {
209 hir::PatKind::Wild => PatKind::Wild,
211 hir::PatKind::Lit(value) => self.lower_lit(value),
213 hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
214 let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref());
215 let lo_span = lo_expr.map_or(pat.span, |e| e.span);
216 let lo = lo_expr.map(|e| self.lower_range_expr(e));
217 let hi = hi_expr.map(|e| self.lower_range_expr(e));
219 let (lp, hp) = (lo.as_ref().map(|x| &x.0), hi.as_ref().map(|x| &x.0));
220 let mut kind = match self.normalize_range_pattern_ends(ty, lp, hp) {
221 Some((lc, hc)) => self.lower_pattern_range(ty, lc, hc, end, lo_span),
224 "found bad range pattern `{:?}` outside of error recovery",
227 self.tcx.sess.delay_span_bug(pat.span, msg);
232 // If we are handling a range with associated constants (e.g.
233 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
234 // constants somewhere. Have them on the range pattern.
235 for end in &[lo, hi] {
236 if let Some((_, Some(ascription))) = end {
237 let subpattern = Box::new(Pat { span: pat.span, ty, kind });
239 PatKind::AscribeUserType { ascription: ascription.clone(), subpattern };
246 hir::PatKind::Path(ref qpath) => {
247 return self.lower_path(qpath, pat.hir_id, pat.span);
250 hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => {
251 PatKind::Deref { subpattern: self.lower_pattern(subpattern) }
254 hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => {
255 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix)
258 hir::PatKind::Tuple(ref pats, ddpos) => {
259 let ty::Tuple(ref tys) = ty.kind() else {
260 span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty);
262 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
263 PatKind::Leaf { subpatterns }
266 hir::PatKind::Binding(_, id, ident, ref sub) => {
267 if let Some(ident_span) = ident.span.find_ancestor_inside(span) {
268 span = span.with_hi(ident_span.hi());
275 .expect("missing binding mode");
276 let (mutability, mode) = match bm {
277 ty::BindByValue(mutbl) => (mutbl, BindingMode::ByValue),
278 ty::BindByReference(hir::Mutability::Mut) => (
280 BindingMode::ByRef(BorrowKind::Mut { allow_two_phase_borrow: false }),
282 ty::BindByReference(hir::Mutability::Not) => {
283 (Mutability::Not, BindingMode::ByRef(BorrowKind::Shared))
287 // A ref x pattern is the same node used for x, and as such it has
288 // x's type, which is &T, where we want T (the type being matched).
290 if let ty::BindByReference(_) = bm {
291 if let ty::Ref(_, rty, _) = ty.kind() {
294 bug!("`ref {}` has wrong type {}", ident, ty);
304 subpattern: self.lower_opt_pattern(sub),
305 is_primary: id == pat.hir_id,
309 hir::PatKind::TupleStruct(ref qpath, ref pats, ddpos) => {
310 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
311 let ty::Adt(adt_def, _) = ty.kind() else {
312 span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
314 let variant_def = adt_def.variant_of_res(res);
315 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
316 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
319 hir::PatKind::Struct(ref qpath, ref fields, _) => {
320 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
321 let subpatterns = fields
323 .map(|field| FieldPat {
324 field: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)),
325 pattern: self.lower_pattern(&field.pat),
329 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
332 hir::PatKind::Or(ref pats) => PatKind::Or { pats: self.lower_patterns(pats) },
335 Box::new(Pat { span, ty, kind })
338 fn lower_tuple_subpats(
340 pats: &'tcx [hir::Pat<'tcx>],
342 gap_pos: hir::DotDotPos,
343 ) -> Vec<FieldPat<'tcx>> {
345 .enumerate_and_adjust(expected_len, gap_pos)
346 .map(|(i, subpattern)| FieldPat {
347 field: Field::new(i),
348 pattern: self.lower_pattern(subpattern),
353 fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Box<[Box<Pat<'tcx>>]> {
354 pats.iter().map(|p| self.lower_pattern(p)).collect()
357 fn lower_opt_pattern(
359 pat: &'tcx Option<&'tcx hir::Pat<'tcx>>,
360 ) -> Option<Box<Pat<'tcx>>> {
361 pat.as_ref().map(|p| self.lower_pattern(p))
364 fn slice_or_array_pattern(
368 prefix: &'tcx [hir::Pat<'tcx>],
369 slice: &'tcx Option<&'tcx hir::Pat<'tcx>>,
370 suffix: &'tcx [hir::Pat<'tcx>],
372 let prefix = self.lower_patterns(prefix);
373 let slice = self.lower_opt_pattern(slice);
374 let suffix = self.lower_patterns(suffix);
376 // Matching a slice, `[T]`.
377 ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
378 // Fixed-length array, `[T; len]`.
379 ty::Array(_, len) => {
380 let len = len.eval_usize(self.tcx, self.param_env);
381 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
382 PatKind::Array { prefix, slice, suffix }
384 _ => span_bug!(span, "bad slice pattern type {:?}", ty),
388 fn lower_variant_or_leaf(
394 subpatterns: Vec<FieldPat<'tcx>>,
396 let res = match res {
397 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
398 let variant_id = self.tcx.parent(variant_ctor_id);
399 Res::Def(DefKind::Variant, variant_id)
404 let mut kind = match res {
405 Res::Def(DefKind::Variant, variant_id) => {
406 let enum_id = self.tcx.parent(variant_id);
407 let adt_def = self.tcx.adt_def(enum_id);
408 if adt_def.is_enum() {
409 let substs = match ty.kind() {
410 ty::Adt(_, substs) | ty::FnDef(_, substs) => substs,
412 // Avoid ICE (#50585)
413 return PatKind::Wild;
415 _ => bug!("inappropriate type for def: {:?}", ty),
420 variant_index: adt_def.variant_index_with_id(variant_id),
424 PatKind::Leaf { subpatterns }
430 | DefKind::Ctor(CtorOf::Struct, ..)
437 | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
439 let pattern_error = match res {
440 Res::Def(DefKind::ConstParam, _) => PatternError::ConstParamInPattern(span),
441 Res::Def(DefKind::Static(_), _) => PatternError::StaticInPattern(span),
442 _ => PatternError::NonConstPath(span),
444 self.errors.push(pattern_error);
449 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
450 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
451 let annotation = CanonicalUserTypeAnnotation {
452 user_ty: Box::new(user_ty),
454 inferred_ty: self.typeck_results.node_type(hir_id),
456 kind = PatKind::AscribeUserType {
457 subpattern: Box::new(Pat { span, ty, kind }),
458 ascription: Ascription { annotation, variance: ty::Variance::Covariant },
465 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
466 /// it to `const_to_pat`. Any other path (like enum variants without fields)
467 /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
468 #[instrument(skip(self), level = "debug")]
469 fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Box<Pat<'tcx>> {
470 let ty = self.typeck_results.node_type(id);
471 let res = self.typeck_results.qpath_res(qpath, id);
473 let pat_from_kind = |kind| Box::new(Pat { span, ty, kind });
475 let (def_id, is_associated_const) = match res {
476 Res::Def(DefKind::Const, def_id) => (def_id, false),
477 Res::Def(DefKind::AssocConst, def_id) => (def_id, true),
479 _ => return pat_from_kind(self.lower_variant_or_leaf(res, id, span, ty, vec![])),
482 // Use `Reveal::All` here because patterns are always monomorphic even if their function
484 let param_env_reveal_all = self.param_env.with_reveal_all_normalized(self.tcx);
485 let substs = self.typeck_results.node_substs(id);
486 let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, substs) {
489 // It should be assoc consts if there's no error but we cannot resolve it.
490 debug_assert!(is_associated_const);
492 self.errors.push(PatternError::AssocConstInPattern(span));
494 return pat_from_kind(PatKind::Wild);
498 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
499 return pat_from_kind(PatKind::Wild);
503 // `mir_const_qualif` must be called with the `DefId` of the item where the const is
504 // defined, not where it is declared. The difference is significant for associated
506 let mir_structural_match_violation = self.tcx.mir_const_qualif(instance.def_id()).custom_eq;
507 debug!("mir_structural_match_violation({:?}) -> {}", qpath, mir_structural_match_violation);
509 match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) {
511 let const_ = mir::ConstantKind::Val(literal, ty);
512 let pattern = self.const_to_pat(const_, id, span, mir_structural_match_violation);
514 if !is_associated_const {
518 let user_provided_types = self.typeck_results().user_provided_types();
519 if let Some(&user_ty) = user_provided_types.get(id) {
520 let annotation = CanonicalUserTypeAnnotation {
521 user_ty: Box::new(user_ty),
523 inferred_ty: self.typeck_results().node_type(id),
527 kind: PatKind::AscribeUserType {
529 ascription: Ascription {
531 /// Note that use `Contravariant` here. See the
532 /// `variance` field documentation for details.
533 variance: ty::Variance::Contravariant,
542 Err(ErrorHandled::TooGeneric) => {
543 // While `Reported | Linted` cases will have diagnostics emitted already
544 // it is not true for TooGeneric case, so we need to give user more information.
545 self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
546 pat_from_kind(PatKind::Wild)
549 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
550 pat_from_kind(PatKind::Wild)
555 /// Converts inline const patterns.
556 fn lower_inline_const(
558 anon_const: &'tcx hir::AnonConst,
562 let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
563 let value = mir::ConstantKind::from_inline_const(self.tcx, anon_const_def_id);
565 // Evaluate early like we do in `lower_path`.
566 let value = value.eval(self.tcx, self.param_env);
569 mir::ConstantKind::Ty(c) => match c.kind() {
570 ConstKind::Param(_) => {
571 self.errors.push(PatternError::ConstParamInPattern(span));
572 return PatKind::Wild;
574 _ => bug!("Expected ConstKind::Param"),
576 mir::ConstantKind::Val(_, _) => self.const_to_pat(value, id, span, false).kind,
577 mir::ConstantKind::Unevaluated(..) => {
578 // If we land here it means the const can't be evaluated because it's `TooGeneric`.
579 self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
580 return PatKind::Wild;
585 /// Converts literals, paths and negation of literals to patterns.
586 /// The special case for negation exists to allow things like `-128_i8`
587 /// which would overflow if we tried to evaluate `128_i8` and then negate
589 fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
590 let (lit, neg) = match expr.kind {
591 hir::ExprKind::Path(ref qpath) => {
592 return self.lower_path(qpath, expr.hir_id, expr.span).kind;
594 hir::ExprKind::ConstBlock(ref anon_const) => {
595 return self.lower_inline_const(anon_const, expr.hir_id, expr.span);
597 hir::ExprKind::Lit(ref lit) => (lit, false),
598 hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => {
599 let hir::ExprKind::Lit(ref lit) = expr.kind else {
600 span_bug!(expr.span, "not a literal: {:?}", expr);
604 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
608 LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg };
609 match self.tcx.at(expr.span).lit_to_mir_constant(lit_input) {
610 Ok(constant) => self.const_to_pat(constant, expr.hir_id, lit.span, false).kind,
611 Err(LitToConstError::Reported) => PatKind::Wild,
612 Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
617 impl<'tcx> UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> {
618 fn tcx(&self) -> TyCtxt<'tcx> {
622 fn typeck_results(&self) -> &ty::TypeckResults<'tcx> {
627 trait PatternFoldable<'tcx>: Sized {
628 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
629 self.super_fold_with(folder)
632 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
635 trait PatternFolder<'tcx>: Sized {
636 fn fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx> {
637 pattern.super_fold_with(self)
640 fn fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx> {
641 kind.super_fold_with(self)
645 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
646 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
647 let content: T = (**self).fold_with(folder);
652 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
653 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
654 self.iter().map(|t| t.fold_with(folder)).collect()
658 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<[T]> {
659 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
660 self.iter().map(|t| t.fold_with(folder)).collect()
664 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
665 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
666 self.as_ref().map(|t| t.fold_with(folder))
670 macro_rules! ClonePatternFoldableImpls {
671 (<$lt_tcx:tt> $($ty:ty),+) => {
673 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
674 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
682 ClonePatternFoldableImpls! { <'tcx>
683 Span, Field, Mutability, Symbol, LocalVarId, usize,
684 Region<'tcx>, Ty<'tcx>, BindingMode, AdtDef<'tcx>,
685 SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
686 UserTypeProjection, CanonicalUserTypeAnnotation<'tcx>
689 impl<'tcx> PatternFoldable<'tcx> for FieldPat<'tcx> {
690 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
691 FieldPat { field: self.field.fold_with(folder), pattern: self.pattern.fold_with(folder) }
695 impl<'tcx> PatternFoldable<'tcx> for Pat<'tcx> {
696 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
697 folder.fold_pattern(self)
700 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
702 ty: self.ty.fold_with(folder),
703 span: self.span.fold_with(folder),
704 kind: self.kind.fold_with(folder),
709 impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
710 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
711 folder.fold_pattern_kind(self)
714 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
716 PatKind::Wild => PatKind::Wild,
717 PatKind::AscribeUserType {
719 ascription: Ascription { ref annotation, variance },
720 } => PatKind::AscribeUserType {
721 subpattern: subpattern.fold_with(folder),
722 ascription: Ascription { annotation: annotation.fold_with(folder), variance },
724 PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, is_primary } => {
726 mutability: mutability.fold_with(folder),
727 name: name.fold_with(folder),
728 mode: mode.fold_with(folder),
729 var: var.fold_with(folder),
730 ty: ty.fold_with(folder),
731 subpattern: subpattern.fold_with(folder),
735 PatKind::Variant { adt_def, substs, variant_index, ref subpatterns } => {
737 adt_def: adt_def.fold_with(folder),
738 substs: substs.fold_with(folder),
740 subpatterns: subpatterns.fold_with(folder),
743 PatKind::Leaf { ref subpatterns } => {
744 PatKind::Leaf { subpatterns: subpatterns.fold_with(folder) }
746 PatKind::Deref { ref subpattern } => {
747 PatKind::Deref { subpattern: subpattern.fold_with(folder) }
749 PatKind::Constant { value } => PatKind::Constant { value },
750 PatKind::Range(ref range) => PatKind::Range(range.clone()),
751 PatKind::Slice { ref prefix, ref slice, ref suffix } => PatKind::Slice {
752 prefix: prefix.fold_with(folder),
753 slice: slice.fold_with(folder),
754 suffix: suffix.fold_with(folder),
756 PatKind::Array { ref prefix, ref slice, ref suffix } => PatKind::Array {
757 prefix: prefix.fold_with(folder),
758 slice: slice.fold_with(folder),
759 suffix: suffix.fold_with(folder),
761 PatKind::Or { ref pats } => PatKind::Or { pats: pats.fold_with(folder) },
766 #[instrument(skip(tcx), level = "debug")]
767 pub(crate) fn compare_const_vals<'tcx>(
769 a: mir::ConstantKind<'tcx>,
770 b: mir::ConstantKind<'tcx>,
771 param_env: ty::ParamEnv<'tcx>,
772 ) -> Option<Ordering> {
773 assert_eq!(a.ty(), b.ty());
777 // This code is hot when compiling matches with many ranges. So we
778 // special-case extraction of evaluated scalars for speed, for types where
779 // raw data comparisons are appropriate. E.g. `unicode-normalization` has
780 // many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared
783 ty::Float(_) | ty::Int(_) => {} // require special handling, see below
786 mir::ConstantKind::Val(ConstValue::Scalar(Scalar::Int(a)), _a_ty),
787 mir::ConstantKind::Val(ConstValue::Scalar(Scalar::Int(b)), _b_ty),
788 ) => return Some(a.cmp(&b)),
793 let a = a.eval_bits(tcx, param_env, ty);
794 let b = b.eval_bits(tcx, param_env, ty);
796 use rustc_apfloat::Float;
798 ty::Float(ty::FloatTy::F32) => {
799 let a = rustc_apfloat::ieee::Single::from_bits(a);
800 let b = rustc_apfloat::ieee::Single::from_bits(b);
803 ty::Float(ty::FloatTy::F64) => {
804 let a = rustc_apfloat::ieee::Double::from_bits(a);
805 let b = rustc_apfloat::ieee::Double::from_bits(b);
809 use rustc_middle::ty::layout::IntegerExt;
810 let size = rustc_target::abi::Integer::from_int_ty(&tcx, ity).size();
811 let a = size.sign_extend(a);
812 let b = size.sign_extend(b);
813 Some((a as i128).cmp(&(b as i128)))
815 _ => Some(a.cmp(&b)),