1 //! Validation of patterns/matches.
7 pub(crate) use self::check_match::check_match;
9 use crate::hair::util::UserAnnotatedTyHelpers;
12 use rustc_errors::struct_span_err;
14 use rustc_hir::def::{CtorKind, 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::{get_slice_bytes, sign_extend, ConstValue};
19 use rustc_middle::mir::interpret::{ErrorHandled, LitToConstError, LitToConstInput};
20 use rustc_middle::mir::UserTypeProjection;
21 use rustc_middle::mir::{BorrowKind, Field, Mutability};
22 use rustc_middle::ty::subst::{GenericArg, SubstsRef};
23 use rustc_middle::ty::{self, AdtDef, DefIdTree, Region, Ty, TyCtxt, UserType};
24 use rustc_middle::ty::{
25 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
27 use rustc_span::{Span, Symbol, DUMMY_SP};
28 use rustc_target::abi::VariantIdx;
30 use std::cmp::Ordering;
33 #[derive(Clone, Debug)]
34 crate enum PatternError {
35 AssocConstInPattern(Span),
36 ConstParamInPattern(Span),
37 StaticInPattern(Span),
42 #[derive(Copy, Clone, Debug)]
43 crate enum BindingMode {
48 #[derive(Clone, Debug)]
49 crate struct FieldPat<'tcx> {
51 crate pattern: Pat<'tcx>,
54 #[derive(Clone, Debug)]
55 crate struct Pat<'tcx> {
58 crate kind: Box<PatKind<'tcx>>,
61 impl<'tcx> Pat<'tcx> {
62 pub(crate) fn wildcard_from_ty(ty: Ty<'tcx>) -> Self {
63 Pat { ty, span: DUMMY_SP, kind: Box::new(PatKind::Wild) }
67 #[derive(Copy, Clone, Debug, PartialEq)]
68 crate struct PatTyProj<'tcx> {
69 crate user_ty: CanonicalUserType<'tcx>,
72 impl<'tcx> PatTyProj<'tcx> {
73 pub(crate) fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
74 Self { user_ty: user_annotation }
77 pub(crate) fn user_ty(
79 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
80 inferred_ty: Ty<'tcx>,
82 ) -> UserTypeProjection {
84 base: annotations.push(CanonicalUserTypeAnnotation {
86 user_ty: self.user_ty,
94 #[derive(Copy, Clone, Debug, PartialEq)]
95 crate struct Ascription<'tcx> {
96 crate user_ty: PatTyProj<'tcx>,
97 /// Variance to use when relating the type `user_ty` to the **type of the value being
98 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
99 /// have a type that is some subtype of the ascribed type.
101 /// Note that this variance does not apply for any bindings within subpatterns. The type
102 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
104 /// The only place where this field is not `Covariant` is when matching constants, where
105 /// we currently use `Contravariant` -- this is because the constant type just needs to
106 /// be "comparable" to the type of the input value. So, for example:
109 /// match x { "foo" => .. }
112 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
113 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
114 /// of the old type-check for now. See #57280 for details.
115 crate variance: ty::Variance,
116 crate user_ty_span: Span,
119 #[derive(Clone, Debug)]
120 crate enum PatKind<'tcx> {
124 ascription: Ascription<'tcx>,
125 subpattern: Pat<'tcx>,
128 /// `x`, `ref x`, `x @ P`, etc.
130 mutability: Mutability,
135 subpattern: Option<Pat<'tcx>>,
136 /// Is this the leftmost occurance of the binding, i.e., is `var` the
137 /// `HirId` of this pattern?
141 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
142 /// multiple variants.
144 adt_def: &'tcx AdtDef,
145 substs: SubstsRef<'tcx>,
146 variant_index: VariantIdx,
147 subpatterns: Vec<FieldPat<'tcx>>,
150 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
151 /// a single variant.
153 subpatterns: Vec<FieldPat<'tcx>>,
156 /// `box P`, `&P`, `&mut P`, etc.
158 subpattern: Pat<'tcx>,
162 value: &'tcx ty::Const<'tcx>,
165 Range(PatRange<'tcx>),
167 /// Matches against a slice, checking the length and extracting elements.
168 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
169 /// e.g., `&[ref xs @ ..]`.
171 prefix: Vec<Pat<'tcx>>,
172 slice: Option<Pat<'tcx>>,
173 suffix: Vec<Pat<'tcx>>,
176 /// Fixed match against an array; irrefutable.
178 prefix: Vec<Pat<'tcx>>,
179 slice: Option<Pat<'tcx>>,
180 suffix: Vec<Pat<'tcx>>,
183 /// An or-pattern, e.g. `p | q`.
184 /// Invariant: `pats.len() >= 2`.
186 pats: Vec<Pat<'tcx>>,
190 #[derive(Copy, Clone, Debug, PartialEq)]
191 crate struct PatRange<'tcx> {
192 crate lo: &'tcx ty::Const<'tcx>,
193 crate hi: &'tcx ty::Const<'tcx>,
197 impl<'tcx> fmt::Display for Pat<'tcx> {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 // Printing lists is a chore.
200 let mut first = true;
201 let mut start_or_continue = |s| {
209 let mut start_or_comma = || start_or_continue(", ");
212 PatKind::Wild => write!(f, "_"),
213 PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern),
214 PatKind::Binding { mutability, name, mode, ref subpattern, .. } => {
215 let is_mut = match mode {
216 BindingMode::ByValue => mutability == Mutability::Mut,
217 BindingMode::ByRef(bk) => {
220 BorrowKind::Mut { .. } => true,
228 write!(f, "{}", name)?;
229 if let Some(ref subpattern) = *subpattern {
230 write!(f, " @ {}", subpattern)?;
234 PatKind::Variant { ref subpatterns, .. } | PatKind::Leaf { ref subpatterns } => {
235 let variant = match *self.kind {
236 PatKind::Variant { adt_def, variant_index, .. } => {
237 Some(&adt_def.variants[variant_index])
240 if let ty::Adt(adt, _) = self.ty.kind {
242 Some(&adt.variants[VariantIdx::new(0)])
252 if let Some(variant) = variant {
253 write!(f, "{}", variant.ident)?;
255 // Only for Adt we can have `S {...}`,
256 // which we handle separately here.
257 if variant.ctor_kind == CtorKind::Fictive {
261 for p in subpatterns {
262 if let PatKind::Wild = *p.pattern.kind {
265 let name = variant.fields[p.field.index()].ident;
266 write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
270 if printed < variant.fields.len() {
271 write!(f, "{}..", start_or_comma())?;
274 return write!(f, " }}");
278 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
279 if num_fields != 0 || variant.is_none() {
281 for i in 0..num_fields {
282 write!(f, "{}", start_or_comma())?;
284 // Common case: the field is where we expect it.
285 if let Some(p) = subpatterns.get(i) {
286 if p.field.index() == i {
287 write!(f, "{}", p.pattern)?;
292 // Otherwise, we have to go looking for it.
293 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
294 write!(f, "{}", p.pattern)?;
304 PatKind::Deref { ref subpattern } => {
306 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
307 ty::Ref(_, _, mutbl) => {
308 write!(f, "&{}", mutbl.prefix_str())?;
310 _ => bug!("{} is a bad Deref pattern type", self.ty),
312 write!(f, "{}", subpattern)
314 PatKind::Constant { value } => write!(f, "{}", value),
315 PatKind::Range(PatRange { lo, hi, end }) => {
316 write!(f, "{}", lo)?;
317 write!(f, "{}", end)?;
320 PatKind::Slice { ref prefix, ref slice, ref suffix }
321 | PatKind::Array { ref prefix, ref slice, ref suffix } => {
324 write!(f, "{}{}", start_or_comma(), p)?;
326 if let Some(ref slice) = *slice {
327 write!(f, "{}", start_or_comma())?;
330 _ => write!(f, "{}", slice)?,
335 write!(f, "{}{}", start_or_comma(), p)?;
339 PatKind::Or { ref pats } => {
341 write!(f, "{}{}", start_or_continue(" | "), pat)?;
349 crate struct PatCtxt<'a, 'tcx> {
350 crate tcx: TyCtxt<'tcx>,
351 crate param_env: ty::ParamEnv<'tcx>,
352 crate typeck_results: &'a ty::TypeckResults<'tcx>,
353 crate errors: Vec<PatternError>,
354 include_lint_checks: bool,
357 impl<'a, 'tcx> Pat<'tcx> {
360 param_env: ty::ParamEnv<'tcx>,
361 typeck_results: &'a ty::TypeckResults<'tcx>,
362 pat: &'tcx hir::Pat<'tcx>,
364 let mut pcx = PatCtxt::new(tcx, param_env, typeck_results);
365 let result = pcx.lower_pattern(pat);
366 if !pcx.errors.is_empty() {
367 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
368 tcx.sess.delay_span_bug(pat.span, &msg);
370 debug!("Pat::from_hir({:?}) = {:?}", pat, result);
375 impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
378 param_env: ty::ParamEnv<'tcx>,
379 typeck_results: &'a ty::TypeckResults<'tcx>,
381 PatCtxt { tcx, param_env, typeck_results, errors: vec![], include_lint_checks: false }
384 crate fn include_lint_checks(&mut self) -> &mut Self {
385 self.include_lint_checks = true;
389 crate fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx> {
390 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
391 // pattern has the type that results *after* dereferencing. For example, in this code:
394 // match &&Some(0i32) {
395 // Some(n) => { ... },
400 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
401 // determined in rustc_typeck::check::match). The adjustments would be
403 // `vec![&&Option<i32>, &Option<i32>]`.
405 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
406 // we wrap the unadjusted pattern in `PatKind::Deref` repeatedly, consuming the
407 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
408 // gets the least-dereferenced type).
409 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
410 self.typeck_results.pat_adjustments().get(pat.hir_id).unwrap_or(&vec![]).iter().rev().fold(
413 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
417 kind: Box::new(PatKind::Deref { subpattern: pat }),
425 expr: &'tcx hir::Expr<'tcx>,
426 ) -> (PatKind<'tcx>, Option<Ascription<'tcx>>) {
427 match self.lower_lit(expr) {
428 PatKind::AscribeUserType { ascription, subpattern: Pat { kind: box kind, .. } } => {
429 (kind, Some(ascription))
431 kind => (kind, None),
435 fn lower_pattern_range(
438 lo: &'tcx ty::Const<'tcx>,
439 hi: &'tcx ty::Const<'tcx>,
443 assert_eq!(lo.ty, ty);
444 assert_eq!(hi.ty, ty);
445 let cmp = compare_const_vals(self.tcx, lo, hi, self.param_env, ty);
447 // `x..y` where `x < y`.
448 // Non-empty because the range includes at least `x`.
449 (RangeEnd::Excluded, Some(Ordering::Less)) => PatKind::Range(PatRange { lo, hi, end }),
450 // `x..y` where `x >= y`. The range is empty => error.
451 (RangeEnd::Excluded, _) => {
456 "lower range bound must be less than upper"
461 // `x..=y` where `x == y`.
462 (RangeEnd::Included, Some(Ordering::Equal)) => PatKind::Constant { value: lo },
463 // `x..=y` where `x < y`.
464 (RangeEnd::Included, Some(Ordering::Less)) => PatKind::Range(PatRange { lo, hi, end }),
465 // `x..=y` where `x > y` hence the range is empty => error.
466 (RangeEnd::Included, _) => {
467 let mut err = struct_span_err!(
471 "lower range bound must be less than or equal to upper"
473 err.span_label(span, "lower bound larger than upper bound");
474 if self.tcx.sess.teach(&err.get_code().unwrap()) {
476 "When matching against a range, the compiler \
477 verifies that the range is non-empty. Range \
478 patterns include both end-points, so this is \
479 equivalent to requiring the start of the range \
480 to be less than or equal to the end of the range.",
489 fn normalize_range_pattern_ends(
492 lo: Option<&PatKind<'tcx>>,
493 hi: Option<&PatKind<'tcx>>,
494 ) -> Option<(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>)> {
496 (Some(PatKind::Constant { value: lo }), Some(PatKind::Constant { value: hi })) => {
499 (Some(PatKind::Constant { value: lo }), None) => {
500 Some((lo, ty.numeric_max_val(self.tcx)?))
502 (None, Some(PatKind::Constant { value: hi })) => {
503 Some((ty.numeric_min_val(self.tcx)?, hi))
509 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx> {
510 let mut ty = self.typeck_results.node_type(pat.hir_id);
512 let kind = match pat.kind {
513 hir::PatKind::Wild => PatKind::Wild,
515 hir::PatKind::Lit(ref value) => self.lower_lit(value),
517 hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
518 let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref());
519 let lo_span = lo_expr.map_or(pat.span, |e| e.span);
520 let lo = lo_expr.map(|e| self.lower_range_expr(e));
521 let hi = hi_expr.map(|e| self.lower_range_expr(e));
523 let (lp, hp) = (lo.as_ref().map(|x| &x.0), hi.as_ref().map(|x| &x.0));
524 let mut kind = match self.normalize_range_pattern_ends(ty, lp, hp) {
525 Some((lc, hc)) => self.lower_pattern_range(ty, lc, hc, end, lo_span),
528 "found bad range pattern `{:?}` outside of error recovery",
531 self.tcx.sess.delay_span_bug(pat.span, msg);
536 // If we are handling a range with associated constants (e.g.
537 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
538 // constants somewhere. Have them on the range pattern.
539 for end in &[lo, hi] {
540 if let Some((_, Some(ascription))) = end {
541 let subpattern = Pat { span: pat.span, ty, kind: Box::new(kind) };
542 kind = PatKind::AscribeUserType { ascription: *ascription, subpattern };
549 hir::PatKind::Path(ref qpath) => {
550 return self.lower_path(qpath, pat.hir_id, pat.span);
553 hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => {
554 PatKind::Deref { subpattern: self.lower_pattern(subpattern) }
557 hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => {
558 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix)
561 hir::PatKind::Tuple(ref pats, ddpos) => {
562 let tys = match ty.kind {
563 ty::Tuple(ref tys) => tys,
564 _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty),
566 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
567 PatKind::Leaf { subpatterns }
570 hir::PatKind::Binding(_, id, ident, ref sub) => {
575 .expect("missing binding mode");
576 let (mutability, mode) = match bm {
577 ty::BindByValue(mutbl) => (mutbl, BindingMode::ByValue),
578 ty::BindByReference(hir::Mutability::Mut) => (
580 BindingMode::ByRef(BorrowKind::Mut { allow_two_phase_borrow: false }),
582 ty::BindByReference(hir::Mutability::Not) => {
583 (Mutability::Not, BindingMode::ByRef(BorrowKind::Shared))
587 // A ref x pattern is the same node used for x, and as such it has
588 // x's type, which is &T, where we want T (the type being matched).
590 if let ty::BindByReference(_) = bm {
591 if let ty::Ref(_, rty, _) = ty.kind {
594 bug!("`ref {}` has wrong type {}", ident, ty);
604 subpattern: self.lower_opt_pattern(sub),
605 is_primary: id == pat.hir_id,
609 hir::PatKind::TupleStruct(ref qpath, ref pats, ddpos) => {
610 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
611 let adt_def = match ty.kind {
612 ty::Adt(adt_def, _) => adt_def,
613 _ => span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty),
615 let variant_def = adt_def.variant_of_res(res);
616 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
617 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
620 hir::PatKind::Struct(ref qpath, ref fields, _) => {
621 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
622 let subpatterns = fields
624 .map(|field| FieldPat {
625 field: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)),
626 pattern: self.lower_pattern(&field.pat),
630 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
633 hir::PatKind::Or(ref pats) => PatKind::Or { pats: self.lower_patterns(pats) },
636 Pat { span: pat.span, ty, kind: Box::new(kind) }
639 fn lower_tuple_subpats(
641 pats: &'tcx [&'tcx hir::Pat<'tcx>],
643 gap_pos: Option<usize>,
644 ) -> Vec<FieldPat<'tcx>> {
646 .enumerate_and_adjust(expected_len, gap_pos)
647 .map(|(i, subpattern)| FieldPat {
648 field: Field::new(i),
649 pattern: self.lower_pattern(subpattern),
654 fn lower_patterns(&mut self, pats: &'tcx [&'tcx hir::Pat<'tcx>]) -> Vec<Pat<'tcx>> {
655 pats.iter().map(|p| self.lower_pattern(p)).collect()
658 fn lower_opt_pattern(&mut self, pat: &'tcx Option<&'tcx hir::Pat<'tcx>>) -> Option<Pat<'tcx>> {
659 pat.as_ref().map(|p| self.lower_pattern(p))
662 fn slice_or_array_pattern(
666 prefix: &'tcx [&'tcx hir::Pat<'tcx>],
667 slice: &'tcx Option<&'tcx hir::Pat<'tcx>>,
668 suffix: &'tcx [&'tcx hir::Pat<'tcx>],
670 let prefix = self.lower_patterns(prefix);
671 let slice = self.lower_opt_pattern(slice);
672 let suffix = self.lower_patterns(suffix);
674 // Matching a slice, `[T]`.
675 ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
676 // Fixed-length array, `[T; len]`.
677 ty::Array(_, len) => {
678 let len = len.eval_usize(self.tcx, self.param_env);
679 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
680 PatKind::Array { prefix, slice, suffix }
682 _ => span_bug!(span, "bad slice pattern type {:?}", ty),
686 fn lower_variant_or_leaf(
692 subpatterns: Vec<FieldPat<'tcx>>,
694 let res = match res {
695 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
696 let variant_id = self.tcx.parent(variant_ctor_id).unwrap();
697 Res::Def(DefKind::Variant, variant_id)
702 let mut kind = match res {
703 Res::Def(DefKind::Variant, variant_id) => {
704 let enum_id = self.tcx.parent(variant_id).unwrap();
705 let adt_def = self.tcx.adt_def(enum_id);
706 if adt_def.is_enum() {
707 let substs = match ty.kind {
708 ty::Adt(_, substs) | ty::FnDef(_, substs) => substs,
710 // Avoid ICE (#50585)
711 return PatKind::Wild;
713 _ => bug!("inappropriate type for def: {:?}", ty),
718 variant_index: adt_def.variant_index_with_id(variant_id),
722 PatKind::Leaf { subpatterns }
728 | DefKind::Ctor(CtorOf::Struct, ..)
735 | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
737 let pattern_error = match res {
738 Res::Def(DefKind::ConstParam, _) => PatternError::ConstParamInPattern(span),
739 _ => PatternError::NonConstPath(span),
741 self.errors.push(pattern_error);
746 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
747 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
748 kind = PatKind::AscribeUserType {
749 subpattern: Pat { span, ty, kind: Box::new(kind) },
750 ascription: Ascription {
751 user_ty: PatTyProj::from_user_type(user_ty),
753 variance: ty::Variance::Covariant,
761 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
762 /// it to `const_to_pat`. Any other path (like enum variants without fields)
763 /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
764 fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Pat<'tcx> {
765 let ty = self.typeck_results.node_type(id);
766 let res = self.typeck_results.qpath_res(qpath, id);
768 let pat_from_kind = |kind| Pat { span, ty, kind: Box::new(kind) };
770 let (def_id, is_associated_const) = match res {
771 Res::Def(DefKind::Const, def_id) => (def_id, false),
772 Res::Def(DefKind::AssocConst, def_id) => (def_id, true),
774 _ => return pat_from_kind(self.lower_variant_or_leaf(res, id, span, ty, vec![])),
777 // Use `Reveal::All` here because patterns are always monomorphic even if their function
779 let param_env_reveal_all = self.param_env.with_reveal_all_normalized(self.tcx);
780 let substs = self.typeck_results.node_substs(id);
781 let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, substs) {
784 self.errors.push(if is_associated_const {
785 PatternError::AssocConstInPattern(span)
787 PatternError::StaticInPattern(span)
790 return pat_from_kind(PatKind::Wild);
794 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
795 return pat_from_kind(PatKind::Wild);
799 // `mir_const_qualif` must be called with the `DefId` of the item where the const is
800 // defined, not where it is declared. The difference is significant for associated
802 let mir_structural_match_violation = self.tcx.mir_const_qualif(instance.def_id()).custom_eq;
803 debug!("mir_structural_match_violation({:?}) -> {}", qpath, mir_structural_match_violation);
805 match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) {
808 ty::Const::from_value(self.tcx, value, self.typeck_results.node_type(id));
810 let pattern = self.const_to_pat(&const_, id, span, mir_structural_match_violation);
812 if !is_associated_const {
816 let user_provided_types = self.typeck_results().user_provided_types();
817 if let Some(u_ty) = user_provided_types.get(id) {
818 let user_ty = PatTyProj::from_user_type(*u_ty);
821 kind: Box::new(PatKind::AscribeUserType {
823 ascription: Ascription {
824 /// Note that use `Contravariant` here. See the
825 /// `variance` field documentation for details.
826 variance: ty::Variance::Contravariant,
837 Err(ErrorHandled::TooGeneric) => {
838 // While `Reported | Linted` cases will have diagnostics emitted already
839 // it is not true for TooGeneric case, so we need to give user more information.
840 self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
841 pat_from_kind(PatKind::Wild)
844 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
845 pat_from_kind(PatKind::Wild)
850 /// Converts literals, paths and negation of literals to patterns.
851 /// The special case for negation exists to allow things like `-128_i8`
852 /// which would overflow if we tried to evaluate `128_i8` and then negate
854 fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
855 if let hir::ExprKind::Path(ref qpath) = expr.kind {
856 *self.lower_path(qpath, expr.hir_id, expr.span).kind
858 let (lit, neg) = match expr.kind {
859 hir::ExprKind::Lit(ref lit) => (lit, false),
860 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
861 let lit = match expr.kind {
862 hir::ExprKind::Lit(ref lit) => lit,
863 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
867 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
871 LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg };
872 match self.tcx.at(expr.span).lit_to_const(lit_input) {
873 Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span, false).kind,
874 Err(LitToConstError::UnparseableFloat) => {
875 self.errors.push(PatternError::FloatBug);
878 Err(LitToConstError::Reported) => PatKind::Wild,
879 Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
885 impl<'tcx> UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> {
886 fn tcx(&self) -> TyCtxt<'tcx> {
890 fn typeck_results(&self) -> &ty::TypeckResults<'tcx> {
895 crate trait PatternFoldable<'tcx>: Sized {
896 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
897 self.super_fold_with(folder)
900 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
903 crate trait PatternFolder<'tcx>: Sized {
904 fn fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx> {
905 pattern.super_fold_with(self)
908 fn fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx> {
909 kind.super_fold_with(self)
913 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
914 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
915 let content: T = (**self).fold_with(folder);
920 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
921 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
922 self.iter().map(|t| t.fold_with(folder)).collect()
926 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
927 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
928 self.as_ref().map(|t| t.fold_with(folder))
932 macro_rules! CloneImpls {
933 (<$lt_tcx:tt> $($ty:ty),+) => {
935 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
936 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
945 Span, Field, Mutability, Symbol, hir::HirId, usize, ty::Const<'tcx>,
946 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
947 SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
948 UserTypeProjection, PatTyProj<'tcx>
951 impl<'tcx> PatternFoldable<'tcx> for FieldPat<'tcx> {
952 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
953 FieldPat { field: self.field.fold_with(folder), pattern: self.pattern.fold_with(folder) }
957 impl<'tcx> PatternFoldable<'tcx> for Pat<'tcx> {
958 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
959 folder.fold_pattern(self)
962 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
964 ty: self.ty.fold_with(folder),
965 span: self.span.fold_with(folder),
966 kind: self.kind.fold_with(folder),
971 impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
972 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
973 folder.fold_pattern_kind(self)
976 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
978 PatKind::Wild => PatKind::Wild,
979 PatKind::AscribeUserType {
981 ascription: Ascription { variance, ref user_ty, user_ty_span },
982 } => PatKind::AscribeUserType {
983 subpattern: subpattern.fold_with(folder),
984 ascription: Ascription {
985 user_ty: user_ty.fold_with(folder),
990 PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, is_primary } => {
992 mutability: mutability.fold_with(folder),
993 name: name.fold_with(folder),
994 mode: mode.fold_with(folder),
995 var: var.fold_with(folder),
996 ty: ty.fold_with(folder),
997 subpattern: subpattern.fold_with(folder),
1001 PatKind::Variant { adt_def, substs, variant_index, ref subpatterns } => {
1003 adt_def: adt_def.fold_with(folder),
1004 substs: substs.fold_with(folder),
1006 subpatterns: subpatterns.fold_with(folder),
1009 PatKind::Leaf { ref subpatterns } => {
1010 PatKind::Leaf { subpatterns: subpatterns.fold_with(folder) }
1012 PatKind::Deref { ref subpattern } => {
1013 PatKind::Deref { subpattern: subpattern.fold_with(folder) }
1015 PatKind::Constant { value } => PatKind::Constant { value },
1016 PatKind::Range(range) => PatKind::Range(range),
1017 PatKind::Slice { ref prefix, ref slice, ref suffix } => PatKind::Slice {
1018 prefix: prefix.fold_with(folder),
1019 slice: slice.fold_with(folder),
1020 suffix: suffix.fold_with(folder),
1022 PatKind::Array { ref prefix, ref slice, ref suffix } => PatKind::Array {
1023 prefix: prefix.fold_with(folder),
1024 slice: slice.fold_with(folder),
1025 suffix: suffix.fold_with(folder),
1027 PatKind::Or { ref pats } => PatKind::Or { pats: pats.fold_with(folder) },
1032 crate fn compare_const_vals<'tcx>(
1034 a: &'tcx ty::Const<'tcx>,
1035 b: &'tcx ty::Const<'tcx>,
1036 param_env: ty::ParamEnv<'tcx>,
1038 ) -> Option<Ordering> {
1039 trace!("compare_const_vals: {:?}, {:?}", a, b);
1041 let from_bool = |v: bool| v.then_some(Ordering::Equal);
1043 let fallback = || from_bool(a == b);
1045 // Use the fallback if any type differs
1046 if a.ty != b.ty || a.ty != ty {
1050 // Early return for equal constants (so e.g. references to ZSTs can be compared, even if they
1051 // are just integer addresses).
1053 return from_bool(true);
1056 let a_bits = a.try_eval_bits(tcx, param_env, ty);
1057 let b_bits = b.try_eval_bits(tcx, param_env, ty);
1059 if let (Some(a), Some(b)) = (a_bits, b_bits) {
1060 use rustc_apfloat::Float;
1061 return match ty.kind {
1062 ty::Float(ast::FloatTy::F32) => {
1063 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1064 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1067 ty::Float(ast::FloatTy::F64) => {
1068 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1069 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1073 use rustc_attr::SignedInt;
1074 use rustc_middle::ty::layout::IntegerExt;
1075 let size = rustc_target::abi::Integer::from_attr(&tcx, SignedInt(ity)).size();
1076 let a = sign_extend(a, size);
1077 let b = sign_extend(b, size);
1078 Some((a as i128).cmp(&(b as i128)))
1080 _ => Some(a.cmp(&b)),
1084 if let ty::Str = ty.kind {
1086 ty::ConstKind::Value(a_val @ ConstValue::Slice { .. }),
1087 ty::ConstKind::Value(b_val @ ConstValue::Slice { .. }),
1090 let a_bytes = get_slice_bytes(&tcx, a_val);
1091 let b_bytes = get_slice_bytes(&tcx, b_val);
1092 return from_bool(a_bytes == b_bytes);