1 //! Validation of patterns/matches.
6 pub(crate) use self::check_match::check_match;
8 use crate::const_eval::const_variant_index;
10 use crate::hair::util::UserAnnotatedTyHelpers;
11 use crate::hair::constant::*;
14 use rustc::mir::{Field, BorrowKind, Mutability};
15 use rustc::mir::{UserTypeProjection};
16 use rustc::mir::interpret::{GlobalId, ConstValue, get_slice_bytes, sign_extend};
17 use rustc::traits::{ObligationCause, PredicateObligation};
18 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, UserType, DefIdTree};
19 use rustc::ty::{CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations};
20 use rustc::ty::subst::{SubstsRef, GenericArg};
21 use rustc::ty::layout::VariantIdx;
22 use rustc::hir::{self, RangeEnd};
23 use rustc::hir::def::{CtorOf, Res, DefKind, CtorKind};
24 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
25 use rustc::hir::ptr::P;
27 use rustc_index::vec::Idx;
29 use std::cmp::Ordering;
32 use syntax::symbol::sym;
35 #[derive(Clone, Debug)]
36 pub enum PatternError {
37 AssocConstInPattern(Span),
38 StaticInPattern(Span),
43 #[derive(Copy, Clone, Debug)]
44 pub enum BindingMode {
49 #[derive(Clone, Debug)]
50 pub struct FieldPat<'tcx> {
52 pub pattern: Pat<'tcx>,
55 #[derive(Clone, Debug)]
56 pub struct Pat<'tcx> {
59 pub kind: Box<PatKind<'tcx>>,
63 #[derive(Copy, Clone, Debug, PartialEq)]
64 pub struct PatTyProj<'tcx> {
65 pub user_ty: CanonicalUserType<'tcx>,
68 impl<'tcx> PatTyProj<'tcx> {
69 pub(crate) fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
71 user_ty: user_annotation,
75 pub(crate) fn user_ty(
77 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
78 inferred_ty: Ty<'tcx>,
80 ) -> UserTypeProjection {
82 base: annotations.push(CanonicalUserTypeAnnotation {
84 user_ty: self.user_ty,
92 #[derive(Copy, Clone, Debug, PartialEq)]
93 pub struct Ascription<'tcx> {
94 pub user_ty: PatTyProj<'tcx>,
95 /// Variance to use when relating the type `user_ty` to the **type of the value being
96 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
97 /// have a type that is some subtype of the ascribed type.
99 /// Note that this variance does not apply for any bindings within subpatterns. The type
100 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
102 /// The only place where this field is not `Covariant` is when matching constants, where
103 /// we currently use `Contravariant` -- this is because the constant type just needs to
104 /// be "comparable" to the type of the input value. So, for example:
107 /// match x { "foo" => .. }
110 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
111 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
112 /// of the old type-check for now. See #57280 for details.
113 pub variance: ty::Variance,
114 pub user_ty_span: Span,
117 #[derive(Clone, Debug)]
118 pub enum PatKind<'tcx> {
122 ascription: Ascription<'tcx>,
123 subpattern: Pat<'tcx>,
126 /// `x`, `ref x`, `x @ P`, etc.
128 mutability: Mutability,
133 subpattern: Option<Pat<'tcx>>,
136 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
137 /// multiple variants.
139 adt_def: &'tcx AdtDef,
140 substs: SubstsRef<'tcx>,
141 variant_index: VariantIdx,
142 subpatterns: Vec<FieldPat<'tcx>>,
145 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
146 /// a single variant.
148 subpatterns: Vec<FieldPat<'tcx>>,
151 /// `box P`, `&P`, `&mut P`, etc.
153 subpattern: Pat<'tcx>,
157 value: &'tcx ty::Const<'tcx>,
160 Range(PatRange<'tcx>),
162 /// Matches against a slice, checking the length and extracting elements.
163 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
164 /// e.g., `&[ref xs @ ..]`.
166 prefix: Vec<Pat<'tcx>>,
167 slice: Option<Pat<'tcx>>,
168 suffix: Vec<Pat<'tcx>>,
171 /// Fixed match against an array; irrefutable.
173 prefix: Vec<Pat<'tcx>>,
174 slice: Option<Pat<'tcx>>,
175 suffix: Vec<Pat<'tcx>>,
178 /// An or-pattern, e.g. `p | q`.
179 /// Invariant: `pats.len() >= 2`.
181 pats: Vec<Pat<'tcx>>,
185 #[derive(Copy, Clone, Debug, PartialEq)]
186 pub struct PatRange<'tcx> {
187 pub lo: &'tcx ty::Const<'tcx>,
188 pub hi: &'tcx ty::Const<'tcx>,
192 impl<'tcx> fmt::Display for Pat<'tcx> {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 // Printing lists is a chore.
195 let mut first = true;
196 let mut start_or_continue = |s| {
204 let mut start_or_comma = || start_or_continue(", ");
207 PatKind::Wild => write!(f, "_"),
208 PatKind::AscribeUserType { ref subpattern, .. } =>
209 write!(f, "{}: _", subpattern),
210 PatKind::Binding { mutability, name, mode, ref subpattern, .. } => {
211 let is_mut = match mode {
212 BindingMode::ByValue => mutability == Mutability::Mut,
213 BindingMode::ByRef(bk) => {
215 match bk { BorrowKind::Mut { .. } => true, _ => false }
221 write!(f, "{}", name)?;
222 if let Some(ref subpattern) = *subpattern {
223 write!(f, " @ {}", subpattern)?;
227 PatKind::Variant { ref subpatterns, .. } |
228 PatKind::Leaf { ref subpatterns } => {
229 let variant = match *self.kind {
230 PatKind::Variant { adt_def, variant_index, .. } => {
231 Some(&adt_def.variants[variant_index])
233 _ => if let ty::Adt(adt, _) = self.ty.kind {
235 Some(&adt.variants[VariantIdx::new(0)])
244 if let Some(variant) = variant {
245 write!(f, "{}", variant.ident)?;
247 // Only for Adt we can have `S {...}`,
248 // which we handle separately here.
249 if variant.ctor_kind == CtorKind::Fictive {
253 for p in subpatterns {
254 if let PatKind::Wild = *p.pattern.kind {
257 let name = variant.fields[p.field.index()].ident;
258 write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
262 if printed < variant.fields.len() {
263 write!(f, "{}..", start_or_comma())?;
266 return write!(f, " }}");
270 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
271 if num_fields != 0 || variant.is_none() {
273 for i in 0..num_fields {
274 write!(f, "{}", start_or_comma())?;
276 // Common case: the field is where we expect it.
277 if let Some(p) = subpatterns.get(i) {
278 if p.field.index() == i {
279 write!(f, "{}", p.pattern)?;
284 // Otherwise, we have to go looking for it.
285 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
286 write!(f, "{}", p.pattern)?;
296 PatKind::Deref { ref subpattern } => {
298 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
299 ty::Ref(_, _, mutbl) => {
301 if mutbl == hir::MutMutable {
305 _ => bug!("{} is a bad Deref pattern type", self.ty)
307 write!(f, "{}", subpattern)
309 PatKind::Constant { value } => {
310 write!(f, "{}", value)
312 PatKind::Range(PatRange { lo, hi, end }) => {
313 write!(f, "{}", lo)?;
314 write!(f, "{}", end)?;
317 PatKind::Slice { ref prefix, ref slice, ref suffix } |
318 PatKind::Array { ref prefix, ref slice, ref suffix } => {
321 write!(f, "{}{}", start_or_comma(), p)?;
323 if let Some(ref slice) = *slice {
324 write!(f, "{}", start_or_comma())?;
327 _ => write!(f, "{}", slice)?
332 write!(f, "{}{}", start_or_comma(), p)?;
336 PatKind::Or { ref pats } => {
338 write!(f, "{}{}", start_or_continue(" | "), pat)?;
346 pub struct PatCtxt<'a, 'tcx> {
347 pub tcx: TyCtxt<'tcx>,
348 pub param_env: ty::ParamEnv<'tcx>,
349 pub tables: &'a ty::TypeckTables<'tcx>,
350 pub substs: SubstsRef<'tcx>,
351 pub errors: Vec<PatternError>,
352 include_lint_checks: bool,
355 impl<'a, 'tcx> Pat<'tcx> {
358 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
359 tables: &'a ty::TypeckTables<'tcx>,
362 let mut pcx = PatCtxt::new(tcx, param_env_and_substs, tables);
363 let result = pcx.lower_pattern(pat);
364 if !pcx.errors.is_empty() {
365 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
366 tcx.sess.delay_span_bug(pat.span, &msg);
368 debug!("Pat::from_hir({:?}) = {:?}", pat, result);
373 impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
376 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
377 tables: &'a ty::TypeckTables<'tcx>,
381 param_env: param_env_and_substs.param_env,
383 substs: param_env_and_substs.value,
385 include_lint_checks: false,
389 pub fn include_lint_checks(&mut self) -> &mut Self {
390 self.include_lint_checks = true;
394 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pat<'tcx> {
395 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
396 // pattern has the type that results *after* dereferencing. For example, in this code:
399 // match &&Some(0i32) {
400 // Some(n) => { ... },
405 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
406 // determined in rustc_typeck::check::match). The adjustments would be
408 // `vec![&&Option<i32>, &Option<i32>]`.
410 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
411 // we wrap the unadjusted pattern in `PatKind::Deref` repeatedly, consuming the
412 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
413 // gets the least-dereferenced type).
414 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
421 .fold(unadjusted_pat, |pat, ref_ty| {
422 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
426 kind: Box::new(PatKind::Deref { subpattern: pat }),
434 expr: &'tcx hir::Expr,
435 ) -> (PatKind<'tcx>, Option<Ascription<'tcx>>) {
436 match self.lower_lit(expr) {
437 PatKind::AscribeUserType {
438 ascription: lo_ascription,
439 subpattern: Pat { kind: box kind, .. },
440 } => (kind, Some(lo_ascription)),
441 kind => (kind, None),
445 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pat<'tcx> {
446 let mut ty = self.tables.node_type(pat.hir_id);
448 let kind = match pat.kind {
449 hir::PatKind::Wild => PatKind::Wild,
451 hir::PatKind::Lit(ref value) => self.lower_lit(value),
453 hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
454 let (lo, lo_ascription) = self.lower_range_expr(lo_expr);
455 let (hi, hi_ascription) = self.lower_range_expr(hi_expr);
457 let mut kind = match (lo, hi) {
458 (PatKind::Constant { value: lo }, PatKind::Constant { value: hi }) => {
459 assert_eq!(lo.ty, ty);
460 assert_eq!(hi.ty, ty);
461 let cmp = compare_const_vals(
469 (RangeEnd::Excluded, Some(Ordering::Less)) =>
470 PatKind::Range(PatRange { lo, hi, end }),
471 (RangeEnd::Excluded, _) => {
476 "lower range bound must be less than upper",
480 (RangeEnd::Included, Some(Ordering::Equal)) => {
481 PatKind::Constant { value: lo }
483 (RangeEnd::Included, Some(Ordering::Less)) => {
484 PatKind::Range(PatRange { lo, hi, end })
486 (RangeEnd::Included, _) => {
487 let mut err = struct_span_err!(
491 "lower range bound must be less than or equal to upper"
495 "lower bound larger than upper bound",
497 if self.tcx.sess.teach(&err.get_code().unwrap()) {
498 err.note("When matching against a range, the compiler \
499 verifies that the range is non-empty. Range \
500 patterns include both end-points, so this is \
501 equivalent to requiring the start of the range \
502 to be less than or equal to the end of the range.");
510 self.tcx.sess.delay_span_bug(
513 "found bad range pattern `{:?}` outside of error recovery",
522 // If we are handling a range with associated constants (e.g.
523 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
524 // constants somewhere. Have them on the range pattern.
525 for ascription in &[lo_ascription, hi_ascription] {
526 if let Some(ascription) = ascription {
527 kind = PatKind::AscribeUserType {
528 ascription: *ascription,
529 subpattern: Pat { span: pat.span, ty, kind: Box::new(kind), },
537 hir::PatKind::Path(ref qpath) => {
538 return self.lower_path(qpath, pat.hir_id, pat.span);
541 hir::PatKind::Ref(ref subpattern, _) |
542 hir::PatKind::Box(ref subpattern) => {
543 PatKind::Deref { subpattern: self.lower_pattern(subpattern) }
546 hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => {
553 kind: Box::new(self.slice_or_array_pattern(
554 pat.span, ty, prefix, slice, suffix))
559 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
560 ty::Error => { // Avoid ICE
561 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
566 "unexpanded type for vector pattern: {:?}",
571 hir::PatKind::Tuple(ref subpatterns, ddpos) => {
573 ty::Tuple(ref tys) => {
576 .enumerate_and_adjust(tys.len(), ddpos)
577 .map(|(i, subpattern)| FieldPat {
578 field: Field::new(i),
579 pattern: self.lower_pattern(subpattern)
583 PatKind::Leaf { subpatterns }
585 ty::Error => { // Avoid ICE (#50577)
586 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
588 _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty),
592 hir::PatKind::Binding(_, id, ident, ref sub) => {
593 let var_ty = self.tables.node_type(pat.hir_id);
594 if let ty::Error = var_ty.kind {
596 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
598 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
599 .expect("missing binding mode");
600 let (mutability, mode) = match bm {
601 ty::BindByValue(hir::MutMutable) =>
602 (Mutability::Mut, BindingMode::ByValue),
603 ty::BindByValue(hir::MutImmutable) =>
604 (Mutability::Not, BindingMode::ByValue),
605 ty::BindByReference(hir::MutMutable) =>
606 (Mutability::Not, BindingMode::ByRef(
607 BorrowKind::Mut { allow_two_phase_borrow: false })),
608 ty::BindByReference(hir::MutImmutable) =>
609 (Mutability::Not, BindingMode::ByRef(
610 BorrowKind::Shared)),
613 // A ref x pattern is the same node used for x, and as such it has
614 // x's type, which is &T, where we want T (the type being matched).
615 if let ty::BindByReference(_) = bm {
616 if let ty::Ref(_, rty, _) = ty.kind {
619 bug!("`ref {}` has wrong type {}", ident, ty);
629 subpattern: self.lower_opt_pattern(sub),
633 hir::PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
634 let res = self.tables.qpath_res(qpath, pat.hir_id);
635 let adt_def = match ty.kind {
636 ty::Adt(adt_def, _) => adt_def,
637 ty::Error => { // Avoid ICE (#50585)
638 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
640 _ => span_bug!(pat.span,
641 "tuple struct pattern not applied to an ADT {:?}",
644 let variant_def = adt_def.variant_of_res(res);
648 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
649 .map(|(i, field)| FieldPat {
650 field: Field::new(i),
651 pattern: self.lower_pattern(field),
655 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
658 hir::PatKind::Struct(ref qpath, ref fields, _) => {
659 let res = self.tables.qpath_res(qpath, pat.hir_id);
664 field: Field::new(self.tcx.field_index(field.hir_id,
666 pattern: self.lower_pattern(&field.pat),
671 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
674 hir::PatKind::Or(ref pats) => {
676 pats: pats.iter().map(|p| self.lower_pattern(p)).collect(),
684 kind: Box::new(kind),
688 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pat<'tcx>> {
689 pats.iter().map(|p| self.lower_pattern(p)).collect()
692 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pat<'tcx>>
694 pat.as_ref().map(|p| self.lower_pattern(p))
697 fn flatten_nested_slice_patterns(
699 prefix: Vec<Pat<'tcx>>,
700 slice: Option<Pat<'tcx>>,
701 suffix: Vec<Pat<'tcx>>)
702 -> (Vec<Pat<'tcx>>, Option<Pat<'tcx>>, Vec<Pat<'tcx>>)
704 let orig_slice = match slice {
705 Some(orig_slice) => orig_slice,
706 None => return (prefix, slice, suffix)
708 let orig_prefix = prefix;
709 let orig_suffix = suffix;
711 // dance because of intentional borrow-checker stupidity.
712 let kind = *orig_slice.kind;
714 PatKind::Slice { prefix, slice, mut suffix } |
715 PatKind::Array { prefix, slice, mut suffix } => {
716 let mut orig_prefix = orig_prefix;
718 orig_prefix.extend(prefix);
719 suffix.extend(orig_suffix);
721 (orig_prefix, slice, suffix)
724 (orig_prefix, Some(Pat {
725 kind: box kind, ..orig_slice
731 fn slice_or_array_pattern(
735 prefix: &'tcx [P<hir::Pat>],
736 slice: &'tcx Option<P<hir::Pat>>,
737 suffix: &'tcx [P<hir::Pat>])
740 let prefix = self.lower_patterns(prefix);
741 let slice = self.lower_opt_pattern(slice);
742 let suffix = self.lower_patterns(suffix);
743 let (prefix, slice, suffix) =
744 self.flatten_nested_slice_patterns(prefix, slice, suffix);
748 // matching a slice or fixed-length array
749 PatKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
752 ty::Array(_, len) => {
753 // fixed-length array
754 let len = len.eval_usize(self.tcx, self.param_env);
755 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
756 PatKind::Array { prefix: prefix, slice: slice, suffix: suffix }
760 span_bug!(span, "bad slice pattern type {:?}", ty);
765 fn lower_variant_or_leaf(
771 subpatterns: Vec<FieldPat<'tcx>>,
773 let res = match res {
774 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
775 let variant_id = self.tcx.parent(variant_ctor_id).unwrap();
776 Res::Def(DefKind::Variant, variant_id)
781 let mut kind = match res {
782 Res::Def(DefKind::Variant, variant_id) => {
783 let enum_id = self.tcx.parent(variant_id).unwrap();
784 let adt_def = self.tcx.adt_def(enum_id);
785 if adt_def.is_enum() {
786 let substs = match ty.kind {
788 ty::FnDef(_, substs) => substs,
789 ty::Error => { // Avoid ICE (#50585)
790 return PatKind::Wild;
792 _ => bug!("inappropriate type for def: {:?}", ty),
797 variant_index: adt_def.variant_index_with_id(variant_id),
801 PatKind::Leaf { subpatterns }
805 Res::Def(DefKind::Struct, _)
806 | Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _)
807 | Res::Def(DefKind::Union, _)
808 | Res::Def(DefKind::TyAlias, _)
809 | Res::Def(DefKind::AssocTy, _)
811 | Res::SelfCtor(..) => {
812 PatKind::Leaf { subpatterns }
816 self.errors.push(PatternError::NonConstPath(span));
821 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
822 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
823 kind = PatKind::AscribeUserType {
827 kind: Box::new(kind),
829 ascription: Ascription {
830 user_ty: PatTyProj::from_user_type(user_ty),
832 variance: ty::Variance::Covariant,
840 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
841 /// it to `const_to_pat`. Any other path (like enum variants without fields)
842 /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
843 fn lower_path(&mut self,
848 let ty = self.tables.node_type(id);
849 let res = self.tables.qpath_res(qpath, id);
850 let is_associated_const = match res {
851 Res::Def(DefKind::AssocConst, _) => true,
854 let kind = match res {
855 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
856 let substs = self.tables.node_substs(id);
857 match ty::Instance::resolve(
868 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
870 let pattern = self.const_to_pat(instance, value, id, span);
871 if !is_associated_const {
875 let user_provided_types = self.tables().user_provided_types();
876 return if let Some(u_ty) = user_provided_types.get(id) {
877 let user_ty = PatTyProj::from_user_type(*u_ty);
881 PatKind::AscribeUserType {
883 ascription: Ascription {
884 /// Note that use `Contravariant` here. See the
885 /// `variance` field documentation for details.
886 variance: ty::Variance::Contravariant,
899 self.tcx.sess.span_err(
901 "could not evaluate constant pattern",
908 self.errors.push(if is_associated_const {
909 PatternError::AssocConstInPattern(span)
911 PatternError::StaticInPattern(span)
917 _ => self.lower_variant_or_leaf(res, id, span, ty, vec![]),
923 kind: Box::new(kind),
927 /// Converts literals, paths and negation of literals to patterns.
928 /// The special case for negation exists to allow things like `-128_i8`
929 /// which would overflow if we tried to evaluate `128_i8` and then negate
931 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatKind<'tcx> {
933 hir::ExprKind::Lit(ref lit) => {
934 let ty = self.tables.expr_ty(expr);
935 match lit_to_const(&lit.node, self.tcx, ty, false) {
937 let instance = ty::Instance::new(
938 self.tables.local_id_root.expect("literal outside any scope"),
941 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
943 Err(LitToConstError::UnparseableFloat) => {
944 self.errors.push(PatternError::FloatBug);
947 Err(LitToConstError::Reported) => PatKind::Wild,
950 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
951 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
952 let ty = self.tables.expr_ty(expr);
953 let lit = match expr.kind {
954 hir::ExprKind::Lit(ref lit) => lit,
955 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
957 match lit_to_const(&lit.node, self.tcx, ty, true) {
959 let instance = ty::Instance::new(
960 self.tables.local_id_root.expect("literal outside any scope"),
963 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
965 Err(LitToConstError::UnparseableFloat) => {
966 self.errors.push(PatternError::FloatBug);
969 Err(LitToConstError::Reported) => PatKind::Wild,
972 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
976 /// Converts an evaluated constant to a pattern (if possible).
977 /// This means aggregate values (like structs and enums) are converted
978 /// to a pattern that matches the value (as if you'd compared via structural equality).
981 instance: ty::Instance<'tcx>,
982 cv: &'tcx ty::Const<'tcx>,
986 // This method is just a warpper handling a validity check; the heavy lifting is
987 // performed by the recursive const_to_pat_inner method, which is not meant to be
988 // invoked except by this method.
990 // once indirect_structural_match is a full fledged error, this
991 // level of indirection can be eliminated
993 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
994 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
996 let mut saw_error = false;
997 let inlined_const_as_pat = self.const_to_pat_inner(instance, cv, id, span, &mut saw_error);
999 if self.include_lint_checks && !saw_error {
1000 // If we were able to successfully convert the const to some pat, double-check
1001 // that the type of the const obeys `#[structural_match]` constraint.
1002 if let Some(non_sm_ty) = ty::search_for_structural_match_violation(self.tcx, cv.ty) {
1003 let msg = match non_sm_ty {
1004 ty::NonStructuralMatchTy::Adt(adt_def) => {
1005 let path = self.tcx.def_path_str(adt_def.did);
1007 "to use a constant of type `{}` in a pattern, \
1008 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
1013 ty::NonStructuralMatchTy::Param => {
1014 bug!("use of constant whose type is a parameter inside a pattern");
1018 // before issuing lint, double-check there even *is* a
1019 // semantic PartialEq for us to dispatch to.
1021 // (If there isn't, then we can safely issue a hard
1022 // error, because that's never worked, due to compiler
1023 // using PartialEq::eq in this scenario in the past.)
1025 let ty_is_partial_eq: bool = {
1026 let partial_eq_trait_id = self.tcx.lang_items().eq_trait().unwrap();
1027 let obligation: PredicateObligation<'_> =
1028 self.tcx.predicate_for_trait_def(self.param_env,
1029 ObligationCause::misc(span, id),
1030 partial_eq_trait_id,
1036 .enter(|infcx| infcx.predicate_may_hold(&obligation))
1039 if !ty_is_partial_eq {
1040 // span_fatal avoids ICE from resolution of non-existent method (rare case).
1041 self.tcx.sess.span_fatal(span, &msg);
1043 self.tcx.lint_hir(lint::builtin::INDIRECT_STRUCTURAL_MATCH, id, span, &msg);
1048 inlined_const_as_pat
1051 /// Recursive helper for `const_to_pat`; invoke that (instead of calling this directly).
1052 fn const_to_pat_inner(
1054 instance: ty::Instance<'tcx>,
1055 cv: &'tcx ty::Const<'tcx>,
1058 // This tracks if we signal some hard error for a given const
1059 // value, so that we will not subsequently issue an irrelevant
1060 // lint for the same const value.
1061 saw_const_match_error: &mut bool,
1064 let mut adt_subpattern = |i, variant_opt| {
1065 let field = Field::new(i);
1066 let val = crate::const_eval::const_field(
1067 self.tcx, self.param_env, variant_opt, field, cv
1069 self.const_to_pat_inner(instance, val, id, span, saw_const_match_error)
1071 let mut adt_subpatterns = |n, variant_opt| {
1073 let field = Field::new(i);
1076 pattern: adt_subpattern(i, variant_opt),
1078 }).collect::<Vec<_>>()
1082 let kind = match cv.ty.kind {
1085 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
1088 "floating-point types cannot be used in patterns",
1094 ty::Adt(adt_def, _) if adt_def.is_union() => {
1095 // Matching on union fields is unsafe, we can't hide it in constants
1096 *saw_const_match_error = true;
1097 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
1100 // keep old code until future-compat upgraded to errors.
1101 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, sym::structural_match) => {
1102 let path = self.tcx.def_path_str(adt_def.did);
1104 "to use a constant of type `{}` in a pattern, \
1105 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
1109 *saw_const_match_error = true;
1110 self.tcx.sess.span_err(span, &msg);
1113 // keep old code until future-compat upgraded to errors.
1114 ty::Ref(_, ty::TyS { kind: ty::Adt(adt_def, _), .. }, _)
1115 if !self.tcx.has_attr(adt_def.did, sym::structural_match) => {
1116 // HACK(estebank): Side-step ICE #53708, but anything other than erroring here
1117 // would be wrong. Returnging `PatKind::Wild` is not technically correct.
1118 let path = self.tcx.def_path_str(adt_def.did);
1120 "to use a constant of type `{}` in a pattern, \
1121 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
1125 *saw_const_match_error = true;
1126 self.tcx.sess.span_err(span, &msg);
1129 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
1130 let variant_index = const_variant_index(self.tcx, self.param_env, cv);
1131 let subpatterns = adt_subpatterns(
1132 adt_def.variants[variant_index].fields.len(),
1133 Some(variant_index),
1142 ty::Adt(adt_def, _) => {
1143 let struct_var = adt_def.non_enum_variant();
1145 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1148 ty::Tuple(fields) => {
1150 subpatterns: adt_subpatterns(fields.len(), None),
1153 ty::Array(_, n) => {
1155 prefix: (0..n.eval_usize(self.tcx, self.param_env))
1156 .map(|i| adt_subpattern(i as usize, None))
1172 kind: Box::new(kind),
1177 impl UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> {
1178 fn tcx(&self) -> TyCtxt<'tcx> {
1182 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1188 pub trait PatternFoldable<'tcx> : Sized {
1189 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1190 self.super_fold_with(folder)
1193 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1196 pub trait PatternFolder<'tcx> : Sized {
1197 fn fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx> {
1198 pattern.super_fold_with(self)
1201 fn fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx> {
1202 kind.super_fold_with(self)
1207 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1208 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1209 let content: T = (**self).fold_with(folder);
1214 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1215 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1216 self.iter().map(|t| t.fold_with(folder)).collect()
1220 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1221 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1222 self.as_ref().map(|t| t.fold_with(folder))
1226 macro_rules! CloneImpls {
1227 (<$lt_tcx:tt> $($ty:ty),+) => {
1229 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1230 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1239 Span, Field, Mutability, ast::Name, hir::HirId, usize, ty::Const<'tcx>,
1240 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1241 SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
1242 UserTypeProjection, PatTyProj<'tcx>
1245 impl<'tcx> PatternFoldable<'tcx> for FieldPat<'tcx> {
1246 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1248 field: self.field.fold_with(folder),
1249 pattern: self.pattern.fold_with(folder)
1254 impl<'tcx> PatternFoldable<'tcx> for Pat<'tcx> {
1255 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1256 folder.fold_pattern(self)
1259 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1261 ty: self.ty.fold_with(folder),
1262 span: self.span.fold_with(folder),
1263 kind: self.kind.fold_with(folder)
1268 impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
1269 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1270 folder.fold_pattern_kind(self)
1273 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1275 PatKind::Wild => PatKind::Wild,
1276 PatKind::AscribeUserType {
1278 ascription: Ascription {
1283 } => PatKind::AscribeUserType {
1284 subpattern: subpattern.fold_with(folder),
1285 ascription: Ascription {
1286 user_ty: user_ty.fold_with(folder),
1298 } => PatKind::Binding {
1299 mutability: mutability.fold_with(folder),
1300 name: name.fold_with(folder),
1301 mode: mode.fold_with(folder),
1302 var: var.fold_with(folder),
1303 ty: ty.fold_with(folder),
1304 subpattern: subpattern.fold_with(folder),
1311 } => PatKind::Variant {
1312 adt_def: adt_def.fold_with(folder),
1313 substs: substs.fold_with(folder),
1315 subpatterns: subpatterns.fold_with(folder)
1319 } => PatKind::Leaf {
1320 subpatterns: subpatterns.fold_with(folder),
1324 } => PatKind::Deref {
1325 subpattern: subpattern.fold_with(folder),
1329 } => PatKind::Constant {
1332 PatKind::Range(range) => PatKind::Range(range),
1337 } => PatKind::Slice {
1338 prefix: prefix.fold_with(folder),
1339 slice: slice.fold_with(folder),
1340 suffix: suffix.fold_with(folder)
1346 } => PatKind::Array {
1347 prefix: prefix.fold_with(folder),
1348 slice: slice.fold_with(folder),
1349 suffix: suffix.fold_with(folder)
1351 PatKind::Or { ref pats } => PatKind::Or { pats: pats.fold_with(folder) },
1356 pub fn compare_const_vals<'tcx>(
1358 a: &'tcx ty::Const<'tcx>,
1359 b: &'tcx ty::Const<'tcx>,
1360 param_env: ty::ParamEnv<'tcx>,
1362 ) -> Option<Ordering> {
1363 trace!("compare_const_vals: {:?}, {:?}", a, b);
1365 let from_bool = |v: bool| {
1367 Some(Ordering::Equal)
1373 let fallback = || from_bool(a == b);
1375 // Use the fallback if any type differs
1376 if a.ty != b.ty || a.ty != ty {
1380 let a_bits = a.try_eval_bits(tcx, param_env, ty);
1381 let b_bits = b.try_eval_bits(tcx, param_env, ty);
1383 if let (Some(a), Some(b)) = (a_bits, b_bits) {
1384 use ::rustc_apfloat::Float;
1385 return match ty.kind {
1386 ty::Float(ast::FloatTy::F32) => {
1387 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1388 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1391 ty::Float(ast::FloatTy::F64) => {
1392 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1393 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1397 use rustc::ty::layout::{Integer, IntegerExt};
1398 use syntax::attr::SignedInt;
1399 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
1400 let a = sign_extend(a, size);
1401 let b = sign_extend(b, size);
1402 Some((a as i128).cmp(&(b as i128)))
1404 _ => Some(a.cmp(&b)),
1408 if let ty::Str = ty.kind {
1409 match (a.val, b.val) {
1410 (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
1411 let a_bytes = get_slice_bytes(&tcx, a.val);
1412 let b_bytes = get_slice_bytes(&tcx, b.val);
1413 return from_bool(a_bytes == b_bytes);