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;
23 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability, UserTypeAnnotation};
24 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
25 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty};
26 use rustc::ty::subst::{Substs, Kind};
27 use rustc::hir::{self, PatKind, RangeEnd};
28 use rustc::hir::def::{Def, CtorKind};
29 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
31 use rustc_data_structures::indexed_vec::Idx;
33 use std::cmp::Ordering;
38 use syntax_pos::symbol::Symbol;
40 #[derive(Clone, Debug)]
41 pub enum PatternError {
42 AssociatedConstInPattern(Span),
43 StaticInPattern(Span),
48 #[derive(Copy, Clone, Debug)]
49 pub enum BindingMode<'tcx> {
51 ByRef(Region<'tcx>, BorrowKind),
54 #[derive(Clone, Debug)]
55 pub struct FieldPattern<'tcx> {
57 pub pattern: Pattern<'tcx>,
60 #[derive(Clone, Debug)]
61 pub struct Pattern<'tcx> {
64 pub kind: Box<PatternKind<'tcx>>,
67 #[derive(Copy, Clone, Debug)]
68 pub struct PatternTypeAnnotation<'tcx>(UserTypeAnnotation<'tcx>);
70 impl<'tcx> PatternTypeAnnotation<'tcx> {
71 pub(crate) fn from_c_ty(c_ty: ty::CanonicalTy<'tcx>) -> Self {
72 Self::from_u_ty(UserTypeAnnotation::Ty(c_ty))
74 pub(crate) fn from_u_ty(u_ty: UserTypeAnnotation<'tcx>) -> Self {
75 PatternTypeAnnotation(u_ty)
78 pub(crate) fn user_ty(self) -> UserTypeAnnotation<'tcx> { self.0 }
81 #[derive(Clone, Debug)]
82 pub enum PatternKind<'tcx> {
86 user_ty: PatternTypeAnnotation<'tcx>,
87 subpattern: Pattern<'tcx>,
91 /// x, ref x, x @ P, etc
93 mutability: Mutability,
95 mode: BindingMode<'tcx>,
98 subpattern: Option<Pattern<'tcx>>,
101 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
103 adt_def: &'tcx AdtDef,
104 substs: &'tcx Substs<'tcx>,
105 variant_index: usize,
106 subpatterns: Vec<FieldPattern<'tcx>>,
109 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
111 subpatterns: Vec<FieldPattern<'tcx>>,
114 /// box P, &P, &mut P, etc
116 subpattern: Pattern<'tcx>,
120 value: &'tcx ty::Const<'tcx>,
124 lo: &'tcx ty::Const<'tcx>,
125 hi: &'tcx ty::Const<'tcx>,
130 /// matches against a slice, checking the length and extracting elements.
131 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
132 /// e.g. `&[ref xs..]`.
134 prefix: Vec<Pattern<'tcx>>,
135 slice: Option<Pattern<'tcx>>,
136 suffix: Vec<Pattern<'tcx>>,
139 /// fixed match against an array, irrefutable
141 prefix: Vec<Pattern<'tcx>>,
142 slice: Option<Pattern<'tcx>>,
143 suffix: Vec<Pattern<'tcx>>,
147 impl<'tcx> fmt::Display for Pattern<'tcx> {
148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 PatternKind::Wild => write!(f, "_"),
151 PatternKind::AscribeUserType { ref subpattern, .. } =>
152 write!(f, "{}: _", subpattern),
153 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
154 let is_mut = match mode {
155 BindingMode::ByValue => mutability == Mutability::Mut,
156 BindingMode::ByRef(_, bk) => {
158 match bk { BorrowKind::Mut { .. } => true, _ => false }
164 write!(f, "{}", name)?;
165 if let Some(ref subpattern) = *subpattern {
166 write!(f, " @ {}", subpattern)?;
170 PatternKind::Variant { ref subpatterns, .. } |
171 PatternKind::Leaf { ref subpatterns } => {
172 let variant = match *self.kind {
173 PatternKind::Variant { adt_def, variant_index, .. } => {
174 Some(&adt_def.variants[variant_index])
176 _ => if let ty::Adt(adt, _) = self.ty.sty {
178 Some(&adt.variants[0])
187 let mut first = true;
188 let mut start_or_continue = || if first { first = false; "" } else { ", " };
190 if let Some(variant) = variant {
191 write!(f, "{}", variant.name)?;
193 // Only for Adt we can have `S {...}`,
194 // which we handle separately here.
195 if variant.ctor_kind == CtorKind::Fictive {
199 for p in subpatterns {
200 if let PatternKind::Wild = *p.pattern.kind {
203 let name = variant.fields[p.field.index()].ident;
204 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
208 if printed < variant.fields.len() {
209 write!(f, "{}..", start_or_continue())?;
212 return write!(f, " }}");
216 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
217 if num_fields != 0 || variant.is_none() {
219 for i in 0..num_fields {
220 write!(f, "{}", start_or_continue())?;
222 // Common case: the field is where we expect it.
223 if let Some(p) = subpatterns.get(i) {
224 if p.field.index() == i {
225 write!(f, "{}", p.pattern)?;
230 // Otherwise, we have to go looking for it.
231 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
232 write!(f, "{}", p.pattern)?;
242 PatternKind::Deref { ref subpattern } => {
244 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
245 ty::Ref(_, _, mutbl) => {
247 if mutbl == hir::MutMutable {
251 _ => bug!("{} is a bad Deref pattern type", self.ty)
253 write!(f, "{}", subpattern)
255 PatternKind::Constant { value } => {
256 fmt_const_val(f, value)
258 PatternKind::Range { lo, hi, ty: _, end } => {
259 fmt_const_val(f, lo)?;
261 RangeEnd::Included => write!(f, "..=")?,
262 RangeEnd::Excluded => write!(f, "..")?,
266 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
267 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
268 let mut first = true;
269 let mut start_or_continue = || if first { first = false; "" } else { ", " };
272 write!(f, "{}{}", start_or_continue(), p)?;
274 if let Some(ref slice) = *slice {
275 write!(f, "{}", start_or_continue())?;
277 PatternKind::Wild => {}
278 _ => write!(f, "{}", slice)?
283 write!(f, "{}{}", start_or_continue(), p)?;
291 pub struct PatternContext<'a, 'tcx: 'a> {
292 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
293 pub param_env: ty::ParamEnv<'tcx>,
294 pub tables: &'a ty::TypeckTables<'tcx>,
295 pub substs: &'tcx Substs<'tcx>,
296 pub errors: Vec<PatternError>,
299 impl<'a, 'tcx> Pattern<'tcx> {
300 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
301 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
302 tables: &'a ty::TypeckTables<'tcx>,
303 pat: &'tcx hir::Pat) -> Self {
304 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
305 let result = pcx.lower_pattern(pat);
306 if !pcx.errors.is_empty() {
307 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
308 tcx.sess.delay_span_bug(pat.span, &msg);
310 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
315 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
316 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
317 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
318 tables: &'a ty::TypeckTables<'tcx>) -> Self {
321 param_env: param_env_and_substs.param_env,
323 substs: param_env_and_substs.value,
328 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
329 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
330 // pattern has the type that results *after* dereferencing. For example, in this code:
333 // match &&Some(0i32) {
334 // Some(n) => { ... },
339 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
340 // determined in rustc_typeck::check::match). The adjustments would be
342 // `vec![&&Option<i32>, &Option<i32>]`.
344 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
345 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
346 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
347 // gets the least-dereferenced type).
348 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
355 .fold(unadjusted_pat, |pat, ref_ty| {
356 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
360 kind: Box::new(PatternKind::Deref { subpattern: pat }),
366 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
367 let mut ty = self.tables.node_id_to_type(pat.hir_id);
369 let kind = match pat.node {
370 PatKind::Wild => PatternKind::Wild,
372 PatKind::Lit(ref value) => self.lower_lit(value),
374 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
375 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
376 (PatternKind::Constant { value: lo },
377 PatternKind::Constant { value: hi }) => {
378 use std::cmp::Ordering;
379 let cmp = compare_const_vals(
383 self.param_env.and(ty),
386 (RangeEnd::Excluded, Some(Ordering::Less)) =>
387 PatternKind::Range { lo, hi, ty, end },
388 (RangeEnd::Excluded, _) => {
393 "lower range bound must be less than upper",
397 (RangeEnd::Included, Some(Ordering::Equal)) => {
398 PatternKind::Constant { value: lo }
400 (RangeEnd::Included, Some(Ordering::Less)) => {
401 PatternKind::Range { lo, hi, ty, end }
403 (RangeEnd::Included, _) => {
404 let mut err = struct_span_err!(
408 "lower range bound must be less than or equal to upper"
412 "lower bound larger than upper bound",
414 if self.tcx.sess.teach(&err.get_code().unwrap()) {
415 err.note("When matching against a range, the compiler \
416 verifies that the range is non-empty. Range \
417 patterns include both end-points, so this is \
418 equivalent to requiring the start of the range \
419 to be less than or equal to the end of the range.");
426 _ => PatternKind::Wild
430 PatKind::Path(ref qpath) => {
431 return self.lower_path(qpath, pat.hir_id, pat.span);
434 PatKind::Ref(ref subpattern, _) |
435 PatKind::Box(ref subpattern) => {
436 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
439 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
443 subpattern: Pattern {
446 kind: Box::new(self.slice_or_array_pattern(
447 pat.span, ty, prefix, slice, suffix))
452 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
453 ty::Error => { // Avoid ICE
454 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
459 "unexpanded type for vector pattern: {:?}",
464 PatKind::Tuple(ref subpatterns, ddpos) => {
466 ty::Tuple(ref tys) => {
469 .enumerate_and_adjust(tys.len(), ddpos)
470 .map(|(i, subpattern)| FieldPattern {
471 field: Field::new(i),
472 pattern: self.lower_pattern(subpattern)
476 PatternKind::Leaf { subpatterns: subpatterns }
478 ty::Error => { // Avoid ICE (#50577)
479 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
481 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
485 PatKind::Binding(_, id, ident, ref sub) => {
486 let var_ty = self.tables.node_id_to_type(pat.hir_id);
487 let region = match var_ty.sty {
488 ty::Ref(r, _, _) => Some(r),
489 ty::Error => { // Avoid ICE
490 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
494 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
495 .expect("missing binding mode");
496 let (mutability, mode) = match bm {
497 ty::BindByValue(hir::MutMutable) =>
498 (Mutability::Mut, BindingMode::ByValue),
499 ty::BindByValue(hir::MutImmutable) =>
500 (Mutability::Not, BindingMode::ByValue),
501 ty::BindByReference(hir::MutMutable) =>
502 (Mutability::Not, BindingMode::ByRef(
503 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
504 ty::BindByReference(hir::MutImmutable) =>
505 (Mutability::Not, BindingMode::ByRef(
506 region.unwrap(), BorrowKind::Shared)),
509 // A ref x pattern is the same node used for x, and as such it has
510 // x's type, which is &T, where we want T (the type being matched).
511 if let ty::BindByReference(_) = bm {
512 if let ty::Ref(_, rty, _) = ty.sty {
515 bug!("`ref {}` has wrong type {}", ident, ty);
519 PatternKind::Binding {
525 subpattern: self.lower_opt_pattern(sub),
529 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
530 let def = self.tables.qpath_def(qpath, pat.hir_id);
531 let adt_def = match ty.sty {
532 ty::Adt(adt_def, _) => adt_def,
533 ty::Error => { // Avoid ICE (#50585)
534 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
536 _ => span_bug!(pat.span,
537 "tuple struct pattern not applied to an ADT {:?}",
540 let variant_def = adt_def.variant_of_def(def);
544 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
545 .map(|(i, field)| FieldPattern {
546 field: Field::new(i),
547 pattern: self.lower_pattern(field),
551 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
554 PatKind::Struct(ref qpath, ref fields, _) => {
555 let def = self.tables.qpath_def(qpath, pat.hir_id);
560 field: Field::new(self.tcx.field_index(field.node.id,
562 pattern: self.lower_pattern(&field.node.pat),
567 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
574 kind: Box::new(kind),
578 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
579 pats.iter().map(|p| self.lower_pattern(p)).collect()
582 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
584 pat.as_ref().map(|p| self.lower_pattern(p))
587 fn flatten_nested_slice_patterns(
589 prefix: Vec<Pattern<'tcx>>,
590 slice: Option<Pattern<'tcx>>,
591 suffix: Vec<Pattern<'tcx>>)
592 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
594 let orig_slice = match slice {
595 Some(orig_slice) => orig_slice,
596 None => return (prefix, slice, suffix)
598 let orig_prefix = prefix;
599 let orig_suffix = suffix;
601 // dance because of intentional borrow-checker stupidity.
602 let kind = *orig_slice.kind;
604 PatternKind::Slice { prefix, slice, mut suffix } |
605 PatternKind::Array { prefix, slice, mut suffix } => {
606 let mut orig_prefix = orig_prefix;
608 orig_prefix.extend(prefix);
609 suffix.extend(orig_suffix);
611 (orig_prefix, slice, suffix)
614 (orig_prefix, Some(Pattern {
615 kind: box kind, ..orig_slice
621 fn slice_or_array_pattern(
625 prefix: &'tcx [P<hir::Pat>],
626 slice: &'tcx Option<P<hir::Pat>>,
627 suffix: &'tcx [P<hir::Pat>])
630 let prefix = self.lower_patterns(prefix);
631 let slice = self.lower_opt_pattern(slice);
632 let suffix = self.lower_patterns(suffix);
633 let (prefix, slice, suffix) =
634 self.flatten_nested_slice_patterns(prefix, slice, suffix);
638 // matching a slice or fixed-length array
639 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
642 ty::Array(_, len) => {
643 // fixed-length array
644 let len = len.unwrap_usize(self.tcx);
645 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
646 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
650 span_bug!(span, "bad slice pattern type {:?}", ty);
655 fn lower_variant_or_leaf(
661 subpatterns: Vec<FieldPattern<'tcx>>,
662 ) -> PatternKind<'tcx> {
663 let mut kind = match def {
664 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
665 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
666 let adt_def = self.tcx.adt_def(enum_id);
667 if adt_def.is_enum() {
668 let substs = match ty.sty {
670 ty::FnDef(_, substs) => substs,
671 ty::Error => { // Avoid ICE (#50585)
672 return PatternKind::Wild;
674 _ => bug!("inappropriate type for def: {:?}", ty.sty),
676 PatternKind::Variant {
679 variant_index: adt_def.variant_index_with_id(variant_id),
683 PatternKind::Leaf { subpatterns: subpatterns }
687 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
688 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
689 PatternKind::Leaf { subpatterns: subpatterns }
693 self.errors.push(PatternError::NonConstPath(span));
698 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
699 let subpattern = Pattern {
702 kind: Box::new(kind),
705 debug!("pattern user_ty = {:?} for pattern at {:?}", user_ty, span);
707 let pat_ty = PatternTypeAnnotation::from_u_ty(user_ty);
708 kind = PatternKind::AscribeUserType {
718 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
719 /// it to `const_to_pat`. Any other path (like enum variants without fields)
720 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
721 fn lower_path(&mut self,
726 let ty = self.tables.node_id_to_type(id);
727 let def = self.tables.qpath_def(qpath, id);
728 let is_associated_const = match def {
729 Def::AssociatedConst(_) => true,
732 let kind = match def {
733 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
734 let substs = self.tables.node_substs(id);
735 match ty::Instance::resolve(
746 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
748 return self.const_to_pat(instance, value, id, span)
751 self.tcx.sess.span_err(
753 "could not evaluate constant pattern",
760 self.errors.push(if is_associated_const {
761 PatternError::AssociatedConstInPattern(span)
763 PatternError::StaticInPattern(span)
769 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
775 kind: Box::new(kind),
779 /// Converts literals, paths and negation of literals to patterns.
780 /// The special case for negation exists to allow things like -128i8
781 /// which would overflow if we tried to evaluate 128i8 and then negate
783 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
785 hir::ExprKind::Lit(ref lit) => {
786 let ty = self.tables.expr_ty(expr);
787 match lit_to_const(&lit.node, self.tcx, ty, false) {
789 let instance = ty::Instance::new(
790 self.tables.local_id_root.expect("literal outside any scope"),
793 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
796 if e == LitToConstError::UnparseableFloat {
797 self.errors.push(PatternError::FloatBug);
803 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
804 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
805 let ty = self.tables.expr_ty(expr);
806 let lit = match expr.node {
807 hir::ExprKind::Lit(ref lit) => lit,
808 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
810 match lit_to_const(&lit.node, self.tcx, ty, true) {
812 let instance = ty::Instance::new(
813 self.tables.local_id_root.expect("literal outside any scope"),
816 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
819 if e == LitToConstError::UnparseableFloat {
820 self.errors.push(PatternError::FloatBug);
826 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
830 /// Converts an evaluated constant to a pattern (if possible).
831 /// This means aggregate values (like structs and enums) are converted
832 /// to a pattern that matches the value (as if you'd compare via eq).
835 instance: ty::Instance<'tcx>,
836 cv: &'tcx ty::Const<'tcx>,
840 debug!("const_to_pat: cv={:#?}", cv);
841 let adt_subpattern = |i, variant_opt| {
842 let field = Field::new(i);
843 let val = const_field(
844 self.tcx, self.param_env, instance,
845 variant_opt, field, cv,
846 ).expect("field access failed");
847 self.const_to_pat(instance, val, id, span)
849 let adt_subpatterns = |n, variant_opt| {
851 let field = Field::new(i);
854 pattern: adt_subpattern(i, variant_opt),
856 }).collect::<Vec<_>>()
858 let kind = match cv.ty.sty {
860 let id = self.tcx.hir.hir_to_node_id(id);
862 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
865 "floating-point types cannot be used in patterns",
867 PatternKind::Constant {
871 ty::Adt(adt_def, _) if adt_def.is_union() => {
872 // Matching on union fields is unsafe, we can't hide it in constants
873 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
876 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
877 let msg = format!("to use a constant of type `{}` in a pattern, \
878 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
879 self.tcx.item_path_str(adt_def.did),
880 self.tcx.item_path_str(adt_def.did));
881 self.tcx.sess.span_err(span, &msg);
884 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
885 let variant_index = const_variant_index(
886 self.tcx, self.param_env, instance, cv
887 ).expect("const_variant_index failed");
888 let subpatterns = adt_subpatterns(
889 adt_def.variants[variant_index].fields.len(),
892 PatternKind::Variant {
899 ty::Adt(adt_def, _) => {
900 let struct_var = adt_def.non_enum_variant();
902 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
905 ty::Tuple(fields) => {
907 subpatterns: adt_subpatterns(fields.len(), None),
912 prefix: (0..n.unwrap_usize(self.tcx))
913 .map(|i| adt_subpattern(i as usize, None))
920 PatternKind::Constant {
929 kind: Box::new(kind),
934 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
935 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
939 fn tables(&self) -> &ty::TypeckTables<'tcx> {
945 pub trait PatternFoldable<'tcx> : Sized {
946 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
947 self.super_fold_with(folder)
950 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
953 pub trait PatternFolder<'tcx> : Sized {
954 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
955 pattern.super_fold_with(self)
958 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
959 kind.super_fold_with(self)
964 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
965 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
966 let content: T = (**self).fold_with(folder);
971 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
972 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
973 self.iter().map(|t| t.fold_with(folder)).collect()
977 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
978 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
979 self.as_ref().map(|t| t.fold_with(folder))
983 macro_rules! CloneImpls {
984 (<$lt_tcx:tt> $($ty:ty),+) => {
986 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
987 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
996 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
997 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
998 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>, PatternTypeAnnotation<'tcx>
1001 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1002 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1004 field: self.field.fold_with(folder),
1005 pattern: self.pattern.fold_with(folder)
1010 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1011 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1012 folder.fold_pattern(self)
1015 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1017 ty: self.ty.fold_with(folder),
1018 span: self.span.fold_with(folder),
1019 kind: self.kind.fold_with(folder)
1024 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1025 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1026 folder.fold_pattern_kind(self)
1029 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1031 PatternKind::Wild => PatternKind::Wild,
1032 PatternKind::AscribeUserType {
1036 } => PatternKind::AscribeUserType {
1037 subpattern: subpattern.fold_with(folder),
1038 user_ty: user_ty.fold_with(folder),
1041 PatternKind::Binding {
1048 } => PatternKind::Binding {
1049 mutability: mutability.fold_with(folder),
1050 name: name.fold_with(folder),
1051 mode: mode.fold_with(folder),
1052 var: var.fold_with(folder),
1053 ty: ty.fold_with(folder),
1054 subpattern: subpattern.fold_with(folder),
1056 PatternKind::Variant {
1061 } => PatternKind::Variant {
1062 adt_def: adt_def.fold_with(folder),
1063 substs: substs.fold_with(folder),
1064 variant_index: variant_index.fold_with(folder),
1065 subpatterns: subpatterns.fold_with(folder)
1069 } => PatternKind::Leaf {
1070 subpatterns: subpatterns.fold_with(folder),
1072 PatternKind::Deref {
1074 } => PatternKind::Deref {
1075 subpattern: subpattern.fold_with(folder),
1077 PatternKind::Constant {
1079 } => PatternKind::Constant {
1080 value: value.fold_with(folder)
1082 PatternKind::Range {
1087 } => PatternKind::Range {
1088 lo: lo.fold_with(folder),
1089 hi: hi.fold_with(folder),
1090 ty: ty.fold_with(folder),
1093 PatternKind::Slice {
1097 } => PatternKind::Slice {
1098 prefix: prefix.fold_with(folder),
1099 slice: slice.fold_with(folder),
1100 suffix: suffix.fold_with(folder)
1102 PatternKind::Array {
1106 } => PatternKind::Array {
1107 prefix: prefix.fold_with(folder),
1108 slice: slice.fold_with(folder),
1109 suffix: suffix.fold_with(folder)
1115 pub fn compare_const_vals<'a, 'tcx>(
1116 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1117 a: &'tcx ty::Const<'tcx>,
1118 b: &'tcx ty::Const<'tcx>,
1119 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1120 ) -> Option<Ordering> {
1121 trace!("compare_const_vals: {:?}, {:?}", a, b);
1123 let from_bool = |v: bool| {
1125 Some(Ordering::Equal)
1131 let fallback = || from_bool(a == b);
1133 // Use the fallback if any type differs
1134 if a.ty != b.ty || a.ty != ty.value {
1138 // FIXME: This should use assert_bits(ty) instead of use_bits
1139 // but triggers possibly bugs due to mismatching of arrays and slices
1140 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1141 use ::rustc_apfloat::Float;
1142 return match ty.value.sty {
1143 ty::Float(ast::FloatTy::F32) => {
1144 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1145 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1148 ty::Float(ast::FloatTy::F64) => {
1149 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1150 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1154 let layout = tcx.layout_of(ty).ok()?;
1155 assert!(layout.abi.is_signed());
1156 let a = sign_extend(a, layout.size);
1157 let b = sign_extend(b, layout.size);
1158 Some((a as i128).cmp(&(b as i128)))
1160 _ => Some(a.cmp(&b)),
1164 if let ty::Ref(_, rty, _) = ty.value.sty {
1165 if let ty::Str = rty.sty {
1166 match (a.val, b.val) {
1168 ConstValue::ScalarPair(
1172 ConstValue::ScalarPair(
1176 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1177 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1178 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1180 let map = tcx.alloc_map.lock();
1181 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1182 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1183 if alloc_a.bytes.len() as u128 == len_a {
1184 return from_bool(alloc_a == alloc_b);
1198 #[derive(PartialEq)]
1199 enum LitToConstError {
1204 // FIXME: Combine with rustc_mir::hair::cx::const_eval_literal
1205 fn lit_to_const<'a, 'tcx>(lit: &'tcx ast::LitKind,
1206 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1209 -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
1212 use rustc::mir::interpret::*;
1213 let lit = match *lit {
1214 LitKind::Str(ref s, _) => {
1216 let id = tcx.allocate_bytes(s.as_bytes());
1217 ConstValue::new_slice(Scalar::Ptr(id.into()), s.len() as u64, tcx)
1219 LitKind::ByteStr(ref data) => {
1220 let id = tcx.allocate_bytes(data);
1221 ConstValue::Scalar(Scalar::Ptr(id.into()))
1223 LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
1227 LitKind::Int(n, _) => {
1232 let ity = match ty.sty {
1233 ty::Int(IntTy::Isize) => Int::Signed(tcx.sess.target.isize_ty),
1234 ty::Int(other) => Int::Signed(other),
1235 ty::Uint(UintTy::Usize) => Int::Unsigned(tcx.sess.target.usize_ty),
1236 ty::Uint(other) => Int::Unsigned(other),
1237 ty::Error => { // Avoid ICE (#51963)
1238 return Err(LitToConstError::Propagated);
1240 _ => bug!("literal integer type with bad type ({:?})", ty.sty),
1242 // This converts from LitKind::Int (which is sign extended) to
1243 // Scalar::Bytes (which is zero extended)
1245 // FIXME(oli-obk): are these casts correct?
1246 Int::Signed(IntTy::I8) if neg =>
1247 (n as i8).overflowing_neg().0 as u8 as u128,
1248 Int::Signed(IntTy::I16) if neg =>
1249 (n as i16).overflowing_neg().0 as u16 as u128,
1250 Int::Signed(IntTy::I32) if neg =>
1251 (n as i32).overflowing_neg().0 as u32 as u128,
1252 Int::Signed(IntTy::I64) if neg =>
1253 (n as i64).overflowing_neg().0 as u64 as u128,
1254 Int::Signed(IntTy::I128) if neg =>
1255 (n as i128).overflowing_neg().0 as u128,
1256 Int::Signed(IntTy::I8) | Int::Unsigned(UintTy::U8) => n as u8 as u128,
1257 Int::Signed(IntTy::I16) | Int::Unsigned(UintTy::U16) => n as u16 as u128,
1258 Int::Signed(IntTy::I32) | Int::Unsigned(UintTy::U32) => n as u32 as u128,
1259 Int::Signed(IntTy::I64) | Int::Unsigned(UintTy::U64) => n as u64 as u128,
1260 Int::Signed(IntTy::I128)| Int::Unsigned(UintTy::U128) => n,
1263 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size.bytes() as u8;
1264 ConstValue::Scalar(Scalar::Bits {
1269 LitKind::Float(n, fty) => {
1270 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1272 LitKind::FloatUnsuffixed(n) => {
1273 let fty = match ty.sty {
1274 ty::Float(fty) => fty,
1277 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1279 LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
1280 LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
1282 Ok(ty::Const::from_const_value(tcx, lit, ty))
1285 pub fn parse_float<'tcx>(
1289 ) -> Result<ConstValue<'tcx>, ()> {
1290 let num = num.as_str();
1291 use rustc_apfloat::ieee::{Single, Double};
1292 use rustc_apfloat::Float;
1293 let (bits, size) = match fty {
1294 ast::FloatTy::F32 => {
1295 num.parse::<f32>().map_err(|_| ())?;
1296 let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1297 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1304 ast::FloatTy::F64 => {
1305 num.parse::<f64>().map_err(|_| ())?;
1306 let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1307 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1316 Ok(ConstValue::Scalar(Scalar::Bits { bits, size }))