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, 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::{CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, UserTypeAnnotation};
19 use rustc::ty::subst::{Substs, Kind};
20 use rustc::ty::layout::VariantIdx;
21 use rustc::hir::{self, PatKind, RangeEnd};
22 use rustc::hir::def::{Def, CtorKind};
23 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
25 use rustc_data_structures::indexed_vec::Idx;
27 use std::cmp::Ordering;
33 #[derive(Clone, Debug)]
34 pub enum PatternError {
35 AssociatedConstInPattern(Span),
36 StaticInPattern(Span),
41 #[derive(Copy, Clone, Debug)]
42 pub enum BindingMode<'tcx> {
44 ByRef(Region<'tcx>, BorrowKind),
47 #[derive(Clone, Debug)]
48 pub struct FieldPattern<'tcx> {
50 pub pattern: Pattern<'tcx>,
53 #[derive(Clone, Debug)]
54 pub struct Pattern<'tcx> {
57 pub kind: Box<PatternKind<'tcx>>,
61 #[derive(Clone, Debug)]
62 pub(crate) struct PatternTypeProjections<'tcx> {
63 contents: Vec<(PatternTypeProjection<'tcx>, Span)>,
66 impl<'tcx> PatternTypeProjections<'tcx> {
67 pub(crate) fn user_ty(
69 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
70 ) -> UserTypeProjections<'tcx> {
71 UserTypeProjections::from_projections(
74 .map(|(pat_ty_proj, span)| (pat_ty_proj.user_ty(annotations, span), span))
78 pub(crate) fn none() -> Self {
79 PatternTypeProjections { contents: vec![] }
82 pub(crate) fn ref_binding(&self) -> Self {
83 // FIXME(#55401): ignore for now
84 PatternTypeProjections { contents: vec![] }
88 mut f: impl FnMut(&PatternTypeProjection<'tcx>) -> PatternTypeProjection<'tcx>)
91 PatternTypeProjections {
92 contents: self.contents
94 .map(|(proj, span)| (f(proj), *span))
98 pub(crate) fn index(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.index()) }
100 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
101 self.map_projs(|pat_ty_proj| pat_ty_proj.subslice(from, to))
104 pub(crate) fn deref(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.deref()) }
106 pub(crate) fn leaf(&self, field: Field) -> Self {
107 self.map_projs(|pat_ty_proj| pat_ty_proj.leaf(field))
110 pub(crate) fn variant(&self,
111 adt_def: &'tcx AdtDef,
112 variant_index: VariantIdx,
113 field: Field) -> Self {
114 self.map_projs(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
117 pub(crate) fn add_user_type(&self, user_ty: &PatternTypeProjection<'tcx>, sp: Span) -> Self {
118 let mut new = self.clone();
119 new.contents.push((user_ty.clone(), sp));
124 #[derive(Clone, Debug)]
125 pub struct PatternTypeProjection<'tcx> {
126 pub base: CanonicalUserTypeAnnotation<'tcx>,
127 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
130 impl<'tcx> PatternTypeProjection<'tcx> {
131 pub(crate) fn index(&self) -> Self {
132 let mut new = self.clone();
133 new.projs.push(ProjectionElem::Index(()));
137 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
138 let mut new = self.clone();
139 new.projs.push(ProjectionElem::Subslice { from, to });
143 pub(crate) fn deref(&self) -> Self {
144 let mut new = self.clone();
145 new.projs.push(ProjectionElem::Deref);
149 pub(crate) fn leaf(&self, field: Field) -> Self {
150 let mut new = self.clone();
151 new.projs.push(ProjectionElem::Field(field, ()));
155 pub(crate) fn variant(&self,
156 adt_def: &'tcx AdtDef,
157 variant_index: VariantIdx,
158 field: Field) -> Self {
159 let mut new = self.clone();
160 new.projs.push(ProjectionElem::Downcast(adt_def, variant_index));
161 new.projs.push(ProjectionElem::Field(field, ()));
165 pub(crate) fn from_user_type(user_annotation: CanonicalUserTypeAnnotation<'tcx>) -> Self {
167 base: user_annotation,
172 pub(crate) fn user_ty(
174 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
176 ) -> UserTypeProjection<'tcx> {
177 let annotation_index = annotations.push((span, self.base));
179 base: annotation_index,
185 #[derive(Clone, Debug)]
186 pub enum PatternKind<'tcx> {
190 user_ty: PatternTypeProjection<'tcx>,
191 subpattern: Pattern<'tcx>,
195 /// x, ref x, x @ P, etc
197 mutability: Mutability,
199 mode: BindingMode<'tcx>,
202 subpattern: Option<Pattern<'tcx>>,
205 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
207 adt_def: &'tcx AdtDef,
208 substs: &'tcx Substs<'tcx>,
209 variant_index: VariantIdx,
210 subpatterns: Vec<FieldPattern<'tcx>>,
213 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
215 subpatterns: Vec<FieldPattern<'tcx>>,
218 /// box P, &P, &mut P, etc
220 subpattern: Pattern<'tcx>,
224 value: &'tcx ty::Const<'tcx>,
227 Range(PatternRange<'tcx>),
229 /// matches against a slice, checking the length and extracting elements.
230 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
231 /// e.g., `&[ref xs..]`.
233 prefix: Vec<Pattern<'tcx>>,
234 slice: Option<Pattern<'tcx>>,
235 suffix: Vec<Pattern<'tcx>>,
238 /// fixed match against an array, irrefutable
240 prefix: Vec<Pattern<'tcx>>,
241 slice: Option<Pattern<'tcx>>,
242 suffix: Vec<Pattern<'tcx>>,
246 #[derive(Clone, Copy, Debug, PartialEq)]
247 pub struct PatternRange<'tcx> {
248 pub lo: &'tcx ty::Const<'tcx>,
249 pub hi: &'tcx ty::Const<'tcx>,
254 impl<'tcx> fmt::Display for Pattern<'tcx> {
255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257 PatternKind::Wild => write!(f, "_"),
258 PatternKind::AscribeUserType { ref subpattern, .. } =>
259 write!(f, "{}: _", subpattern),
260 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
261 let is_mut = match mode {
262 BindingMode::ByValue => mutability == Mutability::Mut,
263 BindingMode::ByRef(_, bk) => {
265 match bk { BorrowKind::Mut { .. } => true, _ => false }
271 write!(f, "{}", name)?;
272 if let Some(ref subpattern) = *subpattern {
273 write!(f, " @ {}", subpattern)?;
277 PatternKind::Variant { ref subpatterns, .. } |
278 PatternKind::Leaf { ref subpatterns } => {
279 let variant = match *self.kind {
280 PatternKind::Variant { adt_def, variant_index, .. } => {
281 Some(&adt_def.variants[variant_index])
283 _ => if let ty::Adt(adt, _) = self.ty.sty {
285 Some(&adt.variants[VariantIdx::new(0)])
294 let mut first = true;
295 let mut start_or_continue = || if first { first = false; "" } else { ", " };
297 if let Some(variant) = variant {
298 write!(f, "{}", variant.ident)?;
300 // Only for Adt we can have `S {...}`,
301 // which we handle separately here.
302 if variant.ctor_kind == CtorKind::Fictive {
306 for p in subpatterns {
307 if let PatternKind::Wild = *p.pattern.kind {
310 let name = variant.fields[p.field.index()].ident;
311 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
315 if printed < variant.fields.len() {
316 write!(f, "{}..", start_or_continue())?;
319 return write!(f, " }}");
323 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
324 if num_fields != 0 || variant.is_none() {
326 for i in 0..num_fields {
327 write!(f, "{}", start_or_continue())?;
329 // Common case: the field is where we expect it.
330 if let Some(p) = subpatterns.get(i) {
331 if p.field.index() == i {
332 write!(f, "{}", p.pattern)?;
337 // Otherwise, we have to go looking for it.
338 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
339 write!(f, "{}", p.pattern)?;
349 PatternKind::Deref { ref subpattern } => {
351 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
352 ty::Ref(_, _, mutbl) => {
354 if mutbl == hir::MutMutable {
358 _ => bug!("{} is a bad Deref pattern type", self.ty)
360 write!(f, "{}", subpattern)
362 PatternKind::Constant { value } => {
363 fmt_const_val(f, value)
365 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
366 fmt_const_val(f, lo)?;
368 RangeEnd::Included => write!(f, "..=")?,
369 RangeEnd::Excluded => write!(f, "..")?,
373 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
374 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
375 let mut first = true;
376 let mut start_or_continue = || if first { first = false; "" } else { ", " };
379 write!(f, "{}{}", start_or_continue(), p)?;
381 if let Some(ref slice) = *slice {
382 write!(f, "{}", start_or_continue())?;
384 PatternKind::Wild => {}
385 _ => write!(f, "{}", slice)?
390 write!(f, "{}{}", start_or_continue(), p)?;
398 pub struct PatternContext<'a, 'tcx: 'a> {
399 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
400 pub param_env: ty::ParamEnv<'tcx>,
401 pub tables: &'a ty::TypeckTables<'tcx>,
402 pub substs: &'tcx Substs<'tcx>,
403 pub errors: Vec<PatternError>,
406 impl<'a, 'tcx> Pattern<'tcx> {
407 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
408 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
409 tables: &'a ty::TypeckTables<'tcx>,
410 pat: &'tcx hir::Pat) -> Self {
411 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
412 let result = pcx.lower_pattern(pat);
413 if !pcx.errors.is_empty() {
414 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
415 tcx.sess.delay_span_bug(pat.span, &msg);
417 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
422 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
423 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
424 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
425 tables: &'a ty::TypeckTables<'tcx>) -> Self {
428 param_env: param_env_and_substs.param_env,
430 substs: param_env_and_substs.value,
435 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
436 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
437 // pattern has the type that results *after* dereferencing. For example, in this code:
440 // match &&Some(0i32) {
441 // Some(n) => { ... },
446 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
447 // determined in rustc_typeck::check::match). The adjustments would be
449 // `vec![&&Option<i32>, &Option<i32>]`.
451 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
452 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
453 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
454 // gets the least-dereferenced type).
455 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
462 .fold(unadjusted_pat, |pat, ref_ty| {
463 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
467 kind: Box::new(PatternKind::Deref { subpattern: pat }),
473 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
474 let mut ty = self.tables.node_id_to_type(pat.hir_id);
476 let kind = match pat.node {
477 PatKind::Wild => PatternKind::Wild,
479 PatKind::Lit(ref value) => self.lower_lit(value),
481 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
482 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
483 (PatternKind::Constant { value: lo },
484 PatternKind::Constant { value: hi }) => {
485 use std::cmp::Ordering;
486 let cmp = compare_const_vals(
490 self.param_env.and(ty),
493 (RangeEnd::Excluded, Some(Ordering::Less)) =>
494 PatternKind::Range(PatternRange { lo, hi, ty, end }),
495 (RangeEnd::Excluded, _) => {
500 "lower range bound must be less than upper",
504 (RangeEnd::Included, Some(Ordering::Equal)) => {
505 PatternKind::Constant { value: lo }
507 (RangeEnd::Included, Some(Ordering::Less)) => {
508 PatternKind::Range(PatternRange { lo, hi, ty, end })
510 (RangeEnd::Included, _) => {
511 let mut err = struct_span_err!(
515 "lower range bound must be less than or equal to upper"
519 "lower bound larger than upper bound",
521 if self.tcx.sess.teach(&err.get_code().unwrap()) {
522 err.note("When matching against a range, the compiler \
523 verifies that the range is non-empty. Range \
524 patterns include both end-points, so this is \
525 equivalent to requiring the start of the range \
526 to be less than or equal to the end of the range.");
533 _ => PatternKind::Wild
537 PatKind::Path(ref qpath) => {
538 return self.lower_path(qpath, pat.hir_id, pat.span);
541 PatKind::Ref(ref subpattern, _) |
542 PatKind::Box(ref subpattern) => {
543 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
546 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
550 subpattern: Pattern {
553 kind: Box::new(self.slice_or_array_pattern(
554 pat.span, ty, prefix, slice, suffix))
559 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
560 ty::Error => { // Avoid ICE
561 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
566 "unexpanded type for vector pattern: {:?}",
571 PatKind::Tuple(ref subpatterns, ddpos) => {
573 ty::Tuple(ref tys) => {
576 .enumerate_and_adjust(tys.len(), ddpos)
577 .map(|(i, subpattern)| FieldPattern {
578 field: Field::new(i),
579 pattern: self.lower_pattern(subpattern)
583 PatternKind::Leaf { subpatterns }
585 ty::Error => { // Avoid ICE (#50577)
586 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
588 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
592 PatKind::Binding(_, id, ident, ref sub) => {
593 let var_ty = self.tables.node_id_to_type(pat.hir_id);
594 let region = match var_ty.sty {
595 ty::Ref(r, _, _) => Some(r),
596 ty::Error => { // Avoid ICE
597 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
601 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
602 .expect("missing binding mode");
603 let (mutability, mode) = match bm {
604 ty::BindByValue(hir::MutMutable) =>
605 (Mutability::Mut, BindingMode::ByValue),
606 ty::BindByValue(hir::MutImmutable) =>
607 (Mutability::Not, BindingMode::ByValue),
608 ty::BindByReference(hir::MutMutable) =>
609 (Mutability::Not, BindingMode::ByRef(
610 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
611 ty::BindByReference(hir::MutImmutable) =>
612 (Mutability::Not, BindingMode::ByRef(
613 region.unwrap(), BorrowKind::Shared)),
616 // A ref x pattern is the same node used for x, and as such it has
617 // x's type, which is &T, where we want T (the type being matched).
618 if let ty::BindByReference(_) = bm {
619 if let ty::Ref(_, rty, _) = ty.sty {
622 bug!("`ref {}` has wrong type {}", ident, ty);
626 PatternKind::Binding {
632 subpattern: self.lower_opt_pattern(sub),
636 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
637 let def = self.tables.qpath_def(qpath, pat.hir_id);
638 let adt_def = match ty.sty {
639 ty::Adt(adt_def, _) => adt_def,
640 ty::Error => { // Avoid ICE (#50585)
641 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
643 _ => span_bug!(pat.span,
644 "tuple struct pattern not applied to an ADT {:?}",
647 let variant_def = adt_def.variant_of_def(def);
651 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
652 .map(|(i, field)| FieldPattern {
653 field: Field::new(i),
654 pattern: self.lower_pattern(field),
658 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
661 PatKind::Struct(ref qpath, ref fields, _) => {
662 let def = self.tables.qpath_def(qpath, pat.hir_id);
667 field: Field::new(self.tcx.field_index(field.node.id,
669 pattern: self.lower_pattern(&field.node.pat),
674 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
681 kind: Box::new(kind),
685 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
686 pats.iter().map(|p| self.lower_pattern(p)).collect()
689 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
691 pat.as_ref().map(|p| self.lower_pattern(p))
694 fn flatten_nested_slice_patterns(
696 prefix: Vec<Pattern<'tcx>>,
697 slice: Option<Pattern<'tcx>>,
698 suffix: Vec<Pattern<'tcx>>)
699 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
701 let orig_slice = match slice {
702 Some(orig_slice) => orig_slice,
703 None => return (prefix, slice, suffix)
705 let orig_prefix = prefix;
706 let orig_suffix = suffix;
708 // dance because of intentional borrow-checker stupidity.
709 let kind = *orig_slice.kind;
711 PatternKind::Slice { prefix, slice, mut suffix } |
712 PatternKind::Array { prefix, slice, mut suffix } => {
713 let mut orig_prefix = orig_prefix;
715 orig_prefix.extend(prefix);
716 suffix.extend(orig_suffix);
718 (orig_prefix, slice, suffix)
721 (orig_prefix, Some(Pattern {
722 kind: box kind, ..orig_slice
728 fn slice_or_array_pattern(
732 prefix: &'tcx [P<hir::Pat>],
733 slice: &'tcx Option<P<hir::Pat>>,
734 suffix: &'tcx [P<hir::Pat>])
737 let prefix = self.lower_patterns(prefix);
738 let slice = self.lower_opt_pattern(slice);
739 let suffix = self.lower_patterns(suffix);
740 let (prefix, slice, suffix) =
741 self.flatten_nested_slice_patterns(prefix, slice, suffix);
745 // matching a slice or fixed-length array
746 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
749 ty::Array(_, len) => {
750 // fixed-length array
751 let len = len.unwrap_usize(self.tcx);
752 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
753 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
757 span_bug!(span, "bad slice pattern type {:?}", ty);
762 fn lower_variant_or_leaf(
768 subpatterns: Vec<FieldPattern<'tcx>>,
769 ) -> PatternKind<'tcx> {
770 let mut kind = match def {
771 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
772 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
773 let adt_def = self.tcx.adt_def(enum_id);
774 if adt_def.is_enum() {
775 let substs = match ty.sty {
777 ty::FnDef(_, substs) => substs,
778 ty::Error => { // Avoid ICE (#50585)
779 return PatternKind::Wild;
781 _ => bug!("inappropriate type for def: {:?}", ty.sty),
783 PatternKind::Variant {
786 variant_index: adt_def.variant_index_with_id(variant_id),
790 PatternKind::Leaf { subpatterns }
794 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
795 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
796 PatternKind::Leaf { subpatterns }
800 self.errors.push(PatternError::NonConstPath(span));
805 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
806 debug!("lower_variant_or_leaf: user_ty={:?} span={:?}", user_ty, span);
807 kind = PatternKind::AscribeUserType {
808 subpattern: Pattern {
811 kind: Box::new(kind),
813 user_ty: PatternTypeProjection::from_user_type(user_ty),
821 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
822 /// it to `const_to_pat`. Any other path (like enum variants without fields)
823 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
824 fn lower_path(&mut self,
829 let ty = self.tables.node_id_to_type(id);
830 let def = self.tables.qpath_def(qpath, id);
831 let is_associated_const = match def {
832 Def::AssociatedConst(_) => true,
835 let kind = match def {
836 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
837 let substs = self.tables.node_substs(id);
838 match ty::Instance::resolve(
849 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
851 return self.const_to_pat(instance, value, id, span)
854 self.tcx.sess.span_err(
856 "could not evaluate constant pattern",
863 self.errors.push(if is_associated_const {
864 PatternError::AssociatedConstInPattern(span)
866 PatternError::StaticInPattern(span)
872 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
878 kind: Box::new(kind),
882 /// Converts literals, paths and negation of literals to patterns.
883 /// The special case for negation exists to allow things like -128i8
884 /// which would overflow if we tried to evaluate 128i8 and then negate
886 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
888 hir::ExprKind::Lit(ref lit) => {
889 let ty = self.tables.expr_ty(expr);
890 match lit_to_const(&lit.node, self.tcx, ty, false) {
892 let instance = ty::Instance::new(
893 self.tables.local_id_root.expect("literal outside any scope"),
896 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
898 Err(LitToConstError::UnparseableFloat) => {
899 self.errors.push(PatternError::FloatBug);
902 Err(LitToConstError::Reported) => PatternKind::Wild,
905 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
906 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
907 let ty = self.tables.expr_ty(expr);
908 let lit = match expr.node {
909 hir::ExprKind::Lit(ref lit) => lit,
910 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
912 match lit_to_const(&lit.node, self.tcx, ty, true) {
914 let instance = ty::Instance::new(
915 self.tables.local_id_root.expect("literal outside any scope"),
918 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
920 Err(LitToConstError::UnparseableFloat) => {
921 self.errors.push(PatternError::FloatBug);
924 Err(LitToConstError::Reported) => PatternKind::Wild,
927 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
931 /// Converts an evaluated constant to a pattern (if possible).
932 /// This means aggregate values (like structs and enums) are converted
933 /// to a pattern that matches the value (as if you'd compare via eq).
936 instance: ty::Instance<'tcx>,
937 cv: &'tcx ty::Const<'tcx>,
941 debug!("const_to_pat: cv={:#?}", cv);
942 let adt_subpattern = |i, variant_opt| {
943 let field = Field::new(i);
944 let val = const_field(
945 self.tcx, self.param_env, instance,
946 variant_opt, field, cv,
947 ).expect("field access failed");
948 self.const_to_pat(instance, val, id, span)
950 let adt_subpatterns = |n, variant_opt| {
952 let field = Field::new(i);
955 pattern: adt_subpattern(i, variant_opt),
957 }).collect::<Vec<_>>()
959 let kind = match cv.ty.sty {
961 let id = self.tcx.hir().hir_to_node_id(id);
963 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
966 "floating-point types cannot be used in patterns",
968 PatternKind::Constant {
972 ty::Adt(adt_def, _) if adt_def.is_union() => {
973 // Matching on union fields is unsafe, we can't hide it in constants
974 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
977 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
978 let msg = format!("to use a constant of type `{}` in a pattern, \
979 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
980 self.tcx.item_path_str(adt_def.did),
981 self.tcx.item_path_str(adt_def.did));
982 self.tcx.sess.span_err(span, &msg);
985 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
986 let variant_index = const_variant_index(
987 self.tcx, self.param_env, instance, cv
988 ).expect("const_variant_index failed");
989 let subpatterns = adt_subpatterns(
990 adt_def.variants[variant_index].fields.len(),
993 PatternKind::Variant {
1000 ty::Adt(adt_def, _) => {
1001 let struct_var = adt_def.non_enum_variant();
1003 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1006 ty::Tuple(fields) => {
1008 subpatterns: adt_subpatterns(fields.len(), None),
1011 ty::Array(_, n) => {
1012 PatternKind::Array {
1013 prefix: (0..n.unwrap_usize(self.tcx))
1014 .map(|i| adt_subpattern(i as usize, None))
1021 PatternKind::Constant {
1030 kind: Box::new(kind),
1035 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1036 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1040 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1046 pub trait PatternFoldable<'tcx> : Sized {
1047 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1048 self.super_fold_with(folder)
1051 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1054 pub trait PatternFolder<'tcx> : Sized {
1055 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1056 pattern.super_fold_with(self)
1059 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1060 kind.super_fold_with(self)
1065 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1066 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1067 let content: T = (**self).fold_with(folder);
1072 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1073 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1074 self.iter().map(|t| t.fold_with(folder)).collect()
1078 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1079 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1080 self.as_ref().map(|t| t.fold_with(folder))
1084 macro_rules! CloneImpls {
1085 (<$lt_tcx:tt> $($ty:ty),+) => {
1087 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1088 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1097 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
1098 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
1099 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>,
1100 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1103 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1104 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1106 field: self.field.fold_with(folder),
1107 pattern: self.pattern.fold_with(folder)
1112 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1113 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1114 folder.fold_pattern(self)
1117 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1119 ty: self.ty.fold_with(folder),
1120 span: self.span.fold_with(folder),
1121 kind: self.kind.fold_with(folder)
1126 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1127 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1128 folder.fold_pattern_kind(self)
1131 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1133 PatternKind::Wild => PatternKind::Wild,
1134 PatternKind::AscribeUserType {
1138 } => PatternKind::AscribeUserType {
1139 subpattern: subpattern.fold_with(folder),
1140 user_ty: user_ty.fold_with(folder),
1143 PatternKind::Binding {
1150 } => PatternKind::Binding {
1151 mutability: mutability.fold_with(folder),
1152 name: name.fold_with(folder),
1153 mode: mode.fold_with(folder),
1154 var: var.fold_with(folder),
1155 ty: ty.fold_with(folder),
1156 subpattern: subpattern.fold_with(folder),
1158 PatternKind::Variant {
1163 } => PatternKind::Variant {
1164 adt_def: adt_def.fold_with(folder),
1165 substs: substs.fold_with(folder),
1167 subpatterns: subpatterns.fold_with(folder)
1171 } => PatternKind::Leaf {
1172 subpatterns: subpatterns.fold_with(folder),
1174 PatternKind::Deref {
1176 } => PatternKind::Deref {
1177 subpattern: subpattern.fold_with(folder),
1179 PatternKind::Constant {
1181 } => PatternKind::Constant {
1182 value: value.fold_with(folder)
1184 PatternKind::Range(PatternRange {
1189 }) => PatternKind::Range(PatternRange {
1190 lo: lo.fold_with(folder),
1191 hi: hi.fold_with(folder),
1192 ty: ty.fold_with(folder),
1195 PatternKind::Slice {
1199 } => PatternKind::Slice {
1200 prefix: prefix.fold_with(folder),
1201 slice: slice.fold_with(folder),
1202 suffix: suffix.fold_with(folder)
1204 PatternKind::Array {
1208 } => PatternKind::Array {
1209 prefix: prefix.fold_with(folder),
1210 slice: slice.fold_with(folder),
1211 suffix: suffix.fold_with(folder)
1217 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1218 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1219 a: &'tcx ty::Const<'tcx>,
1220 b: &'tcx ty::Const<'tcx>,
1221 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1222 ) -> Option<Ordering> {
1223 trace!("compare_const_vals: {:?}, {:?}", a, b);
1225 let from_bool = |v: bool| {
1227 Some(Ordering::Equal)
1233 let fallback = || from_bool(a == b);
1235 // Use the fallback if any type differs
1236 if a.ty != b.ty || a.ty != ty.value {
1240 let tcx = tcx.global_tcx();
1241 let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1243 // FIXME: This should use assert_bits(ty) instead of use_bits
1244 // but triggers possibly bugs due to mismatching of arrays and slices
1245 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1246 use ::rustc_apfloat::Float;
1247 return match ty.value.sty {
1248 ty::Float(ast::FloatTy::F32) => {
1249 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1250 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1253 ty::Float(ast::FloatTy::F64) => {
1254 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1255 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1259 let layout = tcx.layout_of(ty).ok()?;
1260 assert!(layout.abi.is_signed());
1261 let a = sign_extend(a, layout.size);
1262 let b = sign_extend(b, layout.size);
1263 Some((a as i128).cmp(&(b as i128)))
1265 _ => Some(a.cmp(&b)),
1269 if let ty::Str = ty.value.sty {
1270 match (a.val, b.val) {
1272 ConstValue::ScalarPair(
1276 ConstValue::ScalarPair(
1280 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1281 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1282 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1284 let map = tcx.alloc_map.lock();
1285 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1286 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1287 if alloc_a.bytes.len() as u128 == len_a {
1288 return from_bool(alloc_a == alloc_b);