1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Code to validate patterns/matches
16 pub use self::check_match::check_crate;
17 pub(crate) use self::check_match::check_match;
19 use const_eval::{const_field, const_variant_index};
21 use hair::util::UserAnnotatedTyHelpers;
22 use hair::constant::*;
24 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
25 use rustc::mir::{ProjectionElem, UserTypeAnnotation, UserTypeProjection, UserTypeProjections};
26 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
27 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty};
28 use rustc::ty::subst::{Substs, Kind};
29 use rustc::ty::layout::VariantIdx;
30 use rustc::hir::{self, PatKind, RangeEnd};
31 use rustc::hir::def::{Def, CtorKind};
32 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
34 use rustc_data_structures::indexed_vec::Idx;
36 use std::cmp::Ordering;
42 #[derive(Clone, Debug)]
43 pub enum PatternError {
44 AssociatedConstInPattern(Span),
45 StaticInPattern(Span),
50 #[derive(Copy, Clone, Debug)]
51 pub enum BindingMode<'tcx> {
53 ByRef(Region<'tcx>, BorrowKind),
56 #[derive(Clone, Debug)]
57 pub struct FieldPattern<'tcx> {
59 pub pattern: Pattern<'tcx>,
62 #[derive(Clone, Debug)]
63 pub struct Pattern<'tcx> {
66 pub kind: Box<PatternKind<'tcx>>,
70 #[derive(Clone, Debug)]
71 pub(crate) struct PatternTypeProjections<'tcx> {
72 contents: Vec<(PatternTypeProjection<'tcx>, Span)>,
75 impl<'tcx> PatternTypeProjections<'tcx> {
76 pub(crate) fn user_ty(self) -> UserTypeProjections<'tcx> {
77 UserTypeProjections::from_projections(
78 self.contents.into_iter().map(|(pat_ty_proj, span)| (pat_ty_proj.user_ty(), span)))
81 pub(crate) fn none() -> Self {
82 PatternTypeProjections { contents: vec![] }
85 pub(crate) fn ref_binding(&self) -> Self {
86 // FIXME(#47184): ignore for now
87 PatternTypeProjections { contents: vec![] }
91 mut f: impl FnMut(&PatternTypeProjection<'tcx>) -> PatternTypeProjection<'tcx>)
94 PatternTypeProjections {
95 contents: self.contents
97 .map(|(proj, span)| (f(proj), *span))
101 pub(crate) fn index(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.index()) }
103 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
104 self.map_projs(|pat_ty_proj| pat_ty_proj.subslice(from, to))
107 pub(crate) fn deref(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.deref()) }
109 pub(crate) fn leaf(&self, field: Field) -> Self {
110 self.map_projs(|pat_ty_proj| pat_ty_proj.leaf(field))
113 pub(crate) fn variant(&self,
114 adt_def: &'tcx AdtDef,
115 variant_index: VariantIdx,
116 field: Field) -> Self {
117 self.map_projs(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
120 pub(crate) fn add_user_type(&self, user_ty: &PatternTypeProjection<'tcx>, sp: Span) -> Self {
121 let mut new = self.clone();
122 new.contents.push((user_ty.clone(), sp));
127 #[derive(Clone, Debug)]
128 pub struct PatternTypeProjection<'tcx>(UserTypeProjection<'tcx>);
130 impl<'tcx> PatternTypeProjection<'tcx> {
131 pub(crate) fn index(&self) -> Self {
132 let mut new = self.clone();
133 new.0.projs.push(ProjectionElem::Index(()));
137 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
138 let mut new = self.clone();
139 new.0.projs.push(ProjectionElem::Subslice { from, to });
143 pub(crate) fn deref(&self) -> Self {
144 let mut new = self.clone();
145 new.0.projs.push(ProjectionElem::Deref);
149 pub(crate) fn leaf(&self, field: Field) -> Self {
150 let mut new = self.clone();
151 new.0.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.0.projs.push(ProjectionElem::Downcast(adt_def, variant_index));
161 new.0.projs.push(ProjectionElem::Field(field, ()));
165 pub(crate) fn from_canonical_ty(c_ty: ty::CanonicalTy<'tcx>) -> Self {
166 Self::from_user_type(UserTypeAnnotation::Ty(c_ty))
169 pub(crate) fn from_user_type(u_ty: UserTypeAnnotation<'tcx>) -> Self {
170 Self::from_user_type_proj(UserTypeProjection { base: u_ty, projs: vec![], })
173 pub(crate) fn from_user_type_proj(u_ty: UserTypeProjection<'tcx>) -> Self {
174 PatternTypeProjection(u_ty)
177 pub(crate) fn user_ty(self) -> UserTypeProjection<'tcx> { self.0 }
180 #[derive(Clone, Debug)]
181 pub enum PatternKind<'tcx> {
185 user_ty: PatternTypeProjection<'tcx>,
186 subpattern: Pattern<'tcx>,
190 /// x, ref x, x @ P, etc
192 mutability: Mutability,
194 mode: BindingMode<'tcx>,
197 subpattern: Option<Pattern<'tcx>>,
200 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
202 adt_def: &'tcx AdtDef,
203 substs: &'tcx Substs<'tcx>,
204 variant_index: VariantIdx,
205 subpatterns: Vec<FieldPattern<'tcx>>,
208 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
210 subpatterns: Vec<FieldPattern<'tcx>>,
213 /// box P, &P, &mut P, etc
215 subpattern: Pattern<'tcx>,
219 value: &'tcx ty::Const<'tcx>,
223 lo: &'tcx ty::Const<'tcx>,
224 hi: &'tcx ty::Const<'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 impl<'tcx> fmt::Display for Pattern<'tcx> {
247 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
249 PatternKind::Wild => write!(f, "_"),
250 PatternKind::AscribeUserType { ref subpattern, .. } =>
251 write!(f, "{}: _", subpattern),
252 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
253 let is_mut = match mode {
254 BindingMode::ByValue => mutability == Mutability::Mut,
255 BindingMode::ByRef(_, bk) => {
257 match bk { BorrowKind::Mut { .. } => true, _ => false }
263 write!(f, "{}", name)?;
264 if let Some(ref subpattern) = *subpattern {
265 write!(f, " @ {}", subpattern)?;
269 PatternKind::Variant { ref subpatterns, .. } |
270 PatternKind::Leaf { ref subpatterns } => {
271 let variant = match *self.kind {
272 PatternKind::Variant { adt_def, variant_index, .. } => {
273 Some(&adt_def.variants[variant_index])
275 _ => if let ty::Adt(adt, _) = self.ty.sty {
277 Some(&adt.variants[VariantIdx::new(0)])
286 let mut first = true;
287 let mut start_or_continue = || if first { first = false; "" } else { ", " };
289 if let Some(variant) = variant {
290 write!(f, "{}", variant.name)?;
292 // Only for Adt we can have `S {...}`,
293 // which we handle separately here.
294 if variant.ctor_kind == CtorKind::Fictive {
298 for p in subpatterns {
299 if let PatternKind::Wild = *p.pattern.kind {
302 let name = variant.fields[p.field.index()].ident;
303 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
307 if printed < variant.fields.len() {
308 write!(f, "{}..", start_or_continue())?;
311 return write!(f, " }}");
315 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
316 if num_fields != 0 || variant.is_none() {
318 for i in 0..num_fields {
319 write!(f, "{}", start_or_continue())?;
321 // Common case: the field is where we expect it.
322 if let Some(p) = subpatterns.get(i) {
323 if p.field.index() == i {
324 write!(f, "{}", p.pattern)?;
329 // Otherwise, we have to go looking for it.
330 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
331 write!(f, "{}", p.pattern)?;
341 PatternKind::Deref { ref subpattern } => {
343 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
344 ty::Ref(_, _, mutbl) => {
346 if mutbl == hir::MutMutable {
350 _ => bug!("{} is a bad Deref pattern type", self.ty)
352 write!(f, "{}", subpattern)
354 PatternKind::Constant { value } => {
355 fmt_const_val(f, value)
357 PatternKind::Range { lo, hi, ty: _, end } => {
358 fmt_const_val(f, lo)?;
360 RangeEnd::Included => write!(f, "..=")?,
361 RangeEnd::Excluded => write!(f, "..")?,
365 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
366 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
367 let mut first = true;
368 let mut start_or_continue = || if first { first = false; "" } else { ", " };
371 write!(f, "{}{}", start_or_continue(), p)?;
373 if let Some(ref slice) = *slice {
374 write!(f, "{}", start_or_continue())?;
376 PatternKind::Wild => {}
377 _ => write!(f, "{}", slice)?
382 write!(f, "{}{}", start_or_continue(), p)?;
390 pub struct PatternContext<'a, 'tcx: 'a> {
391 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
392 pub param_env: ty::ParamEnv<'tcx>,
393 pub tables: &'a ty::TypeckTables<'tcx>,
394 pub substs: &'tcx Substs<'tcx>,
395 pub errors: Vec<PatternError>,
398 impl<'a, 'tcx> Pattern<'tcx> {
399 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
400 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
401 tables: &'a ty::TypeckTables<'tcx>,
402 pat: &'tcx hir::Pat) -> Self {
403 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
404 let result = pcx.lower_pattern(pat);
405 if !pcx.errors.is_empty() {
406 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
407 tcx.sess.delay_span_bug(pat.span, &msg);
409 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
414 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
415 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
416 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
417 tables: &'a ty::TypeckTables<'tcx>) -> Self {
420 param_env: param_env_and_substs.param_env,
422 substs: param_env_and_substs.value,
427 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
428 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
429 // pattern has the type that results *after* dereferencing. For example, in this code:
432 // match &&Some(0i32) {
433 // Some(n) => { ... },
438 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
439 // determined in rustc_typeck::check::match). The adjustments would be
441 // `vec![&&Option<i32>, &Option<i32>]`.
443 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
444 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
445 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
446 // gets the least-dereferenced type).
447 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
454 .fold(unadjusted_pat, |pat, ref_ty| {
455 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
459 kind: Box::new(PatternKind::Deref { subpattern: pat }),
465 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
466 let mut ty = self.tables.node_id_to_type(pat.hir_id);
468 let kind = match pat.node {
469 PatKind::Wild => PatternKind::Wild,
471 PatKind::Lit(ref value) => self.lower_lit(value),
473 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
474 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
475 (PatternKind::Constant { value: lo },
476 PatternKind::Constant { value: hi }) => {
477 use std::cmp::Ordering;
478 let cmp = compare_const_vals(
482 self.param_env.and(ty),
485 (RangeEnd::Excluded, Some(Ordering::Less)) =>
486 PatternKind::Range { lo, hi, ty, end },
487 (RangeEnd::Excluded, _) => {
492 "lower range bound must be less than upper",
496 (RangeEnd::Included, Some(Ordering::Equal)) => {
497 PatternKind::Constant { value: lo }
499 (RangeEnd::Included, Some(Ordering::Less)) => {
500 PatternKind::Range { lo, hi, ty, end }
502 (RangeEnd::Included, _) => {
503 let mut err = struct_span_err!(
507 "lower range bound must be less than or equal to upper"
511 "lower bound larger than upper bound",
513 if self.tcx.sess.teach(&err.get_code().unwrap()) {
514 err.note("When matching against a range, the compiler \
515 verifies that the range is non-empty. Range \
516 patterns include both end-points, so this is \
517 equivalent to requiring the start of the range \
518 to be less than or equal to the end of the range.");
525 _ => PatternKind::Wild
529 PatKind::Path(ref qpath) => {
530 return self.lower_path(qpath, pat.hir_id, pat.span);
533 PatKind::Ref(ref subpattern, _) |
534 PatKind::Box(ref subpattern) => {
535 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
538 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
542 subpattern: Pattern {
545 kind: Box::new(self.slice_or_array_pattern(
546 pat.span, ty, prefix, slice, suffix))
551 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
552 ty::Error => { // Avoid ICE
553 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
558 "unexpanded type for vector pattern: {:?}",
563 PatKind::Tuple(ref subpatterns, ddpos) => {
565 ty::Tuple(ref tys) => {
568 .enumerate_and_adjust(tys.len(), ddpos)
569 .map(|(i, subpattern)| FieldPattern {
570 field: Field::new(i),
571 pattern: self.lower_pattern(subpattern)
575 PatternKind::Leaf { subpatterns }
577 ty::Error => { // Avoid ICE (#50577)
578 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
580 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
584 PatKind::Binding(_, id, ident, ref sub) => {
585 let var_ty = self.tables.node_id_to_type(pat.hir_id);
586 let region = match var_ty.sty {
587 ty::Ref(r, _, _) => Some(r),
588 ty::Error => { // Avoid ICE
589 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
593 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
594 .expect("missing binding mode");
595 let (mutability, mode) = match bm {
596 ty::BindByValue(hir::MutMutable) =>
597 (Mutability::Mut, BindingMode::ByValue),
598 ty::BindByValue(hir::MutImmutable) =>
599 (Mutability::Not, BindingMode::ByValue),
600 ty::BindByReference(hir::MutMutable) =>
601 (Mutability::Not, BindingMode::ByRef(
602 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
603 ty::BindByReference(hir::MutImmutable) =>
604 (Mutability::Not, BindingMode::ByRef(
605 region.unwrap(), BorrowKind::Shared)),
608 // A ref x pattern is the same node used for x, and as such it has
609 // x's type, which is &T, where we want T (the type being matched).
610 if let ty::BindByReference(_) = bm {
611 if let ty::Ref(_, rty, _) = ty.sty {
614 bug!("`ref {}` has wrong type {}", ident, ty);
618 PatternKind::Binding {
624 subpattern: self.lower_opt_pattern(sub),
628 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
629 let def = self.tables.qpath_def(qpath, pat.hir_id);
630 let adt_def = match ty.sty {
631 ty::Adt(adt_def, _) => adt_def,
632 ty::Error => { // Avoid ICE (#50585)
633 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
635 _ => span_bug!(pat.span,
636 "tuple struct pattern not applied to an ADT {:?}",
639 let variant_def = adt_def.variant_of_def(def);
643 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
644 .map(|(i, field)| FieldPattern {
645 field: Field::new(i),
646 pattern: self.lower_pattern(field),
650 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
653 PatKind::Struct(ref qpath, ref fields, _) => {
654 let def = self.tables.qpath_def(qpath, pat.hir_id);
659 field: Field::new(self.tcx.field_index(field.node.id,
661 pattern: self.lower_pattern(&field.node.pat),
666 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
673 kind: Box::new(kind),
677 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
678 pats.iter().map(|p| self.lower_pattern(p)).collect()
681 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
683 pat.as_ref().map(|p| self.lower_pattern(p))
686 fn flatten_nested_slice_patterns(
688 prefix: Vec<Pattern<'tcx>>,
689 slice: Option<Pattern<'tcx>>,
690 suffix: Vec<Pattern<'tcx>>)
691 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
693 let orig_slice = match slice {
694 Some(orig_slice) => orig_slice,
695 None => return (prefix, slice, suffix)
697 let orig_prefix = prefix;
698 let orig_suffix = suffix;
700 // dance because of intentional borrow-checker stupidity.
701 let kind = *orig_slice.kind;
703 PatternKind::Slice { prefix, slice, mut suffix } |
704 PatternKind::Array { prefix, slice, mut suffix } => {
705 let mut orig_prefix = orig_prefix;
707 orig_prefix.extend(prefix);
708 suffix.extend(orig_suffix);
710 (orig_prefix, slice, suffix)
713 (orig_prefix, Some(Pattern {
714 kind: box kind, ..orig_slice
720 fn slice_or_array_pattern(
724 prefix: &'tcx [P<hir::Pat>],
725 slice: &'tcx Option<P<hir::Pat>>,
726 suffix: &'tcx [P<hir::Pat>])
729 let prefix = self.lower_patterns(prefix);
730 let slice = self.lower_opt_pattern(slice);
731 let suffix = self.lower_patterns(suffix);
732 let (prefix, slice, suffix) =
733 self.flatten_nested_slice_patterns(prefix, slice, suffix);
737 // matching a slice or fixed-length array
738 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
741 ty::Array(_, len) => {
742 // fixed-length array
743 let len = len.unwrap_usize(self.tcx);
744 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
745 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
749 span_bug!(span, "bad slice pattern type {:?}", ty);
754 fn lower_variant_or_leaf(
760 subpatterns: Vec<FieldPattern<'tcx>>,
761 ) -> PatternKind<'tcx> {
762 let mut kind = match def {
763 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
764 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
765 let adt_def = self.tcx.adt_def(enum_id);
766 if adt_def.is_enum() {
767 let substs = match ty.sty {
769 ty::FnDef(_, substs) => substs,
770 ty::Error => { // Avoid ICE (#50585)
771 return PatternKind::Wild;
773 _ => bug!("inappropriate type for def: {:?}", ty.sty),
775 PatternKind::Variant {
778 variant_index: adt_def.variant_index_with_id(variant_id),
782 PatternKind::Leaf { subpatterns }
786 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
787 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
788 PatternKind::Leaf { subpatterns }
792 self.errors.push(PatternError::NonConstPath(span));
797 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
798 let subpattern = Pattern {
801 kind: Box::new(kind),
804 debug!("pattern user_ty = {:?} for pattern at {:?}", user_ty, span);
806 let pat_ty = PatternTypeProjection::from_user_type(user_ty);
807 kind = PatternKind::AscribeUserType {
817 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
818 /// it to `const_to_pat`. Any other path (like enum variants without fields)
819 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
820 fn lower_path(&mut self,
825 let ty = self.tables.node_id_to_type(id);
826 let def = self.tables.qpath_def(qpath, id);
827 let is_associated_const = match def {
828 Def::AssociatedConst(_) => true,
831 let kind = match def {
832 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
833 let substs = self.tables.node_substs(id);
834 match ty::Instance::resolve(
845 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
847 return self.const_to_pat(instance, value, id, span)
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 -128i8
880 /// which would overflow if we tried to evaluate 128i8 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 compare via eq).
932 instance: ty::Instance<'tcx>,
933 cv: &'tcx ty::Const<'tcx>,
937 debug!("const_to_pat: cv={:#?}", cv);
938 let adt_subpattern = |i, variant_opt| {
939 let field = Field::new(i);
940 let val = const_field(
941 self.tcx, self.param_env, instance,
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 let kind = match cv.ty.sty {
957 let id = self.tcx.hir().hir_to_node_id(id);
959 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
962 "floating-point types cannot be used in patterns",
964 PatternKind::Constant {
968 ty::Adt(adt_def, _) if adt_def.is_union() => {
969 // Matching on union fields is unsafe, we can't hide it in constants
970 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
973 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
974 let msg = format!("to use a constant of type `{}` in a pattern, \
975 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
976 self.tcx.item_path_str(adt_def.did),
977 self.tcx.item_path_str(adt_def.did));
978 self.tcx.sess.span_err(span, &msg);
981 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
982 let variant_index = const_variant_index(
983 self.tcx, self.param_env, instance, cv
984 ).expect("const_variant_index failed");
985 let subpatterns = adt_subpatterns(
986 adt_def.variants[variant_index].fields.len(),
989 PatternKind::Variant {
996 ty::Adt(adt_def, _) => {
997 let struct_var = adt_def.non_enum_variant();
999 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1002 ty::Tuple(fields) => {
1004 subpatterns: adt_subpatterns(fields.len(), None),
1007 ty::Array(_, n) => {
1008 PatternKind::Array {
1009 prefix: (0..n.unwrap_usize(self.tcx))
1010 .map(|i| adt_subpattern(i as usize, None))
1017 PatternKind::Constant {
1026 kind: Box::new(kind),
1031 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1032 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1036 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1042 pub trait PatternFoldable<'tcx> : Sized {
1043 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1044 self.super_fold_with(folder)
1047 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1050 pub trait PatternFolder<'tcx> : Sized {
1051 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1052 pattern.super_fold_with(self)
1055 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1056 kind.super_fold_with(self)
1061 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1062 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1063 let content: T = (**self).fold_with(folder);
1068 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1069 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1070 self.iter().map(|t| t.fold_with(folder)).collect()
1074 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1075 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1076 self.as_ref().map(|t| t.fold_with(folder))
1080 macro_rules! CloneImpls {
1081 (<$lt_tcx:tt> $($ty:ty),+) => {
1083 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1084 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1093 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
1094 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
1095 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>,
1096 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1099 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1100 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1102 field: self.field.fold_with(folder),
1103 pattern: self.pattern.fold_with(folder)
1108 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1109 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1110 folder.fold_pattern(self)
1113 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1115 ty: self.ty.fold_with(folder),
1116 span: self.span.fold_with(folder),
1117 kind: self.kind.fold_with(folder)
1122 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1123 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1124 folder.fold_pattern_kind(self)
1127 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1129 PatternKind::Wild => PatternKind::Wild,
1130 PatternKind::AscribeUserType {
1134 } => PatternKind::AscribeUserType {
1135 subpattern: subpattern.fold_with(folder),
1136 user_ty: user_ty.fold_with(folder),
1139 PatternKind::Binding {
1146 } => PatternKind::Binding {
1147 mutability: mutability.fold_with(folder),
1148 name: name.fold_with(folder),
1149 mode: mode.fold_with(folder),
1150 var: var.fold_with(folder),
1151 ty: ty.fold_with(folder),
1152 subpattern: subpattern.fold_with(folder),
1154 PatternKind::Variant {
1159 } => PatternKind::Variant {
1160 adt_def: adt_def.fold_with(folder),
1161 substs: substs.fold_with(folder),
1163 subpatterns: subpatterns.fold_with(folder)
1167 } => PatternKind::Leaf {
1168 subpatterns: subpatterns.fold_with(folder),
1170 PatternKind::Deref {
1172 } => PatternKind::Deref {
1173 subpattern: subpattern.fold_with(folder),
1175 PatternKind::Constant {
1177 } => PatternKind::Constant {
1178 value: value.fold_with(folder)
1180 PatternKind::Range {
1185 } => PatternKind::Range {
1186 lo: lo.fold_with(folder),
1187 hi: hi.fold_with(folder),
1188 ty: ty.fold_with(folder),
1191 PatternKind::Slice {
1195 } => PatternKind::Slice {
1196 prefix: prefix.fold_with(folder),
1197 slice: slice.fold_with(folder),
1198 suffix: suffix.fold_with(folder)
1200 PatternKind::Array {
1204 } => PatternKind::Array {
1205 prefix: prefix.fold_with(folder),
1206 slice: slice.fold_with(folder),
1207 suffix: suffix.fold_with(folder)
1213 pub fn compare_const_vals<'a, 'tcx>(
1214 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1215 a: &'tcx ty::Const<'tcx>,
1216 b: &'tcx ty::Const<'tcx>,
1217 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1218 ) -> Option<Ordering> {
1219 trace!("compare_const_vals: {:?}, {:?}", a, b);
1221 let from_bool = |v: bool| {
1223 Some(Ordering::Equal)
1229 let fallback = || from_bool(a == b);
1231 // Use the fallback if any type differs
1232 if a.ty != b.ty || a.ty != ty.value {
1236 // FIXME: This should use assert_bits(ty) instead of use_bits
1237 // but triggers possibly bugs due to mismatching of arrays and slices
1238 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1239 use ::rustc_apfloat::Float;
1240 return match ty.value.sty {
1241 ty::Float(ast::FloatTy::F32) => {
1242 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1243 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1246 ty::Float(ast::FloatTy::F64) => {
1247 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1248 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1252 let layout = tcx.layout_of(ty).ok()?;
1253 assert!(layout.abi.is_signed());
1254 let a = sign_extend(a, layout.size);
1255 let b = sign_extend(b, layout.size);
1256 Some((a as i128).cmp(&(b as i128)))
1258 _ => Some(a.cmp(&b)),
1262 if let ty::Ref(_, rty, _) = ty.value.sty {
1263 if let ty::Str = rty.sty {
1264 match (a.val, b.val) {
1266 ConstValue::ScalarPair(
1270 ConstValue::ScalarPair(
1274 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1275 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1276 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1278 let map = tcx.alloc_map.lock();
1279 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1280 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1281 if alloc_a.bytes.len() as u128 == len_a {
1282 return from_bool(alloc_a == alloc_b);