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, UserTypeAnnotation, UserTypeProjection, UserTypeProjections};
16 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
17 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, Lift};
18 use rustc::ty::subst::{Substs, Kind};
19 use rustc::ty::layout::VariantIdx;
20 use rustc::hir::{self, PatKind, RangeEnd};
21 use rustc::hir::def::{Def, CtorKind};
22 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
24 use rustc_data_structures::indexed_vec::Idx;
26 use std::cmp::Ordering;
32 #[derive(Clone, Debug)]
33 pub enum PatternError {
34 AssociatedConstInPattern(Span),
35 StaticInPattern(Span),
40 #[derive(Copy, Clone, Debug)]
41 pub enum BindingMode<'tcx> {
43 ByRef(Region<'tcx>, BorrowKind),
46 #[derive(Clone, Debug)]
47 pub struct FieldPattern<'tcx> {
49 pub pattern: Pattern<'tcx>,
52 #[derive(Clone, Debug)]
53 pub struct Pattern<'tcx> {
56 pub kind: Box<PatternKind<'tcx>>,
60 #[derive(Clone, Debug)]
61 pub(crate) struct PatternTypeProjections<'tcx> {
62 contents: Vec<(PatternTypeProjection<'tcx>, Span)>,
65 impl<'tcx> PatternTypeProjections<'tcx> {
66 pub(crate) fn user_ty(self) -> UserTypeProjections<'tcx> {
67 UserTypeProjections::from_projections(
68 self.contents.into_iter().map(|(pat_ty_proj, span)| (pat_ty_proj.user_ty(), span)))
71 pub(crate) fn none() -> Self {
72 PatternTypeProjections { contents: vec![] }
75 pub(crate) fn ref_binding(&self) -> Self {
76 // FIXME(#55401): ignore for now
77 PatternTypeProjections { contents: vec![] }
81 mut f: impl FnMut(&PatternTypeProjection<'tcx>) -> PatternTypeProjection<'tcx>)
84 PatternTypeProjections {
85 contents: self.contents
87 .map(|(proj, span)| (f(proj), *span))
91 pub(crate) fn index(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.index()) }
93 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
94 self.map_projs(|pat_ty_proj| pat_ty_proj.subslice(from, to))
97 pub(crate) fn deref(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.deref()) }
99 pub(crate) fn leaf(&self, field: Field) -> Self {
100 self.map_projs(|pat_ty_proj| pat_ty_proj.leaf(field))
103 pub(crate) fn variant(&self,
104 adt_def: &'tcx AdtDef,
105 variant_index: VariantIdx,
106 field: Field) -> Self {
107 self.map_projs(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
110 pub(crate) fn add_user_type(&self, user_ty: &PatternTypeProjection<'tcx>, sp: Span) -> Self {
111 let mut new = self.clone();
112 new.contents.push((user_ty.clone(), sp));
117 #[derive(Clone, Debug)]
118 pub struct PatternTypeProjection<'tcx>(UserTypeProjection<'tcx>);
120 impl<'tcx> PatternTypeProjection<'tcx> {
121 pub(crate) fn index(&self) -> Self {
122 let mut new = self.clone();
123 new.0.projs.push(ProjectionElem::Index(()));
127 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
128 let mut new = self.clone();
129 new.0.projs.push(ProjectionElem::Subslice { from, to });
133 pub(crate) fn deref(&self) -> Self {
134 let mut new = self.clone();
135 new.0.projs.push(ProjectionElem::Deref);
139 pub(crate) fn leaf(&self, field: Field) -> Self {
140 let mut new = self.clone();
141 new.0.projs.push(ProjectionElem::Field(field, ()));
145 pub(crate) fn variant(&self,
146 adt_def: &'tcx AdtDef,
147 variant_index: VariantIdx,
148 field: Field) -> Self {
149 let mut new = self.clone();
150 new.0.projs.push(ProjectionElem::Downcast(adt_def, variant_index));
151 new.0.projs.push(ProjectionElem::Field(field, ()));
155 pub(crate) fn from_canonical_ty(c_ty: ty::CanonicalTy<'tcx>) -> Self {
156 Self::from_user_type(UserTypeAnnotation::Ty(c_ty))
159 pub(crate) fn from_user_type(u_ty: UserTypeAnnotation<'tcx>) -> Self {
160 Self::from_user_type_proj(UserTypeProjection { base: u_ty, projs: vec![], })
163 pub(crate) fn from_user_type_proj(u_ty: UserTypeProjection<'tcx>) -> Self {
164 PatternTypeProjection(u_ty)
167 pub(crate) fn user_ty(self) -> UserTypeProjection<'tcx> { self.0 }
170 #[derive(Clone, Debug)]
171 pub enum PatternKind<'tcx> {
175 user_ty: PatternTypeProjection<'tcx>,
176 subpattern: Pattern<'tcx>,
180 /// x, ref x, x @ P, etc
182 mutability: Mutability,
184 mode: BindingMode<'tcx>,
187 subpattern: Option<Pattern<'tcx>>,
190 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
192 adt_def: &'tcx AdtDef,
193 substs: &'tcx Substs<'tcx>,
194 variant_index: VariantIdx,
195 subpatterns: Vec<FieldPattern<'tcx>>,
198 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
200 subpatterns: Vec<FieldPattern<'tcx>>,
203 /// box P, &P, &mut P, etc
205 subpattern: Pattern<'tcx>,
209 value: &'tcx ty::Const<'tcx>,
212 Range(PatternRange<'tcx>),
214 /// matches against a slice, checking the length and extracting elements.
215 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
216 /// e.g., `&[ref xs..]`.
218 prefix: Vec<Pattern<'tcx>>,
219 slice: Option<Pattern<'tcx>>,
220 suffix: Vec<Pattern<'tcx>>,
223 /// fixed match against an array, irrefutable
225 prefix: Vec<Pattern<'tcx>>,
226 slice: Option<Pattern<'tcx>>,
227 suffix: Vec<Pattern<'tcx>>,
231 #[derive(Clone, Copy, Debug, PartialEq)]
232 pub struct PatternRange<'tcx> {
233 pub lo: &'tcx ty::Const<'tcx>,
234 pub hi: &'tcx ty::Const<'tcx>,
239 impl<'tcx> fmt::Display for Pattern<'tcx> {
240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
242 PatternKind::Wild => write!(f, "_"),
243 PatternKind::AscribeUserType { ref subpattern, .. } =>
244 write!(f, "{}: _", subpattern),
245 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
246 let is_mut = match mode {
247 BindingMode::ByValue => mutability == Mutability::Mut,
248 BindingMode::ByRef(_, bk) => {
250 match bk { BorrowKind::Mut { .. } => true, _ => false }
256 write!(f, "{}", name)?;
257 if let Some(ref subpattern) = *subpattern {
258 write!(f, " @ {}", subpattern)?;
262 PatternKind::Variant { ref subpatterns, .. } |
263 PatternKind::Leaf { ref subpatterns } => {
264 let variant = match *self.kind {
265 PatternKind::Variant { adt_def, variant_index, .. } => {
266 Some(&adt_def.variants[variant_index])
268 _ => if let ty::Adt(adt, _) = self.ty.sty {
270 Some(&adt.variants[VariantIdx::new(0)])
279 let mut first = true;
280 let mut start_or_continue = || if first { first = false; "" } else { ", " };
282 if let Some(variant) = variant {
283 write!(f, "{}", variant.ident)?;
285 // Only for Adt we can have `S {...}`,
286 // which we handle separately here.
287 if variant.ctor_kind == CtorKind::Fictive {
291 for p in subpatterns {
292 if let PatternKind::Wild = *p.pattern.kind {
295 let name = variant.fields[p.field.index()].ident;
296 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
300 if printed < variant.fields.len() {
301 write!(f, "{}..", start_or_continue())?;
304 return write!(f, " }}");
308 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
309 if num_fields != 0 || variant.is_none() {
311 for i in 0..num_fields {
312 write!(f, "{}", start_or_continue())?;
314 // Common case: the field is where we expect it.
315 if let Some(p) = subpatterns.get(i) {
316 if p.field.index() == i {
317 write!(f, "{}", p.pattern)?;
322 // Otherwise, we have to go looking for it.
323 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
324 write!(f, "{}", p.pattern)?;
334 PatternKind::Deref { ref subpattern } => {
336 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
337 ty::Ref(_, _, mutbl) => {
339 if mutbl == hir::MutMutable {
343 _ => bug!("{} is a bad Deref pattern type", self.ty)
345 write!(f, "{}", subpattern)
347 PatternKind::Constant { value } => {
348 fmt_const_val(f, value)
350 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
351 fmt_const_val(f, lo)?;
353 RangeEnd::Included => write!(f, "..=")?,
354 RangeEnd::Excluded => write!(f, "..")?,
358 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
359 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
360 let mut first = true;
361 let mut start_or_continue = || if first { first = false; "" } else { ", " };
364 write!(f, "{}{}", start_or_continue(), p)?;
366 if let Some(ref slice) = *slice {
367 write!(f, "{}", start_or_continue())?;
369 PatternKind::Wild => {}
370 _ => write!(f, "{}", slice)?
375 write!(f, "{}{}", start_or_continue(), p)?;
383 pub struct PatternContext<'a, 'tcx: 'a> {
384 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
385 pub param_env: ty::ParamEnv<'tcx>,
386 pub tables: &'a ty::TypeckTables<'tcx>,
387 pub substs: &'tcx Substs<'tcx>,
388 pub errors: Vec<PatternError>,
391 impl<'a, 'tcx> Pattern<'tcx> {
392 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
393 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
394 tables: &'a ty::TypeckTables<'tcx>,
395 pat: &'tcx hir::Pat) -> Self {
396 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
397 let result = pcx.lower_pattern(pat);
398 if !pcx.errors.is_empty() {
399 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
400 tcx.sess.delay_span_bug(pat.span, &msg);
402 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
407 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
408 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
409 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
410 tables: &'a ty::TypeckTables<'tcx>) -> Self {
413 param_env: param_env_and_substs.param_env,
415 substs: param_env_and_substs.value,
420 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
421 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
422 // pattern has the type that results *after* dereferencing. For example, in this code:
425 // match &&Some(0i32) {
426 // Some(n) => { ... },
431 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
432 // determined in rustc_typeck::check::match). The adjustments would be
434 // `vec![&&Option<i32>, &Option<i32>]`.
436 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
437 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
438 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
439 // gets the least-dereferenced type).
440 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
447 .fold(unadjusted_pat, |pat, ref_ty| {
448 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
452 kind: Box::new(PatternKind::Deref { subpattern: pat }),
458 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
459 let mut ty = self.tables.node_id_to_type(pat.hir_id);
461 let kind = match pat.node {
462 PatKind::Wild => PatternKind::Wild,
464 PatKind::Lit(ref value) => self.lower_lit(value),
466 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
467 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
468 (PatternKind::Constant { value: lo },
469 PatternKind::Constant { value: hi }) => {
470 use std::cmp::Ordering;
471 let cmp = compare_const_vals(
475 self.param_env.and(ty),
478 (RangeEnd::Excluded, Some(Ordering::Less)) =>
479 PatternKind::Range(PatternRange { lo, hi, ty, end }),
480 (RangeEnd::Excluded, _) => {
485 "lower range bound must be less than upper",
489 (RangeEnd::Included, Some(Ordering::Equal)) => {
490 PatternKind::Constant { value: lo }
492 (RangeEnd::Included, Some(Ordering::Less)) => {
493 PatternKind::Range(PatternRange { lo, hi, ty, end })
495 (RangeEnd::Included, _) => {
496 let mut err = struct_span_err!(
500 "lower range bound must be less than or equal to upper"
504 "lower bound larger than upper bound",
506 if self.tcx.sess.teach(&err.get_code().unwrap()) {
507 err.note("When matching against a range, the compiler \
508 verifies that the range is non-empty. Range \
509 patterns include both end-points, so this is \
510 equivalent to requiring the start of the range \
511 to be less than or equal to the end of the range.");
518 _ => PatternKind::Wild
522 PatKind::Path(ref qpath) => {
523 return self.lower_path(qpath, pat.hir_id, pat.span);
526 PatKind::Ref(ref subpattern, _) |
527 PatKind::Box(ref subpattern) => {
528 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
531 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
535 subpattern: Pattern {
538 kind: Box::new(self.slice_or_array_pattern(
539 pat.span, ty, prefix, slice, suffix))
544 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
545 ty::Error => { // Avoid ICE
546 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
551 "unexpanded type for vector pattern: {:?}",
556 PatKind::Tuple(ref subpatterns, ddpos) => {
558 ty::Tuple(ref tys) => {
561 .enumerate_and_adjust(tys.len(), ddpos)
562 .map(|(i, subpattern)| FieldPattern {
563 field: Field::new(i),
564 pattern: self.lower_pattern(subpattern)
568 PatternKind::Leaf { subpatterns }
570 ty::Error => { // Avoid ICE (#50577)
571 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
573 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
577 PatKind::Binding(_, id, ident, ref sub) => {
578 let var_ty = self.tables.node_id_to_type(pat.hir_id);
579 let region = match var_ty.sty {
580 ty::Ref(r, _, _) => Some(r),
581 ty::Error => { // Avoid ICE
582 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
586 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
587 .expect("missing binding mode");
588 let (mutability, mode) = match bm {
589 ty::BindByValue(hir::MutMutable) =>
590 (Mutability::Mut, BindingMode::ByValue),
591 ty::BindByValue(hir::MutImmutable) =>
592 (Mutability::Not, BindingMode::ByValue),
593 ty::BindByReference(hir::MutMutable) =>
594 (Mutability::Not, BindingMode::ByRef(
595 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
596 ty::BindByReference(hir::MutImmutable) =>
597 (Mutability::Not, BindingMode::ByRef(
598 region.unwrap(), BorrowKind::Shared)),
601 // A ref x pattern is the same node used for x, and as such it has
602 // x's type, which is &T, where we want T (the type being matched).
603 if let ty::BindByReference(_) = bm {
604 if let ty::Ref(_, rty, _) = ty.sty {
607 bug!("`ref {}` has wrong type {}", ident, ty);
611 PatternKind::Binding {
617 subpattern: self.lower_opt_pattern(sub),
621 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
622 let def = self.tables.qpath_def(qpath, pat.hir_id);
623 let adt_def = match ty.sty {
624 ty::Adt(adt_def, _) => adt_def,
625 ty::Error => { // Avoid ICE (#50585)
626 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
628 _ => span_bug!(pat.span,
629 "tuple struct pattern not applied to an ADT {:?}",
632 let variant_def = adt_def.variant_of_def(def);
636 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
637 .map(|(i, field)| FieldPattern {
638 field: Field::new(i),
639 pattern: self.lower_pattern(field),
643 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
646 PatKind::Struct(ref qpath, ref fields, _) => {
647 let def = self.tables.qpath_def(qpath, pat.hir_id);
652 field: Field::new(self.tcx.field_index(field.node.id,
654 pattern: self.lower_pattern(&field.node.pat),
659 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
666 kind: Box::new(kind),
670 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
671 pats.iter().map(|p| self.lower_pattern(p)).collect()
674 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
676 pat.as_ref().map(|p| self.lower_pattern(p))
679 fn flatten_nested_slice_patterns(
681 prefix: Vec<Pattern<'tcx>>,
682 slice: Option<Pattern<'tcx>>,
683 suffix: Vec<Pattern<'tcx>>)
684 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
686 let orig_slice = match slice {
687 Some(orig_slice) => orig_slice,
688 None => return (prefix, slice, suffix)
690 let orig_prefix = prefix;
691 let orig_suffix = suffix;
693 // dance because of intentional borrow-checker stupidity.
694 let kind = *orig_slice.kind;
696 PatternKind::Slice { prefix, slice, mut suffix } |
697 PatternKind::Array { prefix, slice, mut suffix } => {
698 let mut orig_prefix = orig_prefix;
700 orig_prefix.extend(prefix);
701 suffix.extend(orig_suffix);
703 (orig_prefix, slice, suffix)
706 (orig_prefix, Some(Pattern {
707 kind: box kind, ..orig_slice
713 fn slice_or_array_pattern(
717 prefix: &'tcx [P<hir::Pat>],
718 slice: &'tcx Option<P<hir::Pat>>,
719 suffix: &'tcx [P<hir::Pat>])
722 let prefix = self.lower_patterns(prefix);
723 let slice = self.lower_opt_pattern(slice);
724 let suffix = self.lower_patterns(suffix);
725 let (prefix, slice, suffix) =
726 self.flatten_nested_slice_patterns(prefix, slice, suffix);
730 // matching a slice or fixed-length array
731 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
734 ty::Array(_, len) => {
735 // fixed-length array
736 let len = len.unwrap_usize(self.tcx);
737 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
738 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
742 span_bug!(span, "bad slice pattern type {:?}", ty);
747 fn lower_variant_or_leaf(
753 subpatterns: Vec<FieldPattern<'tcx>>,
754 ) -> PatternKind<'tcx> {
755 let mut kind = match def {
756 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
757 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
758 let adt_def = self.tcx.adt_def(enum_id);
759 if adt_def.is_enum() {
760 let substs = match ty.sty {
762 ty::FnDef(_, substs) => substs,
763 ty::Error => { // Avoid ICE (#50585)
764 return PatternKind::Wild;
766 _ => bug!("inappropriate type for def: {:?}", ty.sty),
768 PatternKind::Variant {
771 variant_index: adt_def.variant_index_with_id(variant_id),
775 PatternKind::Leaf { subpatterns }
779 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
780 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
781 PatternKind::Leaf { subpatterns }
785 self.errors.push(PatternError::NonConstPath(span));
790 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
791 let subpattern = Pattern {
794 kind: Box::new(kind),
797 debug!("pattern user_ty = {:?} for pattern at {:?}", user_ty, span);
799 let pat_ty = PatternTypeProjection::from_user_type(user_ty);
800 kind = PatternKind::AscribeUserType {
810 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
811 /// it to `const_to_pat`. Any other path (like enum variants without fields)
812 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
813 fn lower_path(&mut self,
818 let ty = self.tables.node_id_to_type(id);
819 let def = self.tables.qpath_def(qpath, id);
820 let is_associated_const = match def {
821 Def::AssociatedConst(_) => true,
824 let kind = match def {
825 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
826 let substs = self.tables.node_substs(id);
827 match ty::Instance::resolve(
838 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
840 return self.const_to_pat(instance, value, id, span)
843 self.tcx.sess.span_err(
845 "could not evaluate constant pattern",
852 self.errors.push(if is_associated_const {
853 PatternError::AssociatedConstInPattern(span)
855 PatternError::StaticInPattern(span)
861 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
867 kind: Box::new(kind),
871 /// Converts literals, paths and negation of literals to patterns.
872 /// The special case for negation exists to allow things like -128i8
873 /// which would overflow if we tried to evaluate 128i8 and then negate
875 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
877 hir::ExprKind::Lit(ref lit) => {
878 let ty = self.tables.expr_ty(expr);
879 match lit_to_const(&lit.node, self.tcx, ty, false) {
881 let instance = ty::Instance::new(
882 self.tables.local_id_root.expect("literal outside any scope"),
885 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
887 Err(LitToConstError::UnparseableFloat) => {
888 self.errors.push(PatternError::FloatBug);
891 Err(LitToConstError::Reported) => PatternKind::Wild,
894 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
895 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
896 let ty = self.tables.expr_ty(expr);
897 let lit = match expr.node {
898 hir::ExprKind::Lit(ref lit) => lit,
899 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
901 match lit_to_const(&lit.node, self.tcx, ty, true) {
903 let instance = ty::Instance::new(
904 self.tables.local_id_root.expect("literal outside any scope"),
907 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
909 Err(LitToConstError::UnparseableFloat) => {
910 self.errors.push(PatternError::FloatBug);
913 Err(LitToConstError::Reported) => PatternKind::Wild,
916 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
920 /// Converts an evaluated constant to a pattern (if possible).
921 /// This means aggregate values (like structs and enums) are converted
922 /// to a pattern that matches the value (as if you'd compare via eq).
925 instance: ty::Instance<'tcx>,
926 cv: &'tcx ty::Const<'tcx>,
930 debug!("const_to_pat: cv={:#?}", cv);
931 let adt_subpattern = |i, variant_opt| {
932 let field = Field::new(i);
933 let val = const_field(
934 self.tcx, self.param_env, instance,
935 variant_opt, field, cv,
936 ).expect("field access failed");
937 self.const_to_pat(instance, val, id, span)
939 let adt_subpatterns = |n, variant_opt| {
941 let field = Field::new(i);
944 pattern: adt_subpattern(i, variant_opt),
946 }).collect::<Vec<_>>()
948 let kind = match cv.ty.sty {
950 let id = self.tcx.hir().hir_to_node_id(id);
952 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
955 "floating-point types cannot be used in patterns",
957 PatternKind::Constant {
961 ty::Adt(adt_def, _) if adt_def.is_union() => {
962 // Matching on union fields is unsafe, we can't hide it in constants
963 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
966 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
967 let msg = format!("to use a constant of type `{}` in a pattern, \
968 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
969 self.tcx.item_path_str(adt_def.did),
970 self.tcx.item_path_str(adt_def.did));
971 self.tcx.sess.span_err(span, &msg);
974 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
975 let variant_index = const_variant_index(
976 self.tcx, self.param_env, instance, cv
977 ).expect("const_variant_index failed");
978 let subpatterns = adt_subpatterns(
979 adt_def.variants[variant_index].fields.len(),
982 PatternKind::Variant {
989 ty::Adt(adt_def, _) => {
990 let struct_var = adt_def.non_enum_variant();
992 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
995 ty::Tuple(fields) => {
997 subpatterns: adt_subpatterns(fields.len(), None),
1000 ty::Array(_, n) => {
1001 PatternKind::Array {
1002 prefix: (0..n.unwrap_usize(self.tcx))
1003 .map(|i| adt_subpattern(i as usize, None))
1010 PatternKind::Constant {
1019 kind: Box::new(kind),
1024 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1025 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1029 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1035 pub trait PatternFoldable<'tcx> : Sized {
1036 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1037 self.super_fold_with(folder)
1040 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1043 pub trait PatternFolder<'tcx> : Sized {
1044 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1045 pattern.super_fold_with(self)
1048 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1049 kind.super_fold_with(self)
1054 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1055 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1056 let content: T = (**self).fold_with(folder);
1061 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1062 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1063 self.iter().map(|t| t.fold_with(folder)).collect()
1067 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1068 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1069 self.as_ref().map(|t| t.fold_with(folder))
1073 macro_rules! CloneImpls {
1074 (<$lt_tcx:tt> $($ty:ty),+) => {
1076 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1077 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1086 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
1087 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
1088 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>,
1089 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1092 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1093 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1095 field: self.field.fold_with(folder),
1096 pattern: self.pattern.fold_with(folder)
1101 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1102 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1103 folder.fold_pattern(self)
1106 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1108 ty: self.ty.fold_with(folder),
1109 span: self.span.fold_with(folder),
1110 kind: self.kind.fold_with(folder)
1115 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1116 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1117 folder.fold_pattern_kind(self)
1120 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1122 PatternKind::Wild => PatternKind::Wild,
1123 PatternKind::AscribeUserType {
1127 } => PatternKind::AscribeUserType {
1128 subpattern: subpattern.fold_with(folder),
1129 user_ty: user_ty.fold_with(folder),
1132 PatternKind::Binding {
1139 } => PatternKind::Binding {
1140 mutability: mutability.fold_with(folder),
1141 name: name.fold_with(folder),
1142 mode: mode.fold_with(folder),
1143 var: var.fold_with(folder),
1144 ty: ty.fold_with(folder),
1145 subpattern: subpattern.fold_with(folder),
1147 PatternKind::Variant {
1152 } => PatternKind::Variant {
1153 adt_def: adt_def.fold_with(folder),
1154 substs: substs.fold_with(folder),
1156 subpatterns: subpatterns.fold_with(folder)
1160 } => PatternKind::Leaf {
1161 subpatterns: subpatterns.fold_with(folder),
1163 PatternKind::Deref {
1165 } => PatternKind::Deref {
1166 subpattern: subpattern.fold_with(folder),
1168 PatternKind::Constant {
1170 } => PatternKind::Constant {
1171 value: value.fold_with(folder)
1173 PatternKind::Range(PatternRange {
1178 }) => PatternKind::Range(PatternRange {
1179 lo: lo.fold_with(folder),
1180 hi: hi.fold_with(folder),
1181 ty: ty.fold_with(folder),
1184 PatternKind::Slice {
1188 } => PatternKind::Slice {
1189 prefix: prefix.fold_with(folder),
1190 slice: slice.fold_with(folder),
1191 suffix: suffix.fold_with(folder)
1193 PatternKind::Array {
1197 } => PatternKind::Array {
1198 prefix: prefix.fold_with(folder),
1199 slice: slice.fold_with(folder),
1200 suffix: suffix.fold_with(folder)
1206 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1207 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1208 a: &'tcx ty::Const<'tcx>,
1209 b: &'tcx ty::Const<'tcx>,
1210 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1211 ) -> Option<Ordering> {
1212 trace!("compare_const_vals: {:?}, {:?}", a, b);
1214 let from_bool = |v: bool| {
1216 Some(Ordering::Equal)
1222 let fallback = || from_bool(a == b);
1224 // Use the fallback if any type differs
1225 if a.ty != b.ty || a.ty != ty.value {
1229 let tcx = tcx.global_tcx();
1230 let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1232 // FIXME: This should use assert_bits(ty) instead of use_bits
1233 // but triggers possibly bugs due to mismatching of arrays and slices
1234 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1235 use ::rustc_apfloat::Float;
1236 return match ty.value.sty {
1237 ty::Float(ast::FloatTy::F32) => {
1238 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1239 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1242 ty::Float(ast::FloatTy::F64) => {
1243 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1244 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1248 let layout = tcx.layout_of(ty).ok()?;
1249 assert!(layout.abi.is_signed());
1250 let a = sign_extend(a, layout.size);
1251 let b = sign_extend(b, layout.size);
1252 Some((a as i128).cmp(&(b as i128)))
1254 _ => Some(a.cmp(&b)),
1258 if let ty::Str = ty.value.sty {
1259 match (a.val, b.val) {
1261 ConstValue::ScalarPair(
1265 ConstValue::ScalarPair(
1269 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1270 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1271 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1273 let map = tcx.alloc_map.lock();
1274 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1275 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1276 if alloc_a.bytes.len() as u128 == len_a {
1277 return from_bool(alloc_a == alloc_b);