1 //! Validation of patterns/matches.
6 pub use self::check_match::check_crate;
7 pub(crate) use self::check_match::check_match;
9 use crate::const_eval::{const_field, const_variant_index};
11 use crate::hair::util::UserAnnotatedTyHelpers;
12 use crate::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(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<'tcx> {
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: &'tcx Substs<'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: 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: ty::Const<'tcx>,
180 pub hi: 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 fmt_const_val(f, value)
296 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
297 fmt_const_val(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: &'tcx Substs<'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, &'tcx Substs<'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, &'tcx Substs<'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 use std::cmp::Ordering;
432 let cmp = compare_const_vals(
436 self.param_env.and(ty),
439 (RangeEnd::Excluded, Some(Ordering::Less)) =>
440 PatternKind::Range(PatternRange { lo, hi, ty, end }),
441 (RangeEnd::Excluded, _) => {
446 "lower range bound must be less than upper",
450 (RangeEnd::Included, Some(Ordering::Equal)) => {
451 PatternKind::Constant { value: lo }
453 (RangeEnd::Included, Some(Ordering::Less)) => {
454 PatternKind::Range(PatternRange { lo, hi, ty, end })
456 (RangeEnd::Included, _) => {
457 let mut err = struct_span_err!(
461 "lower range bound must be less than or equal to upper"
465 "lower bound larger than upper bound",
467 if self.tcx.sess.teach(&err.get_code().unwrap()) {
468 err.note("When matching against a range, the compiler \
469 verifies that the range is non-empty. Range \
470 patterns include both end-points, so this is \
471 equivalent to requiring the start of the range \
472 to be less than or equal to the end of the range.");
480 self.tcx.sess.delay_span_bug(
483 "found bad range pattern `{:?}` outside of error recovery",
492 // If we are handling a range with associated constants (e.g.
493 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
494 // constants somewhere. Have them on the range pattern.
495 for ascription in &[lo_ascription, hi_ascription] {
496 if let Some(ascription) = ascription {
497 kind = PatternKind::AscribeUserType {
498 ascription: *ascription,
499 subpattern: Pattern { span: pat.span, ty, kind: Box::new(kind), },
507 PatKind::Path(ref qpath) => {
508 return self.lower_path(qpath, pat.hir_id, pat.span);
511 PatKind::Ref(ref subpattern, _) |
512 PatKind::Box(ref subpattern) => {
513 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
516 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
520 subpattern: Pattern {
523 kind: Box::new(self.slice_or_array_pattern(
524 pat.span, ty, prefix, slice, suffix))
529 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
530 ty::Error => { // Avoid ICE
531 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
536 "unexpanded type for vector pattern: {:?}",
541 PatKind::Tuple(ref subpatterns, ddpos) => {
543 ty::Tuple(ref tys) => {
546 .enumerate_and_adjust(tys.len(), ddpos)
547 .map(|(i, subpattern)| FieldPattern {
548 field: Field::new(i),
549 pattern: self.lower_pattern(subpattern)
553 PatternKind::Leaf { subpatterns }
555 ty::Error => { // Avoid ICE (#50577)
556 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
558 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
562 PatKind::Binding(_, id, _, ident, ref sub) => {
563 let var_ty = self.tables.node_type(pat.hir_id);
564 if let ty::Error = var_ty.sty {
566 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
568 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
569 .expect("missing binding mode");
570 let (mutability, mode) = match bm {
571 ty::BindByValue(hir::MutMutable) =>
572 (Mutability::Mut, BindingMode::ByValue),
573 ty::BindByValue(hir::MutImmutable) =>
574 (Mutability::Not, BindingMode::ByValue),
575 ty::BindByReference(hir::MutMutable) =>
576 (Mutability::Not, BindingMode::ByRef(
577 BorrowKind::Mut { allow_two_phase_borrow: false })),
578 ty::BindByReference(hir::MutImmutable) =>
579 (Mutability::Not, BindingMode::ByRef(
580 BorrowKind::Shared)),
583 // A ref x pattern is the same node used for x, and as such it has
584 // x's type, which is &T, where we want T (the type being matched).
585 if let ty::BindByReference(_) = bm {
586 if let ty::Ref(_, rty, _) = ty.sty {
589 bug!("`ref {}` has wrong type {}", ident, ty);
593 PatternKind::Binding {
599 subpattern: self.lower_opt_pattern(sub),
603 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
604 let def = self.tables.qpath_def(qpath, pat.hir_id);
605 let adt_def = match ty.sty {
606 ty::Adt(adt_def, _) => adt_def,
607 ty::Error => { // Avoid ICE (#50585)
608 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
610 _ => span_bug!(pat.span,
611 "tuple struct pattern not applied to an ADT {:?}",
614 let variant_def = adt_def.variant_of_def(def);
618 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
619 .map(|(i, field)| FieldPattern {
620 field: Field::new(i),
621 pattern: self.lower_pattern(field),
625 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
628 PatKind::Struct(ref qpath, ref fields, _) => {
629 let def = self.tables.qpath_def(qpath, pat.hir_id);
634 field: Field::new(self.tcx.field_index(field.node.id,
636 pattern: self.lower_pattern(&field.node.pat),
641 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
648 kind: Box::new(kind),
652 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
653 pats.iter().map(|p| self.lower_pattern(p)).collect()
656 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
658 pat.as_ref().map(|p| self.lower_pattern(p))
661 fn flatten_nested_slice_patterns(
663 prefix: Vec<Pattern<'tcx>>,
664 slice: Option<Pattern<'tcx>>,
665 suffix: Vec<Pattern<'tcx>>)
666 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
668 let orig_slice = match slice {
669 Some(orig_slice) => orig_slice,
670 None => return (prefix, slice, suffix)
672 let orig_prefix = prefix;
673 let orig_suffix = suffix;
675 // dance because of intentional borrow-checker stupidity.
676 let kind = *orig_slice.kind;
678 PatternKind::Slice { prefix, slice, mut suffix } |
679 PatternKind::Array { prefix, slice, mut suffix } => {
680 let mut orig_prefix = orig_prefix;
682 orig_prefix.extend(prefix);
683 suffix.extend(orig_suffix);
685 (orig_prefix, slice, suffix)
688 (orig_prefix, Some(Pattern {
689 kind: box kind, ..orig_slice
695 fn slice_or_array_pattern(
699 prefix: &'tcx [P<hir::Pat>],
700 slice: &'tcx Option<P<hir::Pat>>,
701 suffix: &'tcx [P<hir::Pat>])
704 let prefix = self.lower_patterns(prefix);
705 let slice = self.lower_opt_pattern(slice);
706 let suffix = self.lower_patterns(suffix);
707 let (prefix, slice, suffix) =
708 self.flatten_nested_slice_patterns(prefix, slice, suffix);
712 // matching a slice or fixed-length array
713 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
716 ty::Array(_, len) => {
717 // fixed-length array
718 let len = len.unwrap_usize(self.tcx);
719 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
720 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
724 span_bug!(span, "bad slice pattern type {:?}", ty);
729 fn lower_variant_or_leaf(
735 subpatterns: Vec<FieldPattern<'tcx>>,
736 ) -> PatternKind<'tcx> {
737 let mut kind = match def {
738 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
739 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
740 let adt_def = self.tcx.adt_def(enum_id);
741 if adt_def.is_enum() {
742 let substs = match ty.sty {
744 ty::FnDef(_, substs) => substs,
745 ty::Error => { // Avoid ICE (#50585)
746 return PatternKind::Wild;
748 _ => bug!("inappropriate type for def: {:?}", ty.sty),
750 PatternKind::Variant {
753 variant_index: adt_def.variant_index_with_id(variant_id),
757 PatternKind::Leaf { subpatterns }
761 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
762 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
763 PatternKind::Leaf { subpatterns }
767 self.errors.push(PatternError::NonConstPath(span));
772 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
773 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
774 kind = PatternKind::AscribeUserType {
775 subpattern: Pattern {
778 kind: Box::new(kind),
780 ascription: Ascription {
781 user_ty: PatternTypeProjection::from_user_type(user_ty),
783 variance: ty::Variance::Covariant,
791 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
792 /// it to `const_to_pat`. Any other path (like enum variants without fields)
793 /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
794 fn lower_path(&mut self,
799 let ty = self.tables.node_type(id);
800 let def = self.tables.qpath_def(qpath, id);
801 let is_associated_const = match def {
802 Def::AssociatedConst(_) => true,
805 let kind = match def {
806 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
807 let substs = self.tables.node_substs(id);
808 match ty::Instance::resolve(
819 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
821 let pattern = self.const_to_pat(instance, value, id, span);
822 if !is_associated_const {
826 let user_provided_types = self.tables().user_provided_types();
827 return if let Some(u_ty) = user_provided_types.get(id) {
828 let user_ty = PatternTypeProjection::from_user_type(*u_ty);
832 PatternKind::AscribeUserType {
834 ascription: Ascription {
835 /// Note that use `Contravariant` here. See the
836 /// `variance` field documentation for details.
837 variance: ty::Variance::Contravariant,
850 self.tcx.sess.span_err(
852 "could not evaluate constant pattern",
859 self.errors.push(if is_associated_const {
860 PatternError::AssociatedConstInPattern(span)
862 PatternError::StaticInPattern(span)
868 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
874 kind: Box::new(kind),
878 /// Converts literals, paths and negation of literals to patterns.
879 /// The special case for negation exists to allow things like `-128_i8`
880 /// which would overflow if we tried to evaluate `128_i8` and then negate
882 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
884 hir::ExprKind::Lit(ref lit) => {
885 let ty = self.tables.expr_ty(expr);
886 match lit_to_const(&lit.node, self.tcx, ty, false) {
888 let instance = ty::Instance::new(
889 self.tables.local_id_root.expect("literal outside any scope"),
892 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
894 Err(LitToConstError::UnparseableFloat) => {
895 self.errors.push(PatternError::FloatBug);
898 Err(LitToConstError::Reported) => PatternKind::Wild,
901 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
902 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
903 let ty = self.tables.expr_ty(expr);
904 let lit = match expr.node {
905 hir::ExprKind::Lit(ref lit) => lit,
906 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
908 match lit_to_const(&lit.node, self.tcx, ty, true) {
910 let instance = ty::Instance::new(
911 self.tables.local_id_root.expect("literal outside any scope"),
914 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
916 Err(LitToConstError::UnparseableFloat) => {
917 self.errors.push(PatternError::FloatBug);
920 Err(LitToConstError::Reported) => PatternKind::Wild,
923 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
927 /// Converts an evaluated constant to a pattern (if possible).
928 /// This means aggregate values (like structs and enums) are converted
929 /// to a pattern that matches the value (as if you'd compared via equality).
932 instance: ty::Instance<'tcx>,
937 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
938 let adt_subpattern = |i, variant_opt| {
939 let field = Field::new(i);
940 let val = const_field(
941 self.tcx, self.param_env,
942 variant_opt, field, cv,
943 ).expect("field access failed");
944 self.const_to_pat(instance, val, id, span)
946 let adt_subpatterns = |n, variant_opt| {
948 let field = Field::new(i);
951 pattern: adt_subpattern(i, variant_opt),
953 }).collect::<Vec<_>>()
955 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
956 let kind = match cv.ty.sty {
958 let id = self.tcx.hir().hir_to_node_id(id);
960 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
963 "floating-point types cannot be used in patterns",
965 PatternKind::Constant {
969 ty::Adt(adt_def, _) if adt_def.is_union() => {
970 // Matching on union fields is unsafe, we can't hide it in constants
971 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
974 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
975 let msg = format!("to use a constant of type `{}` in a pattern, \
976 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
977 self.tcx.item_path_str(adt_def.did),
978 self.tcx.item_path_str(adt_def.did));
979 self.tcx.sess.span_err(span, &msg);
982 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
983 let variant_index = const_variant_index(
984 self.tcx, self.param_env, cv
985 ).expect("const_variant_index failed");
986 let subpatterns = adt_subpatterns(
987 adt_def.variants[variant_index].fields.len(),
990 PatternKind::Variant {
997 ty::Adt(adt_def, _) => {
998 let struct_var = adt_def.non_enum_variant();
1000 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1003 ty::Tuple(fields) => {
1005 subpatterns: adt_subpatterns(fields.len(), None),
1008 ty::Array(_, n) => {
1009 PatternKind::Array {
1010 prefix: (0..n.unwrap_usize(self.tcx))
1011 .map(|i| adt_subpattern(i as usize, None))
1018 PatternKind::Constant {
1027 kind: Box::new(kind),
1032 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1033 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1037 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1043 pub trait PatternFoldable<'tcx> : Sized {
1044 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1045 self.super_fold_with(folder)
1048 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1051 pub trait PatternFolder<'tcx> : Sized {
1052 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1053 pattern.super_fold_with(self)
1056 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1057 kind.super_fold_with(self)
1062 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1063 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1064 let content: T = (**self).fold_with(folder);
1069 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1070 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1071 self.iter().map(|t| t.fold_with(folder)).collect()
1075 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1076 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1077 self.as_ref().map(|t| t.fold_with(folder))
1081 macro_rules! CloneImpls {
1082 (<$lt_tcx:tt> $($ty:ty),+) => {
1084 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1085 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1094 Span, Field, Mutability, ast::Name, ast::NodeId, usize, ty::Const<'tcx>,
1095 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1096 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserType<'tcx>,
1097 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1100 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1101 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1103 field: self.field.fold_with(folder),
1104 pattern: self.pattern.fold_with(folder)
1109 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1110 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1111 folder.fold_pattern(self)
1114 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1116 ty: self.ty.fold_with(folder),
1117 span: self.span.fold_with(folder),
1118 kind: self.kind.fold_with(folder)
1123 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1124 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1125 folder.fold_pattern_kind(self)
1128 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1130 PatternKind::Wild => PatternKind::Wild,
1131 PatternKind::AscribeUserType {
1133 ascription: Ascription {
1138 } => PatternKind::AscribeUserType {
1139 subpattern: subpattern.fold_with(folder),
1140 ascription: Ascription {
1141 user_ty: user_ty.fold_with(folder),
1146 PatternKind::Binding {
1153 } => PatternKind::Binding {
1154 mutability: mutability.fold_with(folder),
1155 name: name.fold_with(folder),
1156 mode: mode.fold_with(folder),
1157 var: var.fold_with(folder),
1158 ty: ty.fold_with(folder),
1159 subpattern: subpattern.fold_with(folder),
1161 PatternKind::Variant {
1166 } => PatternKind::Variant {
1167 adt_def: adt_def.fold_with(folder),
1168 substs: substs.fold_with(folder),
1170 subpatterns: subpatterns.fold_with(folder)
1174 } => PatternKind::Leaf {
1175 subpatterns: subpatterns.fold_with(folder),
1177 PatternKind::Deref {
1179 } => PatternKind::Deref {
1180 subpattern: subpattern.fold_with(folder),
1182 PatternKind::Constant {
1184 } => PatternKind::Constant {
1185 value: value.fold_with(folder)
1187 PatternKind::Range(PatternRange {
1192 }) => PatternKind::Range(PatternRange {
1193 lo: lo.fold_with(folder),
1194 hi: hi.fold_with(folder),
1195 ty: ty.fold_with(folder),
1198 PatternKind::Slice {
1202 } => PatternKind::Slice {
1203 prefix: prefix.fold_with(folder),
1204 slice: slice.fold_with(folder),
1205 suffix: suffix.fold_with(folder)
1207 PatternKind::Array {
1211 } => PatternKind::Array {
1212 prefix: prefix.fold_with(folder),
1213 slice: slice.fold_with(folder),
1214 suffix: suffix.fold_with(folder)
1220 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1221 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1224 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1225 ) -> Option<Ordering> {
1226 trace!("compare_const_vals: {:?}, {:?}", a, b);
1228 let from_bool = |v: bool| {
1230 Some(Ordering::Equal)
1236 let fallback = || from_bool(a == b);
1238 // Use the fallback if any type differs
1239 if a.ty != b.ty || a.ty != ty.value {
1243 let tcx = tcx.global_tcx();
1244 let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1246 // FIXME: This should use assert_bits(ty) instead of use_bits
1247 // but triggers possibly bugs due to mismatching of arrays and slices
1248 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1249 use ::rustc_apfloat::Float;
1250 return match ty.value.sty {
1251 ty::Float(ast::FloatTy::F32) => {
1252 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1253 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1256 ty::Float(ast::FloatTy::F64) => {
1257 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1258 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1262 let layout = tcx.layout_of(ty).ok()?;
1263 assert!(layout.abi.is_signed());
1264 let a = sign_extend(a, layout.size);
1265 let b = sign_extend(b, layout.size);
1266 Some((a as i128).cmp(&(b as i128)))
1268 _ => Some(a.cmp(&b)),
1272 if let ty::Str = ty.value.sty {
1273 match (a.val, b.val) {
1283 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1285 let map = tcx.alloc_map.lock();
1286 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1287 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1288 if alloc_a.bytes.len() as u64 == len_a {
1289 return from_bool(alloc_a == alloc_b);