1 //! Code to validate patterns/matches
6 pub use self::check_match::check_crate;
7 pub(crate) use self::check_match::check_match;
9 use const_eval::{const_field, const_variant_index};
11 use hair::util::UserAnnotatedTyHelpers;
12 use hair::constant::*;
14 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
15 use rustc::mir::{ProjectionElem, UserTypeProjection};
16 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
17 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, Lift};
18 use rustc::ty::{CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, UserTypeAnnotation};
19 use rustc::ty::subst::{Substs, Kind};
20 use rustc::ty::layout::VariantIdx;
21 use rustc::hir::{self, PatKind, RangeEnd};
22 use rustc::hir::def::{Def, CtorKind};
23 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
25 use rustc_data_structures::indexed_vec::Idx;
27 use std::cmp::Ordering;
33 #[derive(Clone, Debug)]
34 pub enum PatternError {
35 AssociatedConstInPattern(Span),
36 StaticInPattern(Span),
41 #[derive(Copy, Clone, Debug)]
42 pub enum BindingMode<'tcx> {
44 ByRef(Region<'tcx>, BorrowKind),
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(Clone, Debug)]
62 pub struct PatternTypeProjection<'tcx> {
63 pub base: CanonicalUserTypeAnnotation<'tcx>,
64 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
67 impl<'tcx> PatternTypeProjection<'tcx> {
68 pub(crate) fn from_user_type(user_annotation: CanonicalUserTypeAnnotation<'tcx>) -> Self {
70 base: user_annotation,
75 pub(crate) fn user_ty(
77 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
79 ) -> UserTypeProjection<'tcx> {
81 base: annotations.push((span, self.base)),
87 #[derive(Clone, Debug)]
88 pub enum PatternKind<'tcx> {
92 user_ty: PatternTypeProjection<'tcx>,
93 subpattern: Pattern<'tcx>,
97 /// x, ref x, x @ P, etc
99 mutability: Mutability,
101 mode: BindingMode<'tcx>,
104 subpattern: Option<Pattern<'tcx>>,
107 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
109 adt_def: &'tcx AdtDef,
110 substs: &'tcx Substs<'tcx>,
111 variant_index: VariantIdx,
112 subpatterns: Vec<FieldPattern<'tcx>>,
115 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
117 subpatterns: Vec<FieldPattern<'tcx>>,
120 /// box P, &P, &mut P, etc
122 subpattern: Pattern<'tcx>,
126 value: ty::Const<'tcx>,
129 Range(PatternRange<'tcx>),
131 /// matches against a slice, checking the length and extracting elements.
132 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
133 /// e.g., `&[ref xs..]`.
135 prefix: Vec<Pattern<'tcx>>,
136 slice: Option<Pattern<'tcx>>,
137 suffix: Vec<Pattern<'tcx>>,
140 /// fixed match against an array, irrefutable
142 prefix: Vec<Pattern<'tcx>>,
143 slice: Option<Pattern<'tcx>>,
144 suffix: Vec<Pattern<'tcx>>,
148 #[derive(Clone, Copy, Debug, PartialEq)]
149 pub struct PatternRange<'tcx> {
150 pub lo: ty::Const<'tcx>,
151 pub hi: ty::Const<'tcx>,
156 impl<'tcx> fmt::Display for Pattern<'tcx> {
157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159 PatternKind::Wild => write!(f, "_"),
160 PatternKind::AscribeUserType { ref subpattern, .. } =>
161 write!(f, "{}: _", subpattern),
162 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
163 let is_mut = match mode {
164 BindingMode::ByValue => mutability == Mutability::Mut,
165 BindingMode::ByRef(_, bk) => {
167 match bk { BorrowKind::Mut { .. } => true, _ => false }
173 write!(f, "{}", name)?;
174 if let Some(ref subpattern) = *subpattern {
175 write!(f, " @ {}", subpattern)?;
179 PatternKind::Variant { ref subpatterns, .. } |
180 PatternKind::Leaf { ref subpatterns } => {
181 let variant = match *self.kind {
182 PatternKind::Variant { adt_def, variant_index, .. } => {
183 Some(&adt_def.variants[variant_index])
185 _ => if let ty::Adt(adt, _) = self.ty.sty {
187 Some(&adt.variants[VariantIdx::new(0)])
196 let mut first = true;
197 let mut start_or_continue = || if first { first = false; "" } else { ", " };
199 if let Some(variant) = variant {
200 write!(f, "{}", variant.ident)?;
202 // Only for Adt we can have `S {...}`,
203 // which we handle separately here.
204 if variant.ctor_kind == CtorKind::Fictive {
208 for p in subpatterns {
209 if let PatternKind::Wild = *p.pattern.kind {
212 let name = variant.fields[p.field.index()].ident;
213 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
217 if printed < variant.fields.len() {
218 write!(f, "{}..", start_or_continue())?;
221 return write!(f, " }}");
225 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
226 if num_fields != 0 || variant.is_none() {
228 for i in 0..num_fields {
229 write!(f, "{}", start_or_continue())?;
231 // Common case: the field is where we expect it.
232 if let Some(p) = subpatterns.get(i) {
233 if p.field.index() == i {
234 write!(f, "{}", p.pattern)?;
239 // Otherwise, we have to go looking for it.
240 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
241 write!(f, "{}", p.pattern)?;
251 PatternKind::Deref { ref subpattern } => {
253 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
254 ty::Ref(_, _, mutbl) => {
256 if mutbl == hir::MutMutable {
260 _ => bug!("{} is a bad Deref pattern type", self.ty)
262 write!(f, "{}", subpattern)
264 PatternKind::Constant { value } => {
265 fmt_const_val(f, value)
267 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
268 fmt_const_val(f, lo)?;
270 RangeEnd::Included => write!(f, "..=")?,
271 RangeEnd::Excluded => write!(f, "..")?,
275 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
276 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
277 let mut first = true;
278 let mut start_or_continue = || if first { first = false; "" } else { ", " };
281 write!(f, "{}{}", start_or_continue(), p)?;
283 if let Some(ref slice) = *slice {
284 write!(f, "{}", start_or_continue())?;
286 PatternKind::Wild => {}
287 _ => write!(f, "{}", slice)?
292 write!(f, "{}{}", start_or_continue(), p)?;
300 pub struct PatternContext<'a, 'tcx: 'a> {
301 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
302 pub param_env: ty::ParamEnv<'tcx>,
303 pub tables: &'a ty::TypeckTables<'tcx>,
304 pub substs: &'tcx Substs<'tcx>,
305 pub errors: Vec<PatternError>,
308 impl<'a, 'tcx> Pattern<'tcx> {
309 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
310 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
311 tables: &'a ty::TypeckTables<'tcx>,
312 pat: &'tcx hir::Pat) -> Self {
313 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
314 let result = pcx.lower_pattern(pat);
315 if !pcx.errors.is_empty() {
316 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
317 tcx.sess.delay_span_bug(pat.span, &msg);
319 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
324 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
325 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
326 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
327 tables: &'a ty::TypeckTables<'tcx>) -> Self {
330 param_env: param_env_and_substs.param_env,
332 substs: param_env_and_substs.value,
337 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
338 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
339 // pattern has the type that results *after* dereferencing. For example, in this code:
342 // match &&Some(0i32) {
343 // Some(n) => { ... },
348 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
349 // determined in rustc_typeck::check::match). The adjustments would be
351 // `vec![&&Option<i32>, &Option<i32>]`.
353 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
354 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
355 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
356 // gets the least-dereferenced type).
357 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
364 .fold(unadjusted_pat, |pat, ref_ty| {
365 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
369 kind: Box::new(PatternKind::Deref { subpattern: pat }),
375 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
376 let mut ty = self.tables.node_id_to_type(pat.hir_id);
378 let kind = match pat.node {
379 PatKind::Wild => PatternKind::Wild,
381 PatKind::Lit(ref value) => self.lower_lit(value),
383 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
384 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
385 (PatternKind::Constant { value: lo },
386 PatternKind::Constant { value: hi }) => {
387 use std::cmp::Ordering;
388 let cmp = compare_const_vals(
392 self.param_env.and(ty),
395 (RangeEnd::Excluded, Some(Ordering::Less)) =>
396 PatternKind::Range(PatternRange { lo, hi, ty, end }),
397 (RangeEnd::Excluded, _) => {
402 "lower range bound must be less than upper",
406 (RangeEnd::Included, Some(Ordering::Equal)) => {
407 PatternKind::Constant { value: lo }
409 (RangeEnd::Included, Some(Ordering::Less)) => {
410 PatternKind::Range(PatternRange { lo, hi, ty, end })
412 (RangeEnd::Included, _) => {
413 let mut err = struct_span_err!(
417 "lower range bound must be less than or equal to upper"
421 "lower bound larger than upper bound",
423 if self.tcx.sess.teach(&err.get_code().unwrap()) {
424 err.note("When matching against a range, the compiler \
425 verifies that the range is non-empty. Range \
426 patterns include both end-points, so this is \
427 equivalent to requiring the start of the range \
428 to be less than or equal to the end of the range.");
435 _ => PatternKind::Wild
439 PatKind::Path(ref qpath) => {
440 return self.lower_path(qpath, pat.hir_id, pat.span);
443 PatKind::Ref(ref subpattern, _) |
444 PatKind::Box(ref subpattern) => {
445 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
448 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
452 subpattern: Pattern {
455 kind: Box::new(self.slice_or_array_pattern(
456 pat.span, ty, prefix, slice, suffix))
461 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
462 ty::Error => { // Avoid ICE
463 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
468 "unexpanded type for vector pattern: {:?}",
473 PatKind::Tuple(ref subpatterns, ddpos) => {
475 ty::Tuple(ref tys) => {
478 .enumerate_and_adjust(tys.len(), ddpos)
479 .map(|(i, subpattern)| FieldPattern {
480 field: Field::new(i),
481 pattern: self.lower_pattern(subpattern)
485 PatternKind::Leaf { subpatterns }
487 ty::Error => { // Avoid ICE (#50577)
488 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
490 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
494 PatKind::Binding(_, id, ident, ref sub) => {
495 let var_ty = self.tables.node_id_to_type(pat.hir_id);
496 let region = match var_ty.sty {
497 ty::Ref(r, _, _) => Some(r),
498 ty::Error => { // Avoid ICE
499 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
503 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
504 .expect("missing binding mode");
505 let (mutability, mode) = match bm {
506 ty::BindByValue(hir::MutMutable) =>
507 (Mutability::Mut, BindingMode::ByValue),
508 ty::BindByValue(hir::MutImmutable) =>
509 (Mutability::Not, BindingMode::ByValue),
510 ty::BindByReference(hir::MutMutable) =>
511 (Mutability::Not, BindingMode::ByRef(
512 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
513 ty::BindByReference(hir::MutImmutable) =>
514 (Mutability::Not, BindingMode::ByRef(
515 region.unwrap(), BorrowKind::Shared)),
518 // A ref x pattern is the same node used for x, and as such it has
519 // x's type, which is &T, where we want T (the type being matched).
520 if let ty::BindByReference(_) = bm {
521 if let ty::Ref(_, rty, _) = ty.sty {
524 bug!("`ref {}` has wrong type {}", ident, ty);
528 PatternKind::Binding {
534 subpattern: self.lower_opt_pattern(sub),
538 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
539 let def = self.tables.qpath_def(qpath, pat.hir_id);
540 let adt_def = match ty.sty {
541 ty::Adt(adt_def, _) => adt_def,
542 ty::Error => { // Avoid ICE (#50585)
543 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
545 _ => span_bug!(pat.span,
546 "tuple struct pattern not applied to an ADT {:?}",
549 let variant_def = adt_def.variant_of_def(def);
553 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
554 .map(|(i, field)| FieldPattern {
555 field: Field::new(i),
556 pattern: self.lower_pattern(field),
560 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
563 PatKind::Struct(ref qpath, ref fields, _) => {
564 let def = self.tables.qpath_def(qpath, pat.hir_id);
569 field: Field::new(self.tcx.field_index(field.node.id,
571 pattern: self.lower_pattern(&field.node.pat),
576 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
583 kind: Box::new(kind),
587 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
588 pats.iter().map(|p| self.lower_pattern(p)).collect()
591 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
593 pat.as_ref().map(|p| self.lower_pattern(p))
596 fn flatten_nested_slice_patterns(
598 prefix: Vec<Pattern<'tcx>>,
599 slice: Option<Pattern<'tcx>>,
600 suffix: Vec<Pattern<'tcx>>)
601 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
603 let orig_slice = match slice {
604 Some(orig_slice) => orig_slice,
605 None => return (prefix, slice, suffix)
607 let orig_prefix = prefix;
608 let orig_suffix = suffix;
610 // dance because of intentional borrow-checker stupidity.
611 let kind = *orig_slice.kind;
613 PatternKind::Slice { prefix, slice, mut suffix } |
614 PatternKind::Array { prefix, slice, mut suffix } => {
615 let mut orig_prefix = orig_prefix;
617 orig_prefix.extend(prefix);
618 suffix.extend(orig_suffix);
620 (orig_prefix, slice, suffix)
623 (orig_prefix, Some(Pattern {
624 kind: box kind, ..orig_slice
630 fn slice_or_array_pattern(
634 prefix: &'tcx [P<hir::Pat>],
635 slice: &'tcx Option<P<hir::Pat>>,
636 suffix: &'tcx [P<hir::Pat>])
639 let prefix = self.lower_patterns(prefix);
640 let slice = self.lower_opt_pattern(slice);
641 let suffix = self.lower_patterns(suffix);
642 let (prefix, slice, suffix) =
643 self.flatten_nested_slice_patterns(prefix, slice, suffix);
647 // matching a slice or fixed-length array
648 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
651 ty::Array(_, len) => {
652 // fixed-length array
653 let len = len.unwrap_usize(self.tcx);
654 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
655 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
659 span_bug!(span, "bad slice pattern type {:?}", ty);
664 fn lower_variant_or_leaf(
670 subpatterns: Vec<FieldPattern<'tcx>>,
671 ) -> PatternKind<'tcx> {
672 let mut kind = match def {
673 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
674 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
675 let adt_def = self.tcx.adt_def(enum_id);
676 if adt_def.is_enum() {
677 let substs = match ty.sty {
679 ty::FnDef(_, substs) => substs,
680 ty::Error => { // Avoid ICE (#50585)
681 return PatternKind::Wild;
683 _ => bug!("inappropriate type for def: {:?}", ty.sty),
685 PatternKind::Variant {
688 variant_index: adt_def.variant_index_with_id(variant_id),
692 PatternKind::Leaf { subpatterns }
696 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
697 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
698 PatternKind::Leaf { subpatterns }
702 self.errors.push(PatternError::NonConstPath(span));
707 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
708 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
709 kind = PatternKind::AscribeUserType {
710 subpattern: Pattern {
713 kind: Box::new(kind),
715 user_ty: PatternTypeProjection::from_user_type(user_ty),
723 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
724 /// it to `const_to_pat`. Any other path (like enum variants without fields)
725 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
726 fn lower_path(&mut self,
731 let ty = self.tables.node_id_to_type(id);
732 let def = self.tables.qpath_def(qpath, id);
733 let is_associated_const = match def {
734 Def::AssociatedConst(_) => true,
737 let kind = match def {
738 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
739 let substs = self.tables.node_substs(id);
740 match ty::Instance::resolve(
751 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
753 let pattern = self.const_to_pat(instance, value, id, span);
754 if !is_associated_const {
758 let user_provided_types = self.tables().user_provided_types();
759 return if let Some(u_ty) = user_provided_types.get(id) {
760 let user_ty = PatternTypeProjection::from_user_type(*u_ty);
764 PatternKind::AscribeUserType {
777 self.tcx.sess.span_err(
779 "could not evaluate constant pattern",
786 self.errors.push(if is_associated_const {
787 PatternError::AssociatedConstInPattern(span)
789 PatternError::StaticInPattern(span)
795 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
801 kind: Box::new(kind),
805 /// Converts literals, paths and negation of literals to patterns.
806 /// The special case for negation exists to allow things like -128i8
807 /// which would overflow if we tried to evaluate 128i8 and then negate
809 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
811 hir::ExprKind::Lit(ref lit) => {
812 let ty = self.tables.expr_ty(expr);
813 match lit_to_const(&lit.node, self.tcx, ty, false) {
815 let instance = ty::Instance::new(
816 self.tables.local_id_root.expect("literal outside any scope"),
819 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
821 Err(LitToConstError::UnparseableFloat) => {
822 self.errors.push(PatternError::FloatBug);
825 Err(LitToConstError::Reported) => PatternKind::Wild,
828 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
829 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
830 let ty = self.tables.expr_ty(expr);
831 let lit = match expr.node {
832 hir::ExprKind::Lit(ref lit) => lit,
833 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
835 match lit_to_const(&lit.node, self.tcx, ty, true) {
837 let instance = ty::Instance::new(
838 self.tables.local_id_root.expect("literal outside any scope"),
841 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
843 Err(LitToConstError::UnparseableFloat) => {
844 self.errors.push(PatternError::FloatBug);
847 Err(LitToConstError::Reported) => PatternKind::Wild,
850 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
854 /// Converts an evaluated constant to a pattern (if possible).
855 /// This means aggregate values (like structs and enums) are converted
856 /// to a pattern that matches the value (as if you'd compare via eq).
859 instance: ty::Instance<'tcx>,
864 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
865 let adt_subpattern = |i, variant_opt| {
866 let field = Field::new(i);
867 let val = const_field(
868 self.tcx, self.param_env, instance,
869 variant_opt, field, cv,
870 ).expect("field access failed");
871 self.const_to_pat(instance, val, id, span)
873 let adt_subpatterns = |n, variant_opt| {
875 let field = Field::new(i);
878 pattern: adt_subpattern(i, variant_opt),
880 }).collect::<Vec<_>>()
882 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
883 let kind = match cv.ty.sty {
885 let id = self.tcx.hir().hir_to_node_id(id);
887 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
890 "floating-point types cannot be used in patterns",
892 PatternKind::Constant {
896 ty::Adt(adt_def, _) if adt_def.is_union() => {
897 // Matching on union fields is unsafe, we can't hide it in constants
898 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
901 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
902 let msg = format!("to use a constant of type `{}` in a pattern, \
903 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
904 self.tcx.item_path_str(adt_def.did),
905 self.tcx.item_path_str(adt_def.did));
906 self.tcx.sess.span_err(span, &msg);
909 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
910 let variant_index = const_variant_index(
911 self.tcx, self.param_env, instance, cv
912 ).expect("const_variant_index failed");
913 let subpatterns = adt_subpatterns(
914 adt_def.variants[variant_index].fields.len(),
917 PatternKind::Variant {
924 ty::Adt(adt_def, _) => {
925 let struct_var = adt_def.non_enum_variant();
927 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
930 ty::Tuple(fields) => {
932 subpatterns: adt_subpatterns(fields.len(), None),
937 prefix: (0..n.unwrap_usize(self.tcx))
938 .map(|i| adt_subpattern(i as usize, None))
945 PatternKind::Constant {
954 kind: Box::new(kind),
959 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
960 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
964 fn tables(&self) -> &ty::TypeckTables<'tcx> {
970 pub trait PatternFoldable<'tcx> : Sized {
971 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
972 self.super_fold_with(folder)
975 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
978 pub trait PatternFolder<'tcx> : Sized {
979 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
980 pattern.super_fold_with(self)
983 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
984 kind.super_fold_with(self)
989 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
990 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
991 let content: T = (**self).fold_with(folder);
996 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
997 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
998 self.iter().map(|t| t.fold_with(folder)).collect()
1002 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1003 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1004 self.as_ref().map(|t| t.fold_with(folder))
1008 macro_rules! CloneImpls {
1009 (<$lt_tcx:tt> $($ty:ty),+) => {
1011 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1012 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1021 Span, Field, Mutability, ast::Name, ast::NodeId, usize, ty::Const<'tcx>,
1022 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
1023 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>,
1024 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1027 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1028 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1030 field: self.field.fold_with(folder),
1031 pattern: self.pattern.fold_with(folder)
1036 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1037 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1038 folder.fold_pattern(self)
1041 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1043 ty: self.ty.fold_with(folder),
1044 span: self.span.fold_with(folder),
1045 kind: self.kind.fold_with(folder)
1050 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1051 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1052 folder.fold_pattern_kind(self)
1055 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1057 PatternKind::Wild => PatternKind::Wild,
1058 PatternKind::AscribeUserType {
1062 } => PatternKind::AscribeUserType {
1063 subpattern: subpattern.fold_with(folder),
1064 user_ty: user_ty.fold_with(folder),
1067 PatternKind::Binding {
1074 } => PatternKind::Binding {
1075 mutability: mutability.fold_with(folder),
1076 name: name.fold_with(folder),
1077 mode: mode.fold_with(folder),
1078 var: var.fold_with(folder),
1079 ty: ty.fold_with(folder),
1080 subpattern: subpattern.fold_with(folder),
1082 PatternKind::Variant {
1087 } => PatternKind::Variant {
1088 adt_def: adt_def.fold_with(folder),
1089 substs: substs.fold_with(folder),
1091 subpatterns: subpatterns.fold_with(folder)
1095 } => PatternKind::Leaf {
1096 subpatterns: subpatterns.fold_with(folder),
1098 PatternKind::Deref {
1100 } => PatternKind::Deref {
1101 subpattern: subpattern.fold_with(folder),
1103 PatternKind::Constant {
1105 } => PatternKind::Constant {
1106 value: value.fold_with(folder)
1108 PatternKind::Range(PatternRange {
1113 }) => PatternKind::Range(PatternRange {
1114 lo: lo.fold_with(folder),
1115 hi: hi.fold_with(folder),
1116 ty: ty.fold_with(folder),
1119 PatternKind::Slice {
1123 } => PatternKind::Slice {
1124 prefix: prefix.fold_with(folder),
1125 slice: slice.fold_with(folder),
1126 suffix: suffix.fold_with(folder)
1128 PatternKind::Array {
1132 } => PatternKind::Array {
1133 prefix: prefix.fold_with(folder),
1134 slice: slice.fold_with(folder),
1135 suffix: suffix.fold_with(folder)
1141 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1142 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1145 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1146 ) -> Option<Ordering> {
1147 trace!("compare_const_vals: {:?}, {:?}", a, b);
1149 let from_bool = |v: bool| {
1151 Some(Ordering::Equal)
1157 let fallback = || from_bool(a == b);
1159 // Use the fallback if any type differs
1160 if a.ty != b.ty || a.ty != ty.value {
1164 let tcx = tcx.global_tcx();
1165 let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1167 // FIXME: This should use assert_bits(ty) instead of use_bits
1168 // but triggers possibly bugs due to mismatching of arrays and slices
1169 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1170 use ::rustc_apfloat::Float;
1171 return match ty.value.sty {
1172 ty::Float(ast::FloatTy::F32) => {
1173 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1174 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1177 ty::Float(ast::FloatTy::F64) => {
1178 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1179 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1183 let layout = tcx.layout_of(ty).ok()?;
1184 assert!(layout.abi.is_signed());
1185 let a = sign_extend(a, layout.size);
1186 let b = sign_extend(b, layout.size);
1187 Some((a as i128).cmp(&(b as i128)))
1189 _ => Some(a.cmp(&b)),
1193 if let ty::Str = ty.value.sty {
1194 match (a.val, b.val) {
1196 ConstValue::ScalarPair(
1200 ConstValue::ScalarPair(
1204 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1205 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1206 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1208 let map = tcx.alloc_map.lock();
1209 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1210 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1211 if alloc_a.bytes.len() as u128 == len_a {
1212 return from_bool(alloc_a == alloc_b);