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::*;
13 use rustc::mir::{Field, BorrowKind, Mutability};
14 use rustc::mir::{UserTypeProjection};
15 use rustc::mir::interpret::{GlobalId, ConstValue, sign_extend, AllocId, Pointer};
16 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, UserType, DefIdTree};
17 use rustc::ty::{CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations};
18 use rustc::ty::subst::{SubstsRef, Kind};
19 use rustc::ty::layout::{VariantIdx, Size};
20 use rustc::hir::{self, PatKind, RangeEnd};
21 use rustc::hir::def::{CtorOf, Res, DefKind, CtorKind};
22 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
24 use rustc_data_structures::indexed_vec::Idx;
26 use std::cmp::Ordering;
30 use syntax::symbol::sym;
33 #[derive(Clone, Debug)]
34 pub enum PatternError {
35 AssocConstInPattern(Span),
36 StaticInPattern(Span),
41 #[derive(Copy, Clone, Debug)]
42 pub enum BindingMode {
47 #[derive(Clone, Debug)]
48 pub struct FieldPattern<'tcx> {
50 pub pattern: Pattern<'tcx>,
53 #[derive(Clone, Debug)]
54 pub struct Pattern<'tcx> {
57 pub kind: Box<PatternKind<'tcx>>,
61 #[derive(Copy, Clone, Debug, PartialEq)]
62 pub struct PatternTypeProjection<'tcx> {
63 pub user_ty: CanonicalUserType<'tcx>,
66 impl<'tcx> PatternTypeProjection<'tcx> {
67 pub(crate) fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
69 user_ty: user_annotation,
73 pub(crate) fn user_ty(
75 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
76 inferred_ty: Ty<'tcx>,
78 ) -> UserTypeProjection {
80 base: annotations.push(CanonicalUserTypeAnnotation {
82 user_ty: self.user_ty,
90 #[derive(Copy, Clone, Debug, PartialEq)]
91 pub struct Ascription<'tcx> {
92 pub user_ty: PatternTypeProjection<'tcx>,
93 /// Variance to use when relating the type `user_ty` to the **type of the value being
94 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
95 /// have a type that is some subtype of the ascribed type.
97 /// Note that this variance does not apply for any bindings within subpatterns. The type
98 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
100 /// The only place where this field is not `Covariant` is when matching constants, where
101 /// we currently use `Contravariant` -- this is because the constant type just needs to
102 /// be "comparable" to the type of the input value. So, for example:
105 /// match x { "foo" => .. }
108 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
109 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
110 /// of the old type-check for now. See #57280 for details.
111 pub variance: ty::Variance,
112 pub user_ty_span: Span,
115 #[derive(Clone, Debug)]
116 pub enum PatternKind<'tcx> {
120 ascription: Ascription<'tcx>,
121 subpattern: Pattern<'tcx>,
124 /// `x`, `ref x`, `x @ P`, etc.
126 mutability: Mutability,
131 subpattern: Option<Pattern<'tcx>>,
134 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
135 /// multiple variants.
137 adt_def: &'tcx AdtDef,
138 substs: SubstsRef<'tcx>,
139 variant_index: VariantIdx,
140 subpatterns: Vec<FieldPattern<'tcx>>,
143 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
144 /// a single variant.
146 subpatterns: Vec<FieldPattern<'tcx>>,
149 /// `box P`, `&P`, `&mut P`, etc.
151 subpattern: Pattern<'tcx>,
155 value: &'tcx ty::Const<'tcx>,
158 Range(PatternRange<'tcx>),
160 /// Matches against a slice, checking the length and extracting elements.
161 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
162 /// e.g., `&[ref xs..]`.
164 prefix: Vec<Pattern<'tcx>>,
165 slice: Option<Pattern<'tcx>>,
166 suffix: Vec<Pattern<'tcx>>,
169 /// Fixed match against an array; irrefutable.
171 prefix: Vec<Pattern<'tcx>>,
172 slice: Option<Pattern<'tcx>>,
173 suffix: Vec<Pattern<'tcx>>,
177 #[derive(Copy, Clone, Debug, PartialEq)]
178 pub struct PatternRange<'tcx> {
179 pub lo: &'tcx ty::Const<'tcx>,
180 pub hi: &'tcx ty::Const<'tcx>,
185 impl<'tcx> fmt::Display for Pattern<'tcx> {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 PatternKind::Wild => write!(f, "_"),
189 PatternKind::AscribeUserType { ref subpattern, .. } =>
190 write!(f, "{}: _", subpattern),
191 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
192 let is_mut = match mode {
193 BindingMode::ByValue => mutability == Mutability::Mut,
194 BindingMode::ByRef(bk) => {
196 match bk { BorrowKind::Mut { .. } => true, _ => false }
202 write!(f, "{}", name)?;
203 if let Some(ref subpattern) = *subpattern {
204 write!(f, " @ {}", subpattern)?;
208 PatternKind::Variant { ref subpatterns, .. } |
209 PatternKind::Leaf { ref subpatterns } => {
210 let variant = match *self.kind {
211 PatternKind::Variant { adt_def, variant_index, .. } => {
212 Some(&adt_def.variants[variant_index])
214 _ => if let ty::Adt(adt, _) = self.ty.sty {
216 Some(&adt.variants[VariantIdx::new(0)])
225 let mut first = true;
226 let mut start_or_continue = || if first { first = false; "" } else { ", " };
228 if let Some(variant) = variant {
229 write!(f, "{}", variant.ident)?;
231 // Only for Adt we can have `S {...}`,
232 // which we handle separately here.
233 if variant.ctor_kind == CtorKind::Fictive {
237 for p in subpatterns {
238 if let PatternKind::Wild = *p.pattern.kind {
241 let name = variant.fields[p.field.index()].ident;
242 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
246 if printed < variant.fields.len() {
247 write!(f, "{}..", start_or_continue())?;
250 return write!(f, " }}");
254 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
255 if num_fields != 0 || variant.is_none() {
257 for i in 0..num_fields {
258 write!(f, "{}", start_or_continue())?;
260 // Common case: the field is where we expect it.
261 if let Some(p) = subpatterns.get(i) {
262 if p.field.index() == i {
263 write!(f, "{}", p.pattern)?;
268 // Otherwise, we have to go looking for it.
269 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
270 write!(f, "{}", p.pattern)?;
280 PatternKind::Deref { ref subpattern } => {
282 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
283 ty::Ref(_, _, mutbl) => {
285 if mutbl == hir::MutMutable {
289 _ => bug!("{} is a bad Deref pattern type", self.ty)
291 write!(f, "{}", subpattern)
293 PatternKind::Constant { value } => {
294 write!(f, "{}", value)
296 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
297 write!(f, "{}", lo)?;
299 RangeEnd::Included => write!(f, "..=")?,
300 RangeEnd::Excluded => write!(f, "..")?,
304 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
305 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
306 let mut first = true;
307 let mut start_or_continue = || if first { first = false; "" } else { ", " };
310 write!(f, "{}{}", start_or_continue(), p)?;
312 if let Some(ref slice) = *slice {
313 write!(f, "{}", start_or_continue())?;
315 PatternKind::Wild => {}
316 _ => write!(f, "{}", slice)?
321 write!(f, "{}{}", start_or_continue(), p)?;
329 pub struct PatternContext<'a, 'tcx: 'a> {
330 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
331 pub param_env: ty::ParamEnv<'tcx>,
332 pub tables: &'a ty::TypeckTables<'tcx>,
333 pub substs: SubstsRef<'tcx>,
334 pub errors: Vec<PatternError>,
337 impl<'a, 'tcx> Pattern<'tcx> {
338 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
339 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
340 tables: &'a ty::TypeckTables<'tcx>,
341 pat: &'tcx hir::Pat) -> Self {
342 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
343 let result = pcx.lower_pattern(pat);
344 if !pcx.errors.is_empty() {
345 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
346 tcx.sess.delay_span_bug(pat.span, &msg);
348 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
353 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
354 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
355 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
356 tables: &'a ty::TypeckTables<'tcx>) -> Self {
359 param_env: param_env_and_substs.param_env,
361 substs: param_env_and_substs.value,
366 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
367 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
368 // pattern has the type that results *after* dereferencing. For example, in this code:
371 // match &&Some(0i32) {
372 // Some(n) => { ... },
377 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
378 // determined in rustc_typeck::check::match). The adjustments would be
380 // `vec![&&Option<i32>, &Option<i32>]`.
382 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
383 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
384 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
385 // gets the least-dereferenced type).
386 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
393 .fold(unadjusted_pat, |pat, ref_ty| {
394 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
398 kind: Box::new(PatternKind::Deref { subpattern: pat }),
406 expr: &'tcx hir::Expr,
407 ) -> (PatternKind<'tcx>, Option<Ascription<'tcx>>) {
408 match self.lower_lit(expr) {
409 PatternKind::AscribeUserType {
410 ascription: lo_ascription,
411 subpattern: Pattern { kind: box kind, .. },
412 } => (kind, Some(lo_ascription)),
413 kind => (kind, None),
417 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
418 let mut ty = self.tables.node_type(pat.hir_id);
420 let kind = match pat.node {
421 PatKind::Wild => PatternKind::Wild,
423 PatKind::Lit(ref value) => self.lower_lit(value),
425 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
426 let (lo, lo_ascription) = self.lower_range_expr(lo_expr);
427 let (hi, hi_ascription) = self.lower_range_expr(hi_expr);
429 let mut kind = match (lo, hi) {
430 (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => {
431 let cmp = compare_const_vals(
435 self.param_env.and(ty),
438 (RangeEnd::Excluded, Some(Ordering::Less)) =>
439 PatternKind::Range(PatternRange { lo, hi, ty, end }),
440 (RangeEnd::Excluded, _) => {
445 "lower range bound must be less than upper",
449 (RangeEnd::Included, Some(Ordering::Equal)) => {
450 PatternKind::Constant { value: lo }
452 (RangeEnd::Included, Some(Ordering::Less)) => {
453 PatternKind::Range(PatternRange { lo, hi, ty, end })
455 (RangeEnd::Included, _) => {
456 let mut err = struct_span_err!(
460 "lower range bound must be less than or equal to upper"
464 "lower bound larger than upper bound",
466 if self.tcx.sess.teach(&err.get_code().unwrap()) {
467 err.note("When matching against a range, the compiler \
468 verifies that the range is non-empty. Range \
469 patterns include both end-points, so this is \
470 equivalent to requiring the start of the range \
471 to be less than or equal to the end of the range.");
479 self.tcx.sess.delay_span_bug(
482 "found bad range pattern `{:?}` outside of error recovery",
491 // If we are handling a range with associated constants (e.g.
492 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
493 // constants somewhere. Have them on the range pattern.
494 for ascription in &[lo_ascription, hi_ascription] {
495 if let Some(ascription) = ascription {
496 kind = PatternKind::AscribeUserType {
497 ascription: *ascription,
498 subpattern: Pattern { span: pat.span, ty, kind: Box::new(kind), },
506 PatKind::Path(ref qpath) => {
507 return self.lower_path(qpath, pat.hir_id, pat.span);
510 PatKind::Ref(ref subpattern, _) |
511 PatKind::Box(ref subpattern) => {
512 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
515 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
519 subpattern: Pattern {
522 kind: Box::new(self.slice_or_array_pattern(
523 pat.span, ty, prefix, slice, suffix))
528 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
529 ty::Error => { // Avoid ICE
530 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
535 "unexpanded type for vector pattern: {:?}",
540 PatKind::Tuple(ref subpatterns, ddpos) => {
542 ty::Tuple(ref tys) => {
545 .enumerate_and_adjust(tys.len(), ddpos)
546 .map(|(i, subpattern)| FieldPattern {
547 field: Field::new(i),
548 pattern: self.lower_pattern(subpattern)
552 PatternKind::Leaf { subpatterns }
554 ty::Error => { // Avoid ICE (#50577)
555 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
557 _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty),
561 PatKind::Binding(_, id, ident, ref sub) => {
562 let var_ty = self.tables.node_type(pat.hir_id);
563 if let ty::Error = var_ty.sty {
565 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
567 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
568 .expect("missing binding mode");
569 let (mutability, mode) = match bm {
570 ty::BindByValue(hir::MutMutable) =>
571 (Mutability::Mut, BindingMode::ByValue),
572 ty::BindByValue(hir::MutImmutable) =>
573 (Mutability::Not, BindingMode::ByValue),
574 ty::BindByReference(hir::MutMutable) =>
575 (Mutability::Not, BindingMode::ByRef(
576 BorrowKind::Mut { allow_two_phase_borrow: false })),
577 ty::BindByReference(hir::MutImmutable) =>
578 (Mutability::Not, BindingMode::ByRef(
579 BorrowKind::Shared)),
582 // A ref x pattern is the same node used for x, and as such it has
583 // x's type, which is &T, where we want T (the type being matched).
584 if let ty::BindByReference(_) = bm {
585 if let ty::Ref(_, rty, _) = ty.sty {
588 bug!("`ref {}` has wrong type {}", ident, ty);
592 PatternKind::Binding {
598 subpattern: self.lower_opt_pattern(sub),
602 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
603 let res = self.tables.qpath_res(qpath, pat.hir_id);
604 let adt_def = match ty.sty {
605 ty::Adt(adt_def, _) => adt_def,
606 ty::Error => { // Avoid ICE (#50585)
607 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
609 _ => span_bug!(pat.span,
610 "tuple struct pattern not applied to an ADT {:?}",
613 let variant_def = adt_def.variant_of_res(res);
617 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
618 .map(|(i, field)| FieldPattern {
619 field: Field::new(i),
620 pattern: self.lower_pattern(field),
624 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
627 PatKind::Struct(ref qpath, ref fields, _) => {
628 let res = self.tables.qpath_res(qpath, pat.hir_id);
633 field: Field::new(self.tcx.field_index(field.node.hir_id,
635 pattern: self.lower_pattern(&field.node.pat),
640 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
647 kind: Box::new(kind),
651 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
652 pats.iter().map(|p| self.lower_pattern(p)).collect()
655 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
657 pat.as_ref().map(|p| self.lower_pattern(p))
660 fn flatten_nested_slice_patterns(
662 prefix: Vec<Pattern<'tcx>>,
663 slice: Option<Pattern<'tcx>>,
664 suffix: Vec<Pattern<'tcx>>)
665 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
667 let orig_slice = match slice {
668 Some(orig_slice) => orig_slice,
669 None => return (prefix, slice, suffix)
671 let orig_prefix = prefix;
672 let orig_suffix = suffix;
674 // dance because of intentional borrow-checker stupidity.
675 let kind = *orig_slice.kind;
677 PatternKind::Slice { prefix, slice, mut suffix } |
678 PatternKind::Array { prefix, slice, mut suffix } => {
679 let mut orig_prefix = orig_prefix;
681 orig_prefix.extend(prefix);
682 suffix.extend(orig_suffix);
684 (orig_prefix, slice, suffix)
687 (orig_prefix, Some(Pattern {
688 kind: box kind, ..orig_slice
694 fn slice_or_array_pattern(
698 prefix: &'tcx [P<hir::Pat>],
699 slice: &'tcx Option<P<hir::Pat>>,
700 suffix: &'tcx [P<hir::Pat>])
703 let prefix = self.lower_patterns(prefix);
704 let slice = self.lower_opt_pattern(slice);
705 let suffix = self.lower_patterns(suffix);
706 let (prefix, slice, suffix) =
707 self.flatten_nested_slice_patterns(prefix, slice, suffix);
711 // matching a slice or fixed-length array
712 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
715 ty::Array(_, len) => {
716 // fixed-length array
717 let len = len.unwrap_usize(self.tcx);
718 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
719 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
723 span_bug!(span, "bad slice pattern type {:?}", ty);
728 fn lower_variant_or_leaf(
734 subpatterns: Vec<FieldPattern<'tcx>>,
735 ) -> PatternKind<'tcx> {
736 let res = match res {
737 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
738 let variant_id = self.tcx.parent(variant_ctor_id).unwrap();
739 Res::Def(DefKind::Variant, variant_id)
744 let mut kind = match res {
745 Res::Def(DefKind::Variant, variant_id) => {
746 let enum_id = self.tcx.parent(variant_id).unwrap();
747 let adt_def = self.tcx.adt_def(enum_id);
748 if adt_def.is_enum() {
749 let substs = match ty.sty {
751 ty::FnDef(_, substs) => substs,
752 ty::Error => { // Avoid ICE (#50585)
753 return PatternKind::Wild;
755 _ => bug!("inappropriate type for def: {:?}", ty),
757 PatternKind::Variant {
760 variant_index: adt_def.variant_index_with_id(variant_id),
764 PatternKind::Leaf { subpatterns }
768 Res::Def(DefKind::Struct, _)
769 | Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _)
770 | Res::Def(DefKind::Union, _)
771 | Res::Def(DefKind::TyAlias, _)
772 | Res::Def(DefKind::AssocTy, _)
774 | Res::SelfCtor(..) => {
775 PatternKind::Leaf { subpatterns }
779 self.errors.push(PatternError::NonConstPath(span));
784 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
785 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
786 kind = PatternKind::AscribeUserType {
787 subpattern: Pattern {
790 kind: Box::new(kind),
792 ascription: Ascription {
793 user_ty: PatternTypeProjection::from_user_type(user_ty),
795 variance: ty::Variance::Covariant,
803 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
804 /// it to `const_to_pat`. Any other path (like enum variants without fields)
805 /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
806 fn lower_path(&mut self,
811 let ty = self.tables.node_type(id);
812 let res = self.tables.qpath_res(qpath, id);
813 let is_associated_const = match res {
814 Res::Def(DefKind::AssocConst, _) => true,
817 let kind = match res {
818 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
819 let substs = self.tables.node_substs(id);
820 match ty::Instance::resolve(
831 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
833 let pattern = self.const_to_pat(instance, value, id, span);
834 if !is_associated_const {
838 let user_provided_types = self.tables().user_provided_types();
839 return if let Some(u_ty) = user_provided_types.get(id) {
840 let user_ty = PatternTypeProjection::from_user_type(*u_ty);
844 PatternKind::AscribeUserType {
846 ascription: Ascription {
847 /// Note that use `Contravariant` here. See the
848 /// `variance` field documentation for details.
849 variance: ty::Variance::Contravariant,
862 self.tcx.sess.span_err(
864 "could not evaluate constant pattern",
871 self.errors.push(if is_associated_const {
872 PatternError::AssocConstInPattern(span)
874 PatternError::StaticInPattern(span)
880 _ => self.lower_variant_or_leaf(res, id, span, ty, vec![]),
886 kind: Box::new(kind),
890 /// Converts literals, paths and negation of literals to patterns.
891 /// The special case for negation exists to allow things like `-128_i8`
892 /// which would overflow if we tried to evaluate `128_i8` and then negate
894 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
896 hir::ExprKind::Lit(ref lit) => {
897 let ty = self.tables.expr_ty(expr);
898 match lit_to_const(&lit.node, self.tcx, ty, false) {
900 let instance = ty::Instance::new(
901 self.tables.local_id_root.expect("literal outside any scope"),
904 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
906 Err(LitToConstError::UnparseableFloat) => {
907 self.errors.push(PatternError::FloatBug);
910 Err(LitToConstError::Reported) => PatternKind::Wild,
913 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
914 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
915 let ty = self.tables.expr_ty(expr);
916 let lit = match expr.node {
917 hir::ExprKind::Lit(ref lit) => lit,
918 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
920 match lit_to_const(&lit.node, self.tcx, ty, true) {
922 let instance = ty::Instance::new(
923 self.tables.local_id_root.expect("literal outside any scope"),
926 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
928 Err(LitToConstError::UnparseableFloat) => {
929 self.errors.push(PatternError::FloatBug);
932 Err(LitToConstError::Reported) => PatternKind::Wild,
935 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
939 /// Converts an evaluated constant to a pattern (if possible).
940 /// This means aggregate values (like structs and enums) are converted
941 /// to a pattern that matches the value (as if you'd compared via equality).
944 instance: ty::Instance<'tcx>,
945 cv: &'tcx ty::Const<'tcx>,
949 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
950 let adt_subpattern = |i, variant_opt| {
951 let field = Field::new(i);
952 let val = crate::const_eval::const_field(
953 self.tcx, self.param_env, variant_opt, field, cv
955 self.const_to_pat(instance, val, id, span)
957 let adt_subpatterns = |n, variant_opt| {
959 let field = Field::new(i);
962 pattern: adt_subpattern(i, variant_opt),
964 }).collect::<Vec<_>>()
966 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
967 let kind = match cv.ty.sty {
970 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
973 "floating-point types cannot be used in patterns",
975 PatternKind::Constant {
979 ty::Adt(adt_def, _) if adt_def.is_union() => {
980 // Matching on union fields is unsafe, we can't hide it in constants
981 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
984 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, sym::structural_match) => {
985 let path = self.tcx.def_path_str(adt_def.did);
987 "to use a constant of type `{}` in a pattern, \
988 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
992 self.tcx.sess.span_err(span, &msg);
995 ty::Ref(_, ty::TyS { sty: ty::Adt(adt_def, _), .. }, _)
996 if !self.tcx.has_attr(adt_def.did, sym::structural_match) => {
997 // HACK(estebank): Side-step ICE #53708, but anything other than erroring here
998 // would be wrong. Returnging `PatternKind::Wild` is not technically correct.
999 let path = self.tcx.def_path_str(adt_def.did);
1001 "to use a constant of type `{}` in a pattern, \
1002 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
1006 self.tcx.sess.span_err(span, &msg);
1009 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
1010 let variant_index = const_variant_index(self.tcx, self.param_env, cv);
1011 let subpatterns = adt_subpatterns(
1012 adt_def.variants[variant_index].fields.len(),
1013 Some(variant_index),
1015 PatternKind::Variant {
1022 ty::Adt(adt_def, _) => {
1023 let struct_var = adt_def.non_enum_variant();
1025 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1028 ty::Tuple(fields) => {
1030 subpatterns: adt_subpatterns(fields.len(), None),
1033 ty::Array(_, n) => {
1034 PatternKind::Array {
1035 prefix: (0..n.unwrap_usize(self.tcx))
1036 .map(|i| adt_subpattern(i as usize, None))
1043 PatternKind::Constant {
1052 kind: Box::new(kind),
1057 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1058 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1062 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1068 pub trait PatternFoldable<'tcx> : Sized {
1069 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1070 self.super_fold_with(folder)
1073 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1076 pub trait PatternFolder<'tcx> : Sized {
1077 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1078 pattern.super_fold_with(self)
1081 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1082 kind.super_fold_with(self)
1087 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1088 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1089 let content: T = (**self).fold_with(folder);
1094 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1095 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1096 self.iter().map(|t| t.fold_with(folder)).collect()
1100 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1101 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1102 self.as_ref().map(|t| t.fold_with(folder))
1106 macro_rules! CloneImpls {
1107 (<$lt_tcx:tt> $($ty:ty),+) => {
1109 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1110 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1119 Span, Field, Mutability, ast::Name, hir::HirId, usize, ty::Const<'tcx>,
1120 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1121 SubstsRef<'tcx>, &'tcx Kind<'tcx>, UserType<'tcx>,
1122 UserTypeProjection, PatternTypeProjection<'tcx>
1125 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1126 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1128 field: self.field.fold_with(folder),
1129 pattern: self.pattern.fold_with(folder)
1134 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1135 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1136 folder.fold_pattern(self)
1139 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1141 ty: self.ty.fold_with(folder),
1142 span: self.span.fold_with(folder),
1143 kind: self.kind.fold_with(folder)
1148 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1149 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1150 folder.fold_pattern_kind(self)
1153 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1155 PatternKind::Wild => PatternKind::Wild,
1156 PatternKind::AscribeUserType {
1158 ascription: Ascription {
1163 } => PatternKind::AscribeUserType {
1164 subpattern: subpattern.fold_with(folder),
1165 ascription: Ascription {
1166 user_ty: user_ty.fold_with(folder),
1171 PatternKind::Binding {
1178 } => PatternKind::Binding {
1179 mutability: mutability.fold_with(folder),
1180 name: name.fold_with(folder),
1181 mode: mode.fold_with(folder),
1182 var: var.fold_with(folder),
1183 ty: ty.fold_with(folder),
1184 subpattern: subpattern.fold_with(folder),
1186 PatternKind::Variant {
1191 } => PatternKind::Variant {
1192 adt_def: adt_def.fold_with(folder),
1193 substs: substs.fold_with(folder),
1195 subpatterns: subpatterns.fold_with(folder)
1199 } => PatternKind::Leaf {
1200 subpatterns: subpatterns.fold_with(folder),
1202 PatternKind::Deref {
1204 } => PatternKind::Deref {
1205 subpattern: subpattern.fold_with(folder),
1207 PatternKind::Constant {
1209 } => PatternKind::Constant {
1212 PatternKind::Range(PatternRange {
1217 }) => PatternKind::Range(PatternRange {
1220 ty: ty.fold_with(folder),
1223 PatternKind::Slice {
1227 } => PatternKind::Slice {
1228 prefix: prefix.fold_with(folder),
1229 slice: slice.fold_with(folder),
1230 suffix: suffix.fold_with(folder)
1232 PatternKind::Array {
1236 } => PatternKind::Array {
1237 prefix: prefix.fold_with(folder),
1238 slice: slice.fold_with(folder),
1239 suffix: suffix.fold_with(folder)
1245 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1246 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1247 a: &'tcx ty::Const<'tcx>,
1248 b: &'tcx ty::Const<'tcx>,
1249 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1250 ) -> Option<Ordering> {
1251 trace!("compare_const_vals: {:?}, {:?}", a, b);
1253 let from_bool = |v: bool| {
1255 Some(Ordering::Equal)
1261 let fallback = || from_bool(a == b);
1263 // Use the fallback if any type differs
1264 if a.ty != b.ty || a.ty != ty.value {
1268 // FIXME: This should use assert_bits(ty) instead of use_bits
1269 // but triggers possibly bugs due to mismatching of arrays and slices
1270 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1271 use ::rustc_apfloat::Float;
1272 return match ty.value.sty {
1273 ty::Float(ast::FloatTy::F32) => {
1274 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1275 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1278 ty::Float(ast::FloatTy::F64) => {
1279 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1280 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1284 use rustc::ty::layout::{Integer, IntegerExt};
1285 use syntax::attr::SignedInt;
1286 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
1287 let a = sign_extend(a, size);
1288 let b = sign_extend(b, size);
1289 Some((a as i128).cmp(&(b as i128)))
1291 _ => Some(a.cmp(&b)),
1295 if let ty::Str = ty.value.sty {
1296 match (a.val, b.val) {
1298 ConstValue::Slice { data: alloc_a, start: offset_a, end: end_a },
1299 ConstValue::Slice { data: alloc_b, start: offset_b, end: end_b },
1301 let len_a = end_a - offset_a;
1302 let len_b = end_b - offset_b;
1303 let a = alloc_a.get_bytes(
1305 // invent a pointer, only the offset is relevant anyway
1306 Pointer::new(AllocId(0), Size::from_bytes(offset_a as u64)),
1307 Size::from_bytes(len_a as u64),
1309 let b = alloc_b.get_bytes(
1311 // invent a pointer, only the offset is relevant anyway
1312 Pointer::new(AllocId(0), Size::from_bytes(offset_b as u64)),
1313 Size::from_bytes(len_b as u64),
1315 if let (Ok(a), Ok(b)) = (a, b) {
1316 return from_bool(a == b);