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, UserType};
18 use rustc::ty::{CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations};
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 {
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: CanonicalUserType<'tcx>,
64 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
67 impl<'tcx> PatternTypeProjection<'tcx> {
68 pub(crate) fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
70 base: user_annotation,
75 pub(crate) fn user_ty(
77 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
79 ) -> UserTypeProjection<'tcx> {
81 base: annotations.push(CanonicalUserTypeAnnotation{ span, user_ty: self.base }),
87 #[derive(Clone, Debug)]
88 pub enum PatternKind<'tcx> {
92 user_ty: PatternTypeProjection<'tcx>,
93 subpattern: Pattern<'tcx>,
94 /// Variance to use when relating the type `user_ty` to the **type of the value being
95 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
96 /// have a type that is some subtype of the ascribed type.
98 /// Note that this variance does not apply for any bindings within subpatterns. The type
99 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
101 /// The only place where this field is not `Covariant` is when matching constants, where
102 /// we currently use `Contravariant` -- this is because the constant type just needs to
103 /// be "comparable" to the type of the input value. So, for example:
106 /// match x { "foo" => .. }
109 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
110 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
111 /// of the old type-check for now. See #57280 for details.
112 variance: ty::Variance,
116 /// x, ref x, x @ P, etc
118 mutability: Mutability,
123 subpattern: Option<Pattern<'tcx>>,
126 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
128 adt_def: &'tcx AdtDef,
129 substs: &'tcx Substs<'tcx>,
130 variant_index: VariantIdx,
131 subpatterns: Vec<FieldPattern<'tcx>>,
134 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
136 subpatterns: Vec<FieldPattern<'tcx>>,
139 /// box P, &P, &mut P, etc
141 subpattern: Pattern<'tcx>,
145 value: ty::Const<'tcx>,
148 Range(PatternRange<'tcx>),
150 /// matches against a slice, checking the length and extracting elements.
151 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
152 /// e.g., `&[ref xs..]`.
154 prefix: Vec<Pattern<'tcx>>,
155 slice: Option<Pattern<'tcx>>,
156 suffix: Vec<Pattern<'tcx>>,
159 /// fixed match against an array, irrefutable
161 prefix: Vec<Pattern<'tcx>>,
162 slice: Option<Pattern<'tcx>>,
163 suffix: Vec<Pattern<'tcx>>,
167 #[derive(Clone, Copy, Debug, PartialEq)]
168 pub struct PatternRange<'tcx> {
169 pub lo: ty::Const<'tcx>,
170 pub hi: ty::Const<'tcx>,
175 impl<'tcx> fmt::Display for Pattern<'tcx> {
176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
178 PatternKind::Wild => write!(f, "_"),
179 PatternKind::AscribeUserType { ref subpattern, .. } =>
180 write!(f, "{}: _", subpattern),
181 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
182 let is_mut = match mode {
183 BindingMode::ByValue => mutability == Mutability::Mut,
184 BindingMode::ByRef(bk) => {
186 match bk { BorrowKind::Mut { .. } => true, _ => false }
192 write!(f, "{}", name)?;
193 if let Some(ref subpattern) = *subpattern {
194 write!(f, " @ {}", subpattern)?;
198 PatternKind::Variant { ref subpatterns, .. } |
199 PatternKind::Leaf { ref subpatterns } => {
200 let variant = match *self.kind {
201 PatternKind::Variant { adt_def, variant_index, .. } => {
202 Some(&adt_def.variants[variant_index])
204 _ => if let ty::Adt(adt, _) = self.ty.sty {
206 Some(&adt.variants[VariantIdx::new(0)])
215 let mut first = true;
216 let mut start_or_continue = || if first { first = false; "" } else { ", " };
218 if let Some(variant) = variant {
219 write!(f, "{}", variant.ident)?;
221 // Only for Adt we can have `S {...}`,
222 // which we handle separately here.
223 if variant.ctor_kind == CtorKind::Fictive {
227 for p in subpatterns {
228 if let PatternKind::Wild = *p.pattern.kind {
231 let name = variant.fields[p.field.index()].ident;
232 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
236 if printed < variant.fields.len() {
237 write!(f, "{}..", start_or_continue())?;
240 return write!(f, " }}");
244 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
245 if num_fields != 0 || variant.is_none() {
247 for i in 0..num_fields {
248 write!(f, "{}", start_or_continue())?;
250 // Common case: the field is where we expect it.
251 if let Some(p) = subpatterns.get(i) {
252 if p.field.index() == i {
253 write!(f, "{}", p.pattern)?;
258 // Otherwise, we have to go looking for it.
259 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
260 write!(f, "{}", p.pattern)?;
270 PatternKind::Deref { ref subpattern } => {
272 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
273 ty::Ref(_, _, mutbl) => {
275 if mutbl == hir::MutMutable {
279 _ => bug!("{} is a bad Deref pattern type", self.ty)
281 write!(f, "{}", subpattern)
283 PatternKind::Constant { value } => {
284 fmt_const_val(f, value)
286 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
287 fmt_const_val(f, lo)?;
289 RangeEnd::Included => write!(f, "..=")?,
290 RangeEnd::Excluded => write!(f, "..")?,
294 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
295 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
296 let mut first = true;
297 let mut start_or_continue = || if first { first = false; "" } else { ", " };
300 write!(f, "{}{}", start_or_continue(), p)?;
302 if let Some(ref slice) = *slice {
303 write!(f, "{}", start_or_continue())?;
305 PatternKind::Wild => {}
306 _ => write!(f, "{}", slice)?
311 write!(f, "{}{}", start_or_continue(), p)?;
319 pub struct PatternContext<'a, 'tcx: 'a> {
320 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
321 pub param_env: ty::ParamEnv<'tcx>,
322 pub tables: &'a ty::TypeckTables<'tcx>,
323 pub substs: &'tcx Substs<'tcx>,
324 pub errors: Vec<PatternError>,
327 impl<'a, 'tcx> Pattern<'tcx> {
328 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
329 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
330 tables: &'a ty::TypeckTables<'tcx>,
331 pat: &'tcx hir::Pat) -> Self {
332 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
333 let result = pcx.lower_pattern(pat);
334 if !pcx.errors.is_empty() {
335 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
336 tcx.sess.delay_span_bug(pat.span, &msg);
338 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
343 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
344 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
345 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
346 tables: &'a ty::TypeckTables<'tcx>) -> Self {
349 param_env: param_env_and_substs.param_env,
351 substs: param_env_and_substs.value,
356 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
357 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
358 // pattern has the type that results *after* dereferencing. For example, in this code:
361 // match &&Some(0i32) {
362 // Some(n) => { ... },
367 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
368 // determined in rustc_typeck::check::match). The adjustments would be
370 // `vec![&&Option<i32>, &Option<i32>]`.
372 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
373 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
374 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
375 // gets the least-dereferenced type).
376 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
383 .fold(unadjusted_pat, |pat, ref_ty| {
384 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
388 kind: Box::new(PatternKind::Deref { subpattern: pat }),
394 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
395 let mut ty = self.tables.node_id_to_type(pat.hir_id);
397 let kind = match pat.node {
398 PatKind::Wild => PatternKind::Wild,
400 PatKind::Lit(ref value) => self.lower_lit(value),
402 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
403 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
404 (PatternKind::Constant { value: lo },
405 PatternKind::Constant { value: hi }) => {
406 use std::cmp::Ordering;
407 let cmp = compare_const_vals(
411 self.param_env.and(ty),
414 (RangeEnd::Excluded, Some(Ordering::Less)) =>
415 PatternKind::Range(PatternRange { lo, hi, ty, end }),
416 (RangeEnd::Excluded, _) => {
421 "lower range bound must be less than upper",
425 (RangeEnd::Included, Some(Ordering::Equal)) => {
426 PatternKind::Constant { value: lo }
428 (RangeEnd::Included, Some(Ordering::Less)) => {
429 PatternKind::Range(PatternRange { lo, hi, ty, end })
431 (RangeEnd::Included, _) => {
432 let mut err = struct_span_err!(
436 "lower range bound must be less than or equal to upper"
440 "lower bound larger than upper bound",
442 if self.tcx.sess.teach(&err.get_code().unwrap()) {
443 err.note("When matching against a range, the compiler \
444 verifies that the range is non-empty. Range \
445 patterns include both end-points, so this is \
446 equivalent to requiring the start of the range \
447 to be less than or equal to the end of the range.");
454 _ => PatternKind::Wild
458 PatKind::Path(ref qpath) => {
459 return self.lower_path(qpath, pat.hir_id, pat.span);
462 PatKind::Ref(ref subpattern, _) |
463 PatKind::Box(ref subpattern) => {
464 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
467 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
471 subpattern: Pattern {
474 kind: Box::new(self.slice_or_array_pattern(
475 pat.span, ty, prefix, slice, suffix))
480 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
481 ty::Error => { // Avoid ICE
482 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
487 "unexpanded type for vector pattern: {:?}",
492 PatKind::Tuple(ref subpatterns, ddpos) => {
494 ty::Tuple(ref tys) => {
497 .enumerate_and_adjust(tys.len(), ddpos)
498 .map(|(i, subpattern)| FieldPattern {
499 field: Field::new(i),
500 pattern: self.lower_pattern(subpattern)
504 PatternKind::Leaf { subpatterns }
506 ty::Error => { // Avoid ICE (#50577)
507 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
509 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
513 PatKind::Binding(_, id, ident, ref sub) => {
514 let var_ty = self.tables.node_id_to_type(pat.hir_id);
515 if let ty::Error = var_ty.sty {
517 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
519 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
520 .expect("missing binding mode");
521 let (mutability, mode) = match bm {
522 ty::BindByValue(hir::MutMutable) =>
523 (Mutability::Mut, BindingMode::ByValue),
524 ty::BindByValue(hir::MutImmutable) =>
525 (Mutability::Not, BindingMode::ByValue),
526 ty::BindByReference(hir::MutMutable) =>
527 (Mutability::Not, BindingMode::ByRef(
528 BorrowKind::Mut { allow_two_phase_borrow: false })),
529 ty::BindByReference(hir::MutImmutable) =>
530 (Mutability::Not, BindingMode::ByRef(
531 BorrowKind::Shared)),
534 // A ref x pattern is the same node used for x, and as such it has
535 // x's type, which is &T, where we want T (the type being matched).
536 if let ty::BindByReference(_) = bm {
537 if let ty::Ref(_, rty, _) = ty.sty {
540 bug!("`ref {}` has wrong type {}", ident, ty);
544 PatternKind::Binding {
550 subpattern: self.lower_opt_pattern(sub),
554 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
555 let def = self.tables.qpath_def(qpath, pat.hir_id);
556 let adt_def = match ty.sty {
557 ty::Adt(adt_def, _) => adt_def,
558 ty::Error => { // Avoid ICE (#50585)
559 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
561 _ => span_bug!(pat.span,
562 "tuple struct pattern not applied to an ADT {:?}",
565 let variant_def = adt_def.variant_of_def(def);
569 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
570 .map(|(i, field)| FieldPattern {
571 field: Field::new(i),
572 pattern: self.lower_pattern(field),
576 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
579 PatKind::Struct(ref qpath, ref fields, _) => {
580 let def = self.tables.qpath_def(qpath, pat.hir_id);
585 field: Field::new(self.tcx.field_index(field.node.id,
587 pattern: self.lower_pattern(&field.node.pat),
592 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
599 kind: Box::new(kind),
603 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
604 pats.iter().map(|p| self.lower_pattern(p)).collect()
607 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
609 pat.as_ref().map(|p| self.lower_pattern(p))
612 fn flatten_nested_slice_patterns(
614 prefix: Vec<Pattern<'tcx>>,
615 slice: Option<Pattern<'tcx>>,
616 suffix: Vec<Pattern<'tcx>>)
617 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
619 let orig_slice = match slice {
620 Some(orig_slice) => orig_slice,
621 None => return (prefix, slice, suffix)
623 let orig_prefix = prefix;
624 let orig_suffix = suffix;
626 // dance because of intentional borrow-checker stupidity.
627 let kind = *orig_slice.kind;
629 PatternKind::Slice { prefix, slice, mut suffix } |
630 PatternKind::Array { prefix, slice, mut suffix } => {
631 let mut orig_prefix = orig_prefix;
633 orig_prefix.extend(prefix);
634 suffix.extend(orig_suffix);
636 (orig_prefix, slice, suffix)
639 (orig_prefix, Some(Pattern {
640 kind: box kind, ..orig_slice
646 fn slice_or_array_pattern(
650 prefix: &'tcx [P<hir::Pat>],
651 slice: &'tcx Option<P<hir::Pat>>,
652 suffix: &'tcx [P<hir::Pat>])
655 let prefix = self.lower_patterns(prefix);
656 let slice = self.lower_opt_pattern(slice);
657 let suffix = self.lower_patterns(suffix);
658 let (prefix, slice, suffix) =
659 self.flatten_nested_slice_patterns(prefix, slice, suffix);
663 // matching a slice or fixed-length array
664 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
667 ty::Array(_, len) => {
668 // fixed-length array
669 let len = len.unwrap_usize(self.tcx);
670 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
671 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
675 span_bug!(span, "bad slice pattern type {:?}", ty);
680 fn lower_variant_or_leaf(
686 subpatterns: Vec<FieldPattern<'tcx>>,
687 ) -> PatternKind<'tcx> {
688 let mut kind = match def {
689 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
690 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
691 let adt_def = self.tcx.adt_def(enum_id);
692 if adt_def.is_enum() {
693 let substs = match ty.sty {
695 ty::FnDef(_, substs) => substs,
696 ty::Error => { // Avoid ICE (#50585)
697 return PatternKind::Wild;
699 _ => bug!("inappropriate type for def: {:?}", ty.sty),
701 PatternKind::Variant {
704 variant_index: adt_def.variant_index_with_id(variant_id),
708 PatternKind::Leaf { subpatterns }
712 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
713 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
714 PatternKind::Leaf { subpatterns }
718 self.errors.push(PatternError::NonConstPath(span));
723 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
724 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
725 kind = PatternKind::AscribeUserType {
726 subpattern: Pattern {
729 kind: Box::new(kind),
731 user_ty: PatternTypeProjection::from_user_type(user_ty),
733 variance: ty::Variance::Covariant,
740 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
741 /// it to `const_to_pat`. Any other path (like enum variants without fields)
742 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
743 fn lower_path(&mut self,
748 let ty = self.tables.node_id_to_type(id);
749 let def = self.tables.qpath_def(qpath, id);
750 let is_associated_const = match def {
751 Def::AssociatedConst(_) => true,
754 let kind = match def {
755 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
756 let substs = self.tables.node_substs(id);
757 match ty::Instance::resolve(
768 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
770 let pattern = self.const_to_pat(instance, value, id, span);
771 if !is_associated_const {
775 let user_provided_types = self.tables().user_provided_types();
776 return if let Some(u_ty) = user_provided_types.get(id) {
777 let user_ty = PatternTypeProjection::from_user_type(*u_ty);
781 PatternKind::AscribeUserType {
783 /// Note that use `Contravariant` here. See the
784 /// `variance` field documentation for details.
785 variance: ty::Variance::Contravariant,
797 self.tcx.sess.span_err(
799 "could not evaluate constant pattern",
806 self.errors.push(if is_associated_const {
807 PatternError::AssociatedConstInPattern(span)
809 PatternError::StaticInPattern(span)
815 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
821 kind: Box::new(kind),
825 /// Converts literals, paths and negation of literals to patterns.
826 /// The special case for negation exists to allow things like -128i8
827 /// which would overflow if we tried to evaluate 128i8 and then negate
829 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
831 hir::ExprKind::Lit(ref lit) => {
832 let ty = self.tables.expr_ty(expr);
833 match lit_to_const(&lit.node, self.tcx, ty, false) {
835 let instance = ty::Instance::new(
836 self.tables.local_id_root.expect("literal outside any scope"),
839 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
841 Err(LitToConstError::UnparseableFloat) => {
842 self.errors.push(PatternError::FloatBug);
845 Err(LitToConstError::Reported) => PatternKind::Wild,
848 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
849 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
850 let ty = self.tables.expr_ty(expr);
851 let lit = match expr.node {
852 hir::ExprKind::Lit(ref lit) => lit,
853 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
855 match lit_to_const(&lit.node, self.tcx, ty, true) {
857 let instance = ty::Instance::new(
858 self.tables.local_id_root.expect("literal outside any scope"),
861 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
863 Err(LitToConstError::UnparseableFloat) => {
864 self.errors.push(PatternError::FloatBug);
867 Err(LitToConstError::Reported) => PatternKind::Wild,
870 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
874 /// Converts an evaluated constant to a pattern (if possible).
875 /// This means aggregate values (like structs and enums) are converted
876 /// to a pattern that matches the value (as if you'd compare via eq).
879 instance: ty::Instance<'tcx>,
884 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
885 let adt_subpattern = |i, variant_opt| {
886 let field = Field::new(i);
887 let val = const_field(
888 self.tcx, self.param_env, instance,
889 variant_opt, field, cv,
890 ).expect("field access failed");
891 self.const_to_pat(instance, val, id, span)
893 let adt_subpatterns = |n, variant_opt| {
895 let field = Field::new(i);
898 pattern: adt_subpattern(i, variant_opt),
900 }).collect::<Vec<_>>()
902 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
903 let kind = match cv.ty.sty {
905 let id = self.tcx.hir().hir_to_node_id(id);
907 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
910 "floating-point types cannot be used in patterns",
912 PatternKind::Constant {
916 ty::Adt(adt_def, _) if adt_def.is_union() => {
917 // Matching on union fields is unsafe, we can't hide it in constants
918 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
921 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
922 let msg = format!("to use a constant of type `{}` in a pattern, \
923 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
924 self.tcx.item_path_str(adt_def.did),
925 self.tcx.item_path_str(adt_def.did));
926 self.tcx.sess.span_err(span, &msg);
929 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
930 let variant_index = const_variant_index(
931 self.tcx, self.param_env, instance, cv
932 ).expect("const_variant_index failed");
933 let subpatterns = adt_subpatterns(
934 adt_def.variants[variant_index].fields.len(),
937 PatternKind::Variant {
944 ty::Adt(adt_def, _) => {
945 let struct_var = adt_def.non_enum_variant();
947 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
950 ty::Tuple(fields) => {
952 subpatterns: adt_subpatterns(fields.len(), None),
957 prefix: (0..n.unwrap_usize(self.tcx))
958 .map(|i| adt_subpattern(i as usize, None))
965 PatternKind::Constant {
974 kind: Box::new(kind),
979 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
980 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
984 fn tables(&self) -> &ty::TypeckTables<'tcx> {
990 pub trait PatternFoldable<'tcx> : Sized {
991 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
992 self.super_fold_with(folder)
995 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
998 pub trait PatternFolder<'tcx> : Sized {
999 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1000 pattern.super_fold_with(self)
1003 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1004 kind.super_fold_with(self)
1009 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1010 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1011 let content: T = (**self).fold_with(folder);
1016 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1017 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1018 self.iter().map(|t| t.fold_with(folder)).collect()
1022 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1023 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1024 self.as_ref().map(|t| t.fold_with(folder))
1028 macro_rules! CloneImpls {
1029 (<$lt_tcx:tt> $($ty:ty),+) => {
1031 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1032 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1041 Span, Field, Mutability, ast::Name, ast::NodeId, usize, ty::Const<'tcx>,
1042 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1043 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserType<'tcx>,
1044 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1047 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1048 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1050 field: self.field.fold_with(folder),
1051 pattern: self.pattern.fold_with(folder)
1056 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1057 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1058 folder.fold_pattern(self)
1061 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1063 ty: self.ty.fold_with(folder),
1064 span: self.span.fold_with(folder),
1065 kind: self.kind.fold_with(folder)
1070 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1071 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1072 folder.fold_pattern_kind(self)
1075 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1077 PatternKind::Wild => PatternKind::Wild,
1078 PatternKind::AscribeUserType {
1083 } => PatternKind::AscribeUserType {
1084 subpattern: subpattern.fold_with(folder),
1085 user_ty: user_ty.fold_with(folder),
1089 PatternKind::Binding {
1096 } => PatternKind::Binding {
1097 mutability: mutability.fold_with(folder),
1098 name: name.fold_with(folder),
1099 mode: mode.fold_with(folder),
1100 var: var.fold_with(folder),
1101 ty: ty.fold_with(folder),
1102 subpattern: subpattern.fold_with(folder),
1104 PatternKind::Variant {
1109 } => PatternKind::Variant {
1110 adt_def: adt_def.fold_with(folder),
1111 substs: substs.fold_with(folder),
1113 subpatterns: subpatterns.fold_with(folder)
1117 } => PatternKind::Leaf {
1118 subpatterns: subpatterns.fold_with(folder),
1120 PatternKind::Deref {
1122 } => PatternKind::Deref {
1123 subpattern: subpattern.fold_with(folder),
1125 PatternKind::Constant {
1127 } => PatternKind::Constant {
1128 value: value.fold_with(folder)
1130 PatternKind::Range(PatternRange {
1135 }) => PatternKind::Range(PatternRange {
1136 lo: lo.fold_with(folder),
1137 hi: hi.fold_with(folder),
1138 ty: ty.fold_with(folder),
1141 PatternKind::Slice {
1145 } => PatternKind::Slice {
1146 prefix: prefix.fold_with(folder),
1147 slice: slice.fold_with(folder),
1148 suffix: suffix.fold_with(folder)
1150 PatternKind::Array {
1154 } => PatternKind::Array {
1155 prefix: prefix.fold_with(folder),
1156 slice: slice.fold_with(folder),
1157 suffix: suffix.fold_with(folder)
1163 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1164 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1167 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1168 ) -> Option<Ordering> {
1169 trace!("compare_const_vals: {:?}, {:?}", a, b);
1171 let from_bool = |v: bool| {
1173 Some(Ordering::Equal)
1179 let fallback = || from_bool(a == b);
1181 // Use the fallback if any type differs
1182 if a.ty != b.ty || a.ty != ty.value {
1186 let tcx = tcx.global_tcx();
1187 let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1189 // FIXME: This should use assert_bits(ty) instead of use_bits
1190 // but triggers possibly bugs due to mismatching of arrays and slices
1191 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1192 use ::rustc_apfloat::Float;
1193 return match ty.value.sty {
1194 ty::Float(ast::FloatTy::F32) => {
1195 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1196 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1199 ty::Float(ast::FloatTy::F64) => {
1200 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1201 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1205 let layout = tcx.layout_of(ty).ok()?;
1206 assert!(layout.abi.is_signed());
1207 let a = sign_extend(a, layout.size);
1208 let b = sign_extend(b, layout.size);
1209 Some((a as i128).cmp(&(b as i128)))
1211 _ => Some(a.cmp(&b)),
1215 if let ty::Str = ty.value.sty {
1216 match (a.val, b.val) {
1218 ConstValue::ScalarPair(
1222 ConstValue::ScalarPair(
1226 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1227 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1228 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1230 let map = tcx.alloc_map.lock();
1231 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1232 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1233 if alloc_a.bytes.len() as u128 == len_a {
1234 return from_bool(alloc_a == alloc_b);