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::{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 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<'tcx> {
80 base: annotations.push(CanonicalUserTypeAnnotation {
82 user_ty: self.user_ty,
90 #[derive(Clone, Debug)]
91 pub enum PatternKind<'tcx> {
95 user_ty: PatternTypeProjection<'tcx>,
96 subpattern: Pattern<'tcx>,
97 /// Variance to use when relating the type `user_ty` to the **type of the value being
98 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
99 /// have a type that is some subtype of the ascribed type.
101 /// Note that this variance does not apply for any bindings within subpatterns. The type
102 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
104 /// The only place where this field is not `Covariant` is when matching constants, where
105 /// we currently use `Contravariant` -- this is because the constant type just needs to
106 /// be "comparable" to the type of the input value. So, for example:
109 /// match x { "foo" => .. }
112 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
113 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
114 /// of the old type-check for now. See #57280 for details.
115 variance: ty::Variance,
119 /// x, ref x, x @ P, etc
121 mutability: Mutability,
126 subpattern: Option<Pattern<'tcx>>,
129 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
131 adt_def: &'tcx AdtDef,
132 substs: &'tcx Substs<'tcx>,
133 variant_index: VariantIdx,
134 subpatterns: Vec<FieldPattern<'tcx>>,
137 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
139 subpatterns: Vec<FieldPattern<'tcx>>,
142 /// box P, &P, &mut P, etc
144 subpattern: Pattern<'tcx>,
148 value: ty::Const<'tcx>,
151 Range(PatternRange<'tcx>),
153 /// matches against a slice, checking the length and extracting elements.
154 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
155 /// e.g., `&[ref xs..]`.
157 prefix: Vec<Pattern<'tcx>>,
158 slice: Option<Pattern<'tcx>>,
159 suffix: Vec<Pattern<'tcx>>,
162 /// fixed match against an array, irrefutable
164 prefix: Vec<Pattern<'tcx>>,
165 slice: Option<Pattern<'tcx>>,
166 suffix: Vec<Pattern<'tcx>>,
170 #[derive(Clone, Copy, Debug, PartialEq)]
171 pub struct PatternRange<'tcx> {
172 pub lo: ty::Const<'tcx>,
173 pub hi: ty::Const<'tcx>,
178 impl<'tcx> fmt::Display for Pattern<'tcx> {
179 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181 PatternKind::Wild => write!(f, "_"),
182 PatternKind::AscribeUserType { ref subpattern, .. } =>
183 write!(f, "{}: _", subpattern),
184 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
185 let is_mut = match mode {
186 BindingMode::ByValue => mutability == Mutability::Mut,
187 BindingMode::ByRef(bk) => {
189 match bk { BorrowKind::Mut { .. } => true, _ => false }
195 write!(f, "{}", name)?;
196 if let Some(ref subpattern) = *subpattern {
197 write!(f, " @ {}", subpattern)?;
201 PatternKind::Variant { ref subpatterns, .. } |
202 PatternKind::Leaf { ref subpatterns } => {
203 let variant = match *self.kind {
204 PatternKind::Variant { adt_def, variant_index, .. } => {
205 Some(&adt_def.variants[variant_index])
207 _ => if let ty::Adt(adt, _) = self.ty.sty {
209 Some(&adt.variants[VariantIdx::new(0)])
218 let mut first = true;
219 let mut start_or_continue = || if first { first = false; "" } else { ", " };
221 if let Some(variant) = variant {
222 write!(f, "{}", variant.ident)?;
224 // Only for Adt we can have `S {...}`,
225 // which we handle separately here.
226 if variant.ctor_kind == CtorKind::Fictive {
230 for p in subpatterns {
231 if let PatternKind::Wild = *p.pattern.kind {
234 let name = variant.fields[p.field.index()].ident;
235 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
239 if printed < variant.fields.len() {
240 write!(f, "{}..", start_or_continue())?;
243 return write!(f, " }}");
247 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
248 if num_fields != 0 || variant.is_none() {
250 for i in 0..num_fields {
251 write!(f, "{}", start_or_continue())?;
253 // Common case: the field is where we expect it.
254 if let Some(p) = subpatterns.get(i) {
255 if p.field.index() == i {
256 write!(f, "{}", p.pattern)?;
261 // Otherwise, we have to go looking for it.
262 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
263 write!(f, "{}", p.pattern)?;
273 PatternKind::Deref { ref subpattern } => {
275 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
276 ty::Ref(_, _, mutbl) => {
278 if mutbl == hir::MutMutable {
282 _ => bug!("{} is a bad Deref pattern type", self.ty)
284 write!(f, "{}", subpattern)
286 PatternKind::Constant { value } => {
287 fmt_const_val(f, value)
289 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
290 fmt_const_val(f, lo)?;
292 RangeEnd::Included => write!(f, "..=")?,
293 RangeEnd::Excluded => write!(f, "..")?,
297 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
298 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
299 let mut first = true;
300 let mut start_or_continue = || if first { first = false; "" } else { ", " };
303 write!(f, "{}{}", start_or_continue(), p)?;
305 if let Some(ref slice) = *slice {
306 write!(f, "{}", start_or_continue())?;
308 PatternKind::Wild => {}
309 _ => write!(f, "{}", slice)?
314 write!(f, "{}{}", start_or_continue(), p)?;
322 pub struct PatternContext<'a, 'tcx: 'a> {
323 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
324 pub param_env: ty::ParamEnv<'tcx>,
325 pub tables: &'a ty::TypeckTables<'tcx>,
326 pub substs: &'tcx Substs<'tcx>,
327 pub errors: Vec<PatternError>,
330 impl<'a, 'tcx> Pattern<'tcx> {
331 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
332 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
333 tables: &'a ty::TypeckTables<'tcx>,
334 pat: &'tcx hir::Pat) -> Self {
335 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
336 let result = pcx.lower_pattern(pat);
337 if !pcx.errors.is_empty() {
338 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
339 tcx.sess.delay_span_bug(pat.span, &msg);
341 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
346 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
347 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
348 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
349 tables: &'a ty::TypeckTables<'tcx>) -> Self {
352 param_env: param_env_and_substs.param_env,
354 substs: param_env_and_substs.value,
359 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
360 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
361 // pattern has the type that results *after* dereferencing. For example, in this code:
364 // match &&Some(0i32) {
365 // Some(n) => { ... },
370 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
371 // determined in rustc_typeck::check::match). The adjustments would be
373 // `vec![&&Option<i32>, &Option<i32>]`.
375 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
376 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
377 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
378 // gets the least-dereferenced type).
379 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
386 .fold(unadjusted_pat, |pat, ref_ty| {
387 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
391 kind: Box::new(PatternKind::Deref { subpattern: pat }),
397 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
398 let mut ty = self.tables.node_id_to_type(pat.hir_id);
400 let kind = match pat.node {
401 PatKind::Wild => PatternKind::Wild,
403 PatKind::Lit(ref value) => self.lower_lit(value),
405 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
406 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
407 (PatternKind::Constant { value: lo },
408 PatternKind::Constant { value: hi }) => {
409 use std::cmp::Ordering;
410 let cmp = compare_const_vals(
414 self.param_env.and(ty),
417 (RangeEnd::Excluded, Some(Ordering::Less)) =>
418 PatternKind::Range(PatternRange { lo, hi, ty, end }),
419 (RangeEnd::Excluded, _) => {
424 "lower range bound must be less than upper",
428 (RangeEnd::Included, Some(Ordering::Equal)) => {
429 PatternKind::Constant { value: lo }
431 (RangeEnd::Included, Some(Ordering::Less)) => {
432 PatternKind::Range(PatternRange { lo, hi, ty, end })
434 (RangeEnd::Included, _) => {
435 let mut err = struct_span_err!(
439 "lower range bound must be less than or equal to upper"
443 "lower bound larger than upper bound",
445 if self.tcx.sess.teach(&err.get_code().unwrap()) {
446 err.note("When matching against a range, the compiler \
447 verifies that the range is non-empty. Range \
448 patterns include both end-points, so this is \
449 equivalent to requiring the start of the range \
450 to be less than or equal to the end of the range.");
457 _ => PatternKind::Wild
461 PatKind::Path(ref qpath) => {
462 return self.lower_path(qpath, pat.hir_id, pat.span);
465 PatKind::Ref(ref subpattern, _) |
466 PatKind::Box(ref subpattern) => {
467 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
470 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
474 subpattern: Pattern {
477 kind: Box::new(self.slice_or_array_pattern(
478 pat.span, ty, prefix, slice, suffix))
483 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
484 ty::Error => { // Avoid ICE
485 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
490 "unexpanded type for vector pattern: {:?}",
495 PatKind::Tuple(ref subpatterns, ddpos) => {
497 ty::Tuple(ref tys) => {
500 .enumerate_and_adjust(tys.len(), ddpos)
501 .map(|(i, subpattern)| FieldPattern {
502 field: Field::new(i),
503 pattern: self.lower_pattern(subpattern)
507 PatternKind::Leaf { subpatterns }
509 ty::Error => { // Avoid ICE (#50577)
510 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
512 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
516 PatKind::Binding(_, id, ident, ref sub) => {
517 let var_ty = self.tables.node_id_to_type(pat.hir_id);
518 if let ty::Error = var_ty.sty {
520 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
522 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
523 .expect("missing binding mode");
524 let (mutability, mode) = match bm {
525 ty::BindByValue(hir::MutMutable) =>
526 (Mutability::Mut, BindingMode::ByValue),
527 ty::BindByValue(hir::MutImmutable) =>
528 (Mutability::Not, BindingMode::ByValue),
529 ty::BindByReference(hir::MutMutable) =>
530 (Mutability::Not, BindingMode::ByRef(
531 BorrowKind::Mut { allow_two_phase_borrow: false })),
532 ty::BindByReference(hir::MutImmutable) =>
533 (Mutability::Not, BindingMode::ByRef(
534 BorrowKind::Shared)),
537 // A ref x pattern is the same node used for x, and as such it has
538 // x's type, which is &T, where we want T (the type being matched).
539 if let ty::BindByReference(_) = bm {
540 if let ty::Ref(_, rty, _) = ty.sty {
543 bug!("`ref {}` has wrong type {}", ident, ty);
547 PatternKind::Binding {
553 subpattern: self.lower_opt_pattern(sub),
557 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
558 let def = self.tables.qpath_def(qpath, pat.hir_id);
559 let adt_def = match ty.sty {
560 ty::Adt(adt_def, _) => adt_def,
561 ty::Error => { // Avoid ICE (#50585)
562 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
564 _ => span_bug!(pat.span,
565 "tuple struct pattern not applied to an ADT {:?}",
568 let variant_def = adt_def.variant_of_def(def);
572 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
573 .map(|(i, field)| FieldPattern {
574 field: Field::new(i),
575 pattern: self.lower_pattern(field),
579 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
582 PatKind::Struct(ref qpath, ref fields, _) => {
583 let def = self.tables.qpath_def(qpath, pat.hir_id);
588 field: Field::new(self.tcx.field_index(field.node.id,
590 pattern: self.lower_pattern(&field.node.pat),
595 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
602 kind: Box::new(kind),
606 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
607 pats.iter().map(|p| self.lower_pattern(p)).collect()
610 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
612 pat.as_ref().map(|p| self.lower_pattern(p))
615 fn flatten_nested_slice_patterns(
617 prefix: Vec<Pattern<'tcx>>,
618 slice: Option<Pattern<'tcx>>,
619 suffix: Vec<Pattern<'tcx>>)
620 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
622 let orig_slice = match slice {
623 Some(orig_slice) => orig_slice,
624 None => return (prefix, slice, suffix)
626 let orig_prefix = prefix;
627 let orig_suffix = suffix;
629 // dance because of intentional borrow-checker stupidity.
630 let kind = *orig_slice.kind;
632 PatternKind::Slice { prefix, slice, mut suffix } |
633 PatternKind::Array { prefix, slice, mut suffix } => {
634 let mut orig_prefix = orig_prefix;
636 orig_prefix.extend(prefix);
637 suffix.extend(orig_suffix);
639 (orig_prefix, slice, suffix)
642 (orig_prefix, Some(Pattern {
643 kind: box kind, ..orig_slice
649 fn slice_or_array_pattern(
653 prefix: &'tcx [P<hir::Pat>],
654 slice: &'tcx Option<P<hir::Pat>>,
655 suffix: &'tcx [P<hir::Pat>])
658 let prefix = self.lower_patterns(prefix);
659 let slice = self.lower_opt_pattern(slice);
660 let suffix = self.lower_patterns(suffix);
661 let (prefix, slice, suffix) =
662 self.flatten_nested_slice_patterns(prefix, slice, suffix);
666 // matching a slice or fixed-length array
667 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
670 ty::Array(_, len) => {
671 // fixed-length array
672 let len = len.unwrap_usize(self.tcx);
673 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
674 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
678 span_bug!(span, "bad slice pattern type {:?}", ty);
683 fn lower_variant_or_leaf(
689 subpatterns: Vec<FieldPattern<'tcx>>,
690 ) -> PatternKind<'tcx> {
691 let mut kind = match def {
692 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
693 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
694 let adt_def = self.tcx.adt_def(enum_id);
695 if adt_def.is_enum() {
696 let substs = match ty.sty {
698 ty::FnDef(_, substs) => substs,
699 ty::Error => { // Avoid ICE (#50585)
700 return PatternKind::Wild;
702 _ => bug!("inappropriate type for def: {:?}", ty.sty),
704 PatternKind::Variant {
707 variant_index: adt_def.variant_index_with_id(variant_id),
711 PatternKind::Leaf { subpatterns }
715 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
716 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
717 PatternKind::Leaf { subpatterns }
721 self.errors.push(PatternError::NonConstPath(span));
726 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
727 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
728 kind = PatternKind::AscribeUserType {
729 subpattern: Pattern {
732 kind: Box::new(kind),
734 user_ty: PatternTypeProjection::from_user_type(user_ty),
736 variance: ty::Variance::Covariant,
743 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
744 /// it to `const_to_pat`. Any other path (like enum variants without fields)
745 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
746 fn lower_path(&mut self,
751 let ty = self.tables.node_id_to_type(id);
752 let def = self.tables.qpath_def(qpath, id);
753 let is_associated_const = match def {
754 Def::AssociatedConst(_) => true,
757 let kind = match def {
758 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
759 let substs = self.tables.node_substs(id);
760 match ty::Instance::resolve(
771 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
773 let pattern = self.const_to_pat(instance, value, id, span);
774 if !is_associated_const {
778 let user_provided_types = self.tables().user_provided_types();
779 return if let Some(u_ty) = user_provided_types.get(id) {
780 let user_ty = PatternTypeProjection::from_user_type(*u_ty);
784 PatternKind::AscribeUserType {
786 /// Note that use `Contravariant` here. See the
787 /// `variance` field documentation for details.
788 variance: ty::Variance::Contravariant,
800 self.tcx.sess.span_err(
802 "could not evaluate constant pattern",
809 self.errors.push(if is_associated_const {
810 PatternError::AssociatedConstInPattern(span)
812 PatternError::StaticInPattern(span)
818 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
824 kind: Box::new(kind),
828 /// Converts literals, paths and negation of literals to patterns.
829 /// The special case for negation exists to allow things like -128i8
830 /// which would overflow if we tried to evaluate 128i8 and then negate
832 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
834 hir::ExprKind::Lit(ref lit) => {
835 let ty = self.tables.expr_ty(expr);
836 match lit_to_const(&lit.node, self.tcx, ty, false) {
838 let instance = ty::Instance::new(
839 self.tables.local_id_root.expect("literal outside any scope"),
842 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
844 Err(LitToConstError::UnparseableFloat) => {
845 self.errors.push(PatternError::FloatBug);
848 Err(LitToConstError::Reported) => PatternKind::Wild,
851 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
852 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
853 let ty = self.tables.expr_ty(expr);
854 let lit = match expr.node {
855 hir::ExprKind::Lit(ref lit) => lit,
856 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
858 match lit_to_const(&lit.node, self.tcx, ty, true) {
860 let instance = ty::Instance::new(
861 self.tables.local_id_root.expect("literal outside any scope"),
864 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
866 Err(LitToConstError::UnparseableFloat) => {
867 self.errors.push(PatternError::FloatBug);
870 Err(LitToConstError::Reported) => PatternKind::Wild,
873 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
877 /// Converts an evaluated constant to a pattern (if possible).
878 /// This means aggregate values (like structs and enums) are converted
879 /// to a pattern that matches the value (as if you'd compare via eq).
882 instance: ty::Instance<'tcx>,
887 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
888 let adt_subpattern = |i, variant_opt| {
889 let field = Field::new(i);
890 let val = const_field(
891 self.tcx, self.param_env, instance,
892 variant_opt, field, cv,
893 ).expect("field access failed");
894 self.const_to_pat(instance, val, id, span)
896 let adt_subpatterns = |n, variant_opt| {
898 let field = Field::new(i);
901 pattern: adt_subpattern(i, variant_opt),
903 }).collect::<Vec<_>>()
905 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
906 let kind = match cv.ty.sty {
908 let id = self.tcx.hir().hir_to_node_id(id);
910 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
913 "floating-point types cannot be used in patterns",
915 PatternKind::Constant {
919 ty::Adt(adt_def, _) if adt_def.is_union() => {
920 // Matching on union fields is unsafe, we can't hide it in constants
921 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
924 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
925 let msg = format!("to use a constant of type `{}` in a pattern, \
926 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
927 self.tcx.item_path_str(adt_def.did),
928 self.tcx.item_path_str(adt_def.did));
929 self.tcx.sess.span_err(span, &msg);
932 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
933 let variant_index = const_variant_index(
934 self.tcx, self.param_env, instance, cv
935 ).expect("const_variant_index failed");
936 let subpatterns = adt_subpatterns(
937 adt_def.variants[variant_index].fields.len(),
940 PatternKind::Variant {
947 ty::Adt(adt_def, _) => {
948 let struct_var = adt_def.non_enum_variant();
950 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
953 ty::Tuple(fields) => {
955 subpatterns: adt_subpatterns(fields.len(), None),
960 prefix: (0..n.unwrap_usize(self.tcx))
961 .map(|i| adt_subpattern(i as usize, None))
968 PatternKind::Constant {
977 kind: Box::new(kind),
982 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
983 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
987 fn tables(&self) -> &ty::TypeckTables<'tcx> {
993 pub trait PatternFoldable<'tcx> : Sized {
994 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
995 self.super_fold_with(folder)
998 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1001 pub trait PatternFolder<'tcx> : Sized {
1002 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1003 pattern.super_fold_with(self)
1006 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1007 kind.super_fold_with(self)
1012 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1013 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1014 let content: T = (**self).fold_with(folder);
1019 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1020 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1021 self.iter().map(|t| t.fold_with(folder)).collect()
1025 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1026 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1027 self.as_ref().map(|t| t.fold_with(folder))
1031 macro_rules! CloneImpls {
1032 (<$lt_tcx:tt> $($ty:ty),+) => {
1034 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1035 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1044 Span, Field, Mutability, ast::Name, ast::NodeId, usize, ty::Const<'tcx>,
1045 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1046 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserType<'tcx>,
1047 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1050 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1051 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1053 field: self.field.fold_with(folder),
1054 pattern: self.pattern.fold_with(folder)
1059 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1060 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1061 folder.fold_pattern(self)
1064 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1066 ty: self.ty.fold_with(folder),
1067 span: self.span.fold_with(folder),
1068 kind: self.kind.fold_with(folder)
1073 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1074 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1075 folder.fold_pattern_kind(self)
1078 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1080 PatternKind::Wild => PatternKind::Wild,
1081 PatternKind::AscribeUserType {
1086 } => PatternKind::AscribeUserType {
1087 subpattern: subpattern.fold_with(folder),
1088 user_ty: user_ty.fold_with(folder),
1092 PatternKind::Binding {
1099 } => PatternKind::Binding {
1100 mutability: mutability.fold_with(folder),
1101 name: name.fold_with(folder),
1102 mode: mode.fold_with(folder),
1103 var: var.fold_with(folder),
1104 ty: ty.fold_with(folder),
1105 subpattern: subpattern.fold_with(folder),
1107 PatternKind::Variant {
1112 } => PatternKind::Variant {
1113 adt_def: adt_def.fold_with(folder),
1114 substs: substs.fold_with(folder),
1116 subpatterns: subpatterns.fold_with(folder)
1120 } => PatternKind::Leaf {
1121 subpatterns: subpatterns.fold_with(folder),
1123 PatternKind::Deref {
1125 } => PatternKind::Deref {
1126 subpattern: subpattern.fold_with(folder),
1128 PatternKind::Constant {
1130 } => PatternKind::Constant {
1131 value: value.fold_with(folder)
1133 PatternKind::Range(PatternRange {
1138 }) => PatternKind::Range(PatternRange {
1139 lo: lo.fold_with(folder),
1140 hi: hi.fold_with(folder),
1141 ty: ty.fold_with(folder),
1144 PatternKind::Slice {
1148 } => PatternKind::Slice {
1149 prefix: prefix.fold_with(folder),
1150 slice: slice.fold_with(folder),
1151 suffix: suffix.fold_with(folder)
1153 PatternKind::Array {
1157 } => PatternKind::Array {
1158 prefix: prefix.fold_with(folder),
1159 slice: slice.fold_with(folder),
1160 suffix: suffix.fold_with(folder)
1166 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1167 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1170 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1171 ) -> Option<Ordering> {
1172 trace!("compare_const_vals: {:?}, {:?}", a, b);
1174 let from_bool = |v: bool| {
1176 Some(Ordering::Equal)
1182 let fallback = || from_bool(a == b);
1184 // Use the fallback if any type differs
1185 if a.ty != b.ty || a.ty != ty.value {
1189 let tcx = tcx.global_tcx();
1190 let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1192 // FIXME: This should use assert_bits(ty) instead of use_bits
1193 // but triggers possibly bugs due to mismatching of arrays and slices
1194 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1195 use ::rustc_apfloat::Float;
1196 return match ty.value.sty {
1197 ty::Float(ast::FloatTy::F32) => {
1198 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1199 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1202 ty::Float(ast::FloatTy::F64) => {
1203 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1204 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1208 let layout = tcx.layout_of(ty).ok()?;
1209 assert!(layout.abi.is_signed());
1210 let a = sign_extend(a, layout.size);
1211 let b = sign_extend(b, layout.size);
1212 Some((a as i128).cmp(&(b as i128)))
1214 _ => Some(a.cmp(&b)),
1218 if let ty::Str = ty.value.sty {
1219 match (a.val, b.val) {
1221 ConstValue::ScalarPair(
1225 ConstValue::ScalarPair(
1229 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1230 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1231 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1233 let map = tcx.alloc_map.lock();
1234 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1235 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1236 if alloc_a.bytes.len() as u128 == len_a {
1237 return from_bool(alloc_a == alloc_b);