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 interpret::{const_val_field, const_variant_index, self};
21 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
22 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, Value};
23 use rustc::ty::{self, TyCtxt, AdtDef, Ty, Region};
24 use rustc::ty::subst::{Substs, Kind};
25 use rustc::hir::{self, PatKind, RangeEnd};
26 use rustc::hir::def::{Def, CtorKind};
27 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
29 use rustc_data_structures::indexed_vec::Idx;
31 use std::cmp::Ordering;
36 use syntax_pos::symbol::Symbol;
38 #[derive(Clone, Debug)]
39 pub enum PatternError {
40 AssociatedConstInPattern(Span),
41 StaticInPattern(Span),
46 #[derive(Copy, Clone, Debug)]
47 pub enum BindingMode<'tcx> {
49 ByRef(Region<'tcx>, BorrowKind),
52 #[derive(Clone, Debug)]
53 pub struct FieldPattern<'tcx> {
55 pub pattern: Pattern<'tcx>,
58 #[derive(Clone, Debug)]
59 pub struct Pattern<'tcx> {
62 pub kind: Box<PatternKind<'tcx>>,
65 #[derive(Clone, Debug)]
66 pub enum PatternKind<'tcx> {
69 /// x, ref x, x @ P, etc
71 mutability: Mutability,
73 mode: BindingMode<'tcx>,
76 subpattern: Option<Pattern<'tcx>>,
79 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
81 adt_def: &'tcx AdtDef,
82 substs: &'tcx Substs<'tcx>,
84 subpatterns: Vec<FieldPattern<'tcx>>,
87 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
89 subpatterns: Vec<FieldPattern<'tcx>>,
92 /// box P, &P, &mut P, etc
94 subpattern: Pattern<'tcx>,
98 value: &'tcx ty::Const<'tcx>,
102 lo: &'tcx ty::Const<'tcx>,
103 hi: &'tcx ty::Const<'tcx>,
107 /// matches against a slice, checking the length and extracting elements.
108 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
109 /// e.g. `&[ref xs..]`.
111 prefix: Vec<Pattern<'tcx>>,
112 slice: Option<Pattern<'tcx>>,
113 suffix: Vec<Pattern<'tcx>>,
116 /// fixed match against an array, irrefutable
118 prefix: Vec<Pattern<'tcx>>,
119 slice: Option<Pattern<'tcx>>,
120 suffix: Vec<Pattern<'tcx>>,
124 impl<'tcx> fmt::Display for Pattern<'tcx> {
125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127 PatternKind::Wild => write!(f, "_"),
128 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
129 let is_mut = match mode {
130 BindingMode::ByValue => mutability == Mutability::Mut,
131 BindingMode::ByRef(_, bk) => {
133 match bk { BorrowKind::Mut { .. } => true, _ => false }
139 write!(f, "{}", name)?;
140 if let Some(ref subpattern) = *subpattern {
141 write!(f, " @ {}", subpattern)?;
145 PatternKind::Variant { ref subpatterns, .. } |
146 PatternKind::Leaf { ref subpatterns } => {
147 let variant = match *self.kind {
148 PatternKind::Variant { adt_def, variant_index, .. } => {
149 Some(&adt_def.variants[variant_index])
151 _ => if let ty::TyAdt(adt, _) = self.ty.sty {
153 Some(&adt.variants[0])
162 let mut first = true;
163 let mut start_or_continue = || if first { first = false; "" } else { ", " };
165 if let Some(variant) = variant {
166 write!(f, "{}", variant.name)?;
168 // Only for TyAdt we can have `S {...}`,
169 // which we handle separately here.
170 if variant.ctor_kind == CtorKind::Fictive {
174 for p in subpatterns {
175 if let PatternKind::Wild = *p.pattern.kind {
178 let name = variant.fields[p.field.index()].ident;
179 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
183 if printed < variant.fields.len() {
184 write!(f, "{}..", start_or_continue())?;
187 return write!(f, " }}");
191 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
192 if num_fields != 0 || variant.is_none() {
194 for i in 0..num_fields {
195 write!(f, "{}", start_or_continue())?;
197 // Common case: the field is where we expect it.
198 if let Some(p) = subpatterns.get(i) {
199 if p.field.index() == i {
200 write!(f, "{}", p.pattern)?;
205 // Otherwise, we have to go looking for it.
206 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
207 write!(f, "{}", p.pattern)?;
217 PatternKind::Deref { ref subpattern } => {
219 ty::TyAdt(def, _) if def.is_box() => write!(f, "box ")?,
220 ty::TyRef(_, _, mutbl) => {
222 if mutbl == hir::MutMutable {
226 _ => bug!("{} is a bad Deref pattern type", self.ty)
228 write!(f, "{}", subpattern)
230 PatternKind::Constant { value } => {
231 fmt_const_val(f, value)
233 PatternKind::Range { lo, hi, end } => {
234 fmt_const_val(f, lo)?;
236 RangeEnd::Included => write!(f, "...")?,
237 RangeEnd::Excluded => write!(f, "..")?,
241 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
242 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
243 let mut first = true;
244 let mut start_or_continue = || if first { first = false; "" } else { ", " };
247 write!(f, "{}{}", start_or_continue(), p)?;
249 if let Some(ref slice) = *slice {
250 write!(f, "{}", start_or_continue())?;
252 PatternKind::Wild => {}
253 _ => write!(f, "{}", slice)?
258 write!(f, "{}{}", start_or_continue(), p)?;
266 pub struct PatternContext<'a, 'tcx: 'a> {
267 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
268 pub param_env: ty::ParamEnv<'tcx>,
269 pub tables: &'a ty::TypeckTables<'tcx>,
270 pub substs: &'tcx Substs<'tcx>,
271 pub errors: Vec<PatternError>,
274 impl<'a, 'tcx> Pattern<'tcx> {
275 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
276 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
277 tables: &'a ty::TypeckTables<'tcx>,
278 pat: &'tcx hir::Pat) -> Self {
279 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
280 let result = pcx.lower_pattern(pat);
281 if !pcx.errors.is_empty() {
282 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
283 tcx.sess.delay_span_bug(pat.span, &msg);
285 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
290 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
291 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
292 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
293 tables: &'a ty::TypeckTables<'tcx>) -> Self {
296 param_env: param_env_and_substs.param_env,
298 substs: param_env_and_substs.value,
303 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
304 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
305 // pattern has the type that results *after* dereferencing. For example, in this code:
308 // match &&Some(0i32) {
309 // Some(n) => { ... },
314 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
315 // determined in rustc_typeck::check::match). The adjustments would be
317 // `vec![&&Option<i32>, &Option<i32>]`.
319 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
320 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
321 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
322 // gets the least-dereferenced type).
323 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
330 .fold(unadjusted_pat, |pat, ref_ty| {
331 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
335 kind: Box::new(PatternKind::Deref { subpattern: pat }),
341 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
342 let mut ty = self.tables.node_id_to_type(pat.hir_id);
344 let kind = match pat.node {
345 PatKind::Wild => PatternKind::Wild,
347 PatKind::Lit(ref value) => self.lower_lit(value),
349 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
350 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
351 (PatternKind::Constant { value: lo },
352 PatternKind::Constant { value: hi }) => {
353 use std::cmp::Ordering;
354 let cmp = compare_const_vals(
358 self.param_env.and(ty),
361 (RangeEnd::Excluded, Some(Ordering::Less)) =>
362 PatternKind::Range { lo, hi, end },
363 (RangeEnd::Excluded, _) => {
368 "lower range bound must be less than upper",
372 (RangeEnd::Included, None) |
373 (RangeEnd::Included, Some(Ordering::Greater)) => {
374 let mut err = struct_span_err!(
378 "lower range bound must be less than or equal to upper"
382 "lower bound larger than upper bound",
384 if self.tcx.sess.teach(&err.get_code().unwrap()) {
385 err.note("When matching against a range, the compiler \
386 verifies that the range is non-empty. Range \
387 patterns include both end-points, so this is \
388 equivalent to requiring the start of the range \
389 to be less than or equal to the end of the range.");
394 (RangeEnd::Included, Some(_)) => PatternKind::Range { lo, hi, end },
397 _ => PatternKind::Wild
401 PatKind::Path(ref qpath) => {
402 return self.lower_path(qpath, pat.hir_id, pat.span);
405 PatKind::Ref(ref subpattern, _) |
406 PatKind::Box(ref subpattern) => {
407 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
410 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
412 ty::TyRef(_, ty, _) =>
414 subpattern: Pattern {
417 kind: Box::new(self.slice_or_array_pattern(
418 pat.span, ty, prefix, slice, suffix))
423 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
424 ty::TyError => { // Avoid ICE
425 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
430 "unexpanded type for vector pattern: {:?}",
435 PatKind::Tuple(ref subpatterns, ddpos) => {
437 ty::TyTuple(ref tys) => {
440 .enumerate_and_adjust(tys.len(), ddpos)
441 .map(|(i, subpattern)| FieldPattern {
442 field: Field::new(i),
443 pattern: self.lower_pattern(subpattern)
447 PatternKind::Leaf { subpatterns: subpatterns }
449 ty::TyError => { // Avoid ICE (#50577)
450 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
452 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
456 PatKind::Binding(_, id, ident, ref sub) => {
457 let var_ty = self.tables.node_id_to_type(pat.hir_id);
458 let region = match var_ty.sty {
459 ty::TyRef(r, _, _) => Some(r),
460 ty::TyError => { // Avoid ICE
461 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
465 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
466 .expect("missing binding mode");
467 let (mutability, mode) = match bm {
468 ty::BindByValue(hir::MutMutable) =>
469 (Mutability::Mut, BindingMode::ByValue),
470 ty::BindByValue(hir::MutImmutable) =>
471 (Mutability::Not, BindingMode::ByValue),
472 ty::BindByReference(hir::MutMutable) =>
473 (Mutability::Not, BindingMode::ByRef(
474 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
475 ty::BindByReference(hir::MutImmutable) =>
476 (Mutability::Not, BindingMode::ByRef(
477 region.unwrap(), BorrowKind::Shared)),
480 // A ref x pattern is the same node used for x, and as such it has
481 // x's type, which is &T, where we want T (the type being matched).
482 if let ty::BindByReference(_) = bm {
483 if let ty::TyRef(_, rty, _) = ty.sty {
486 bug!("`ref {}` has wrong type {}", ident, ty);
490 PatternKind::Binding {
496 subpattern: self.lower_opt_pattern(sub),
500 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
501 let def = self.tables.qpath_def(qpath, pat.hir_id);
502 let adt_def = match ty.sty {
503 ty::TyAdt(adt_def, _) => adt_def,
504 ty::TyError => { // Avoid ICE (#50585)
505 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
507 _ => span_bug!(pat.span,
508 "tuple struct pattern not applied to an ADT {:?}",
511 let variant_def = adt_def.variant_of_def(def);
515 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
516 .map(|(i, field)| FieldPattern {
517 field: Field::new(i),
518 pattern: self.lower_pattern(field),
521 self.lower_variant_or_leaf(def, pat.span, ty, subpatterns)
524 PatKind::Struct(ref qpath, ref fields, _) => {
525 let def = self.tables.qpath_def(qpath, pat.hir_id);
530 field: Field::new(self.tcx.field_index(field.node.id,
532 pattern: self.lower_pattern(&field.node.pat),
537 self.lower_variant_or_leaf(def, pat.span, ty, subpatterns)
544 kind: Box::new(kind),
548 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
549 pats.iter().map(|p| self.lower_pattern(p)).collect()
552 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
554 pat.as_ref().map(|p| self.lower_pattern(p))
557 fn flatten_nested_slice_patterns(
559 prefix: Vec<Pattern<'tcx>>,
560 slice: Option<Pattern<'tcx>>,
561 suffix: Vec<Pattern<'tcx>>)
562 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
564 let orig_slice = match slice {
565 Some(orig_slice) => orig_slice,
566 None => return (prefix, slice, suffix)
568 let orig_prefix = prefix;
569 let orig_suffix = suffix;
571 // dance because of intentional borrow-checker stupidity.
572 let kind = *orig_slice.kind;
574 PatternKind::Slice { prefix, slice, mut suffix } |
575 PatternKind::Array { prefix, slice, mut suffix } => {
576 let mut orig_prefix = orig_prefix;
578 orig_prefix.extend(prefix);
579 suffix.extend(orig_suffix);
581 (orig_prefix, slice, suffix)
584 (orig_prefix, Some(Pattern {
585 kind: box kind, ..orig_slice
591 fn slice_or_array_pattern(
595 prefix: &'tcx [P<hir::Pat>],
596 slice: &'tcx Option<P<hir::Pat>>,
597 suffix: &'tcx [P<hir::Pat>])
600 let prefix = self.lower_patterns(prefix);
601 let slice = self.lower_opt_pattern(slice);
602 let suffix = self.lower_patterns(suffix);
603 let (prefix, slice, suffix) =
604 self.flatten_nested_slice_patterns(prefix, slice, suffix);
608 // matching a slice or fixed-length array
609 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
612 ty::TyArray(_, len) => {
613 // fixed-length array
614 let len = len.unwrap_usize(self.tcx);
615 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
616 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
620 span_bug!(span, "bad slice pattern type {:?}", ty);
625 fn lower_variant_or_leaf(
630 subpatterns: Vec<FieldPattern<'tcx>>)
634 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
635 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
636 let adt_def = self.tcx.adt_def(enum_id);
637 if adt_def.is_enum() {
638 let substs = match ty.sty {
639 ty::TyAdt(_, substs) |
640 ty::TyFnDef(_, substs) => substs,
641 ty::TyError => { // Avoid ICE (#50585)
642 return PatternKind::Wild;
644 _ => bug!("inappropriate type for def: {:?}", ty.sty),
646 PatternKind::Variant {
649 variant_index: adt_def.variant_index_with_id(variant_id),
653 PatternKind::Leaf { subpatterns: subpatterns }
657 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
658 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
659 PatternKind::Leaf { subpatterns: subpatterns }
663 self.errors.push(PatternError::NonConstPath(span));
669 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
670 /// it to `const_to_pat`. Any other path (like enum variants without fields)
671 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
672 fn lower_path(&mut self,
677 let ty = self.tables.node_id_to_type(id);
678 let def = self.tables.qpath_def(qpath, id);
679 let is_associated_const = match def {
680 Def::AssociatedConst(_) => true,
683 let kind = match def {
684 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
685 let substs = self.tables.node_substs(id);
686 match ty::Instance::resolve(
697 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
699 return self.const_to_pat(instance, value, id, span)
704 "could not evaluate constant pattern",
711 self.errors.push(if is_associated_const {
712 PatternError::AssociatedConstInPattern(span)
714 PatternError::StaticInPattern(span)
720 _ => self.lower_variant_or_leaf(def, span, ty, vec![]),
726 kind: Box::new(kind),
730 /// Converts literals, paths and negation of literals to patterns.
731 /// The special case for negation exists to allow things like -128i8
732 /// which would overflow if we tried to evaluate 128i8 and then negate
734 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
736 hir::ExprLit(ref lit) => {
737 let ty = self.tables.expr_ty(expr);
738 match lit_to_const(&lit.node, self.tcx, ty, false) {
740 let instance = ty::Instance::new(
741 self.tables.local_id_root.expect("literal outside any scope"),
744 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
747 self.errors.push(PatternError::FloatBug);
752 hir::ExprPath(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
753 hir::ExprUnary(hir::UnNeg, ref expr) => {
754 let ty = self.tables.expr_ty(expr);
755 let lit = match expr.node {
756 hir::ExprLit(ref lit) => lit,
757 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
759 match lit_to_const(&lit.node, self.tcx, ty, true) {
761 let instance = ty::Instance::new(
762 self.tables.local_id_root.expect("literal outside any scope"),
765 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
768 self.errors.push(PatternError::FloatBug);
773 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
777 /// Converts an evaluated constant to a pattern (if possible).
778 /// This means aggregate values (like structs and enums) are converted
779 /// to a pattern that matches the value (as if you'd compare via eq).
782 instance: ty::Instance<'tcx>,
783 cv: &'tcx ty::Const<'tcx>,
787 debug!("const_to_pat: cv={:#?}", cv);
788 let adt_subpattern = |i, variant_opt| {
789 let field = Field::new(i);
790 let val = const_val_field(
791 self.tcx, self.param_env, instance,
792 variant_opt, field, cv,
793 ).expect("field access failed");
794 self.const_to_pat(instance, val, id, span)
796 let adt_subpatterns = |n, variant_opt| {
798 let field = Field::new(i);
801 pattern: adt_subpattern(i, variant_opt),
803 }).collect::<Vec<_>>()
805 let kind = match cv.ty.sty {
807 let id = self.tcx.hir.hir_to_node_id(id);
809 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
812 "floating-point types cannot be used in patterns",
814 PatternKind::Constant {
818 ty::TyAdt(adt_def, _) if adt_def.is_union() => {
819 // Matching on union fields is unsafe, we can't hide it in constants
820 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
823 ty::TyAdt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
824 let msg = format!("to use a constant of type `{}` in a pattern, \
825 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
826 self.tcx.item_path_str(adt_def.did),
827 self.tcx.item_path_str(adt_def.did));
828 self.tcx.sess.span_err(span, &msg);
831 ty::TyAdt(adt_def, substs) if adt_def.is_enum() => {
832 let variant_index = const_variant_index(
833 self.tcx, self.param_env, instance, cv
834 ).expect("const_variant_index failed");
835 let subpatterns = adt_subpatterns(
836 adt_def.variants[variant_index].fields.len(),
839 PatternKind::Variant {
846 ty::TyAdt(adt_def, _) => {
847 let struct_var = adt_def.non_enum_variant();
849 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
852 ty::TyTuple(fields) => {
854 subpatterns: adt_subpatterns(fields.len(), None),
857 ty::TyArray(_, n) => {
859 prefix: (0..n.unwrap_usize(self.tcx))
860 .map(|i| adt_subpattern(i as usize, None))
867 PatternKind::Constant {
876 kind: Box::new(kind),
881 pub trait PatternFoldable<'tcx> : Sized {
882 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
883 self.super_fold_with(folder)
886 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
889 pub trait PatternFolder<'tcx> : Sized {
890 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
891 pattern.super_fold_with(self)
894 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
895 kind.super_fold_with(self)
900 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
901 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
902 let content: T = (**self).fold_with(folder);
907 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
908 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
909 self.iter().map(|t| t.fold_with(folder)).collect()
913 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
914 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
915 self.as_ref().map(|t| t.fold_with(folder))
919 macro_rules! CloneImpls {
920 (<$lt_tcx:tt> $($ty:ty),+) => {
922 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
923 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
932 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
933 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
934 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>
937 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
938 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
940 field: self.field.fold_with(folder),
941 pattern: self.pattern.fold_with(folder)
946 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
947 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
948 folder.fold_pattern(self)
951 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
953 ty: self.ty.fold_with(folder),
954 span: self.span.fold_with(folder),
955 kind: self.kind.fold_with(folder)
960 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
961 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
962 folder.fold_pattern_kind(self)
965 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
967 PatternKind::Wild => PatternKind::Wild,
968 PatternKind::Binding {
975 } => PatternKind::Binding {
976 mutability: mutability.fold_with(folder),
977 name: name.fold_with(folder),
978 mode: mode.fold_with(folder),
979 var: var.fold_with(folder),
980 ty: ty.fold_with(folder),
981 subpattern: subpattern.fold_with(folder),
983 PatternKind::Variant {
988 } => PatternKind::Variant {
989 adt_def: adt_def.fold_with(folder),
990 substs: substs.fold_with(folder),
991 variant_index: variant_index.fold_with(folder),
992 subpatterns: subpatterns.fold_with(folder)
996 } => PatternKind::Leaf {
997 subpatterns: subpatterns.fold_with(folder),
1001 } => PatternKind::Deref {
1002 subpattern: subpattern.fold_with(folder),
1004 PatternKind::Constant {
1006 } => PatternKind::Constant {
1007 value: value.fold_with(folder)
1009 PatternKind::Range {
1013 } => PatternKind::Range {
1014 lo: lo.fold_with(folder),
1015 hi: hi.fold_with(folder),
1018 PatternKind::Slice {
1022 } => PatternKind::Slice {
1023 prefix: prefix.fold_with(folder),
1024 slice: slice.fold_with(folder),
1025 suffix: suffix.fold_with(folder)
1027 PatternKind::Array {
1031 } => PatternKind::Array {
1032 prefix: prefix.fold_with(folder),
1033 slice: slice.fold_with(folder),
1034 suffix: suffix.fold_with(folder)
1040 pub fn compare_const_vals<'a, 'tcx>(
1041 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1042 a: &'tcx ty::Const<'tcx>,
1043 b: &'tcx ty::Const<'tcx>,
1044 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1045 ) -> Option<Ordering> {
1046 trace!("compare_const_vals: {:?}, {:?}", a, b);
1048 let from_bool = |v: bool| {
1050 Some(Ordering::Equal)
1056 let fallback = || from_bool(a == b);
1058 // Use the fallback if any type differs
1059 if a.ty != b.ty || a.ty != ty.value {
1063 // FIXME: This should use assert_bits(ty) instead of use_bits
1064 // but triggers possibly bugs due to mismatching of arrays and slices
1065 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1066 use ::rustc_apfloat::Float;
1067 return match ty.value.sty {
1068 ty::TyFloat(ast::FloatTy::F32) => {
1069 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1070 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1073 ty::TyFloat(ast::FloatTy::F64) => {
1074 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1075 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1079 let a = interpret::sign_extend(tcx, a, ty.value).expect("layout error for TyInt");
1080 let b = interpret::sign_extend(tcx, b, ty.value).expect("layout error for TyInt");
1081 Some((a as i128).cmp(&(b as i128)))
1083 _ => Some(a.cmp(&b)),
1087 if let ty::TyRef(_, rty, _) = ty.value.sty {
1088 if let ty::TyStr = rty.sty {
1089 match (a.to_byval_value(), b.to_byval_value()) {
1091 Some(Value::ScalarPair(
1095 Some(Value::ScalarPair(
1099 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1100 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1101 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1103 let map = tcx.alloc_map.lock();
1104 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1105 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1106 if alloc_a.bytes.len() as u128 == len_a {
1107 return from_bool(alloc_a == alloc_b);
1121 // FIXME: Combine with rustc_mir::hair::cx::const_eval_literal
1122 fn lit_to_const<'a, 'tcx>(lit: &'tcx ast::LitKind,
1123 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1126 -> Result<&'tcx ty::Const<'tcx>, ()> {
1129 use rustc::mir::interpret::*;
1130 let lit = match *lit {
1131 LitKind::Str(ref s, _) => {
1133 let id = tcx.allocate_bytes(s.as_bytes());
1134 let value = Scalar::Ptr(id.into()).to_value_with_len(s.len() as u64, tcx);
1135 ConstValue::from_byval_value(value)
1137 LitKind::ByteStr(ref data) => {
1138 let id = tcx.allocate_bytes(data);
1139 ConstValue::Scalar(Scalar::Ptr(id.into()))
1141 LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
1145 LitKind::Int(n, _) => {
1150 let ity = match ty.sty {
1151 ty::TyInt(IntTy::Isize) => Int::Signed(tcx.sess.target.isize_ty),
1152 ty::TyInt(other) => Int::Signed(other),
1153 ty::TyUint(UintTy::Usize) => Int::Unsigned(tcx.sess.target.usize_ty),
1154 ty::TyUint(other) => Int::Unsigned(other),
1157 // This converts from LitKind::Int (which is sign extended) to
1158 // Scalar::Bytes (which is zero extended)
1160 // FIXME(oli-obk): are these casts correct?
1161 Int::Signed(IntTy::I8) if neg =>
1162 (n as i8).overflowing_neg().0 as u8 as u128,
1163 Int::Signed(IntTy::I16) if neg =>
1164 (n as i16).overflowing_neg().0 as u16 as u128,
1165 Int::Signed(IntTy::I32) if neg =>
1166 (n as i32).overflowing_neg().0 as u32 as u128,
1167 Int::Signed(IntTy::I64) if neg =>
1168 (n as i64).overflowing_neg().0 as u64 as u128,
1169 Int::Signed(IntTy::I128) if neg =>
1170 (n as i128).overflowing_neg().0 as u128,
1171 Int::Signed(IntTy::I8) | Int::Unsigned(UintTy::U8) => n as u8 as u128,
1172 Int::Signed(IntTy::I16) | Int::Unsigned(UintTy::U16) => n as u16 as u128,
1173 Int::Signed(IntTy::I32) | Int::Unsigned(UintTy::U32) => n as u32 as u128,
1174 Int::Signed(IntTy::I64) | Int::Unsigned(UintTy::U64) => n as u64 as u128,
1175 Int::Signed(IntTy::I128)| Int::Unsigned(UintTy::U128) => n,
1178 let defined = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size.bits() as u8;
1179 ConstValue::Scalar(Scalar::Bits {
1184 LitKind::Float(n, fty) => {
1185 parse_float(n, fty, neg)?
1187 LitKind::FloatUnsuffixed(n) => {
1188 let fty = match ty.sty {
1189 ty::TyFloat(fty) => fty,
1192 parse_float(n, fty, neg)?
1194 LitKind::Bool(b) => ConstValue::Scalar(Scalar::Bits {
1198 LitKind::Char(c) => ConstValue::Scalar(Scalar::Bits {
1203 Ok(ty::Const::from_const_value(tcx, lit, ty))
1206 pub fn parse_float<'tcx>(
1210 ) -> Result<ConstValue<'tcx>, ()> {
1211 let num = num.as_str();
1212 use rustc_apfloat::ieee::{Single, Double};
1213 use rustc_apfloat::Float;
1214 let (bits, defined) = match fty {
1215 ast::FloatTy::F32 => {
1216 num.parse::<f32>().map_err(|_| ())?;
1217 let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1218 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1225 ast::FloatTy::F64 => {
1226 num.parse::<f64>().map_err(|_| ())?;
1227 let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1228 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1237 Ok(ConstValue::Scalar(Scalar::Bits { bits, defined }))