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};
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::ExprKind::Lit(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 if e == LitToConstError::UnparseableFloat {
748 self.errors.push(PatternError::FloatBug);
754 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
755 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
756 let ty = self.tables.expr_ty(expr);
757 let lit = match expr.node {
758 hir::ExprKind::Lit(ref lit) => lit,
759 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
761 match lit_to_const(&lit.node, self.tcx, ty, true) {
763 let instance = ty::Instance::new(
764 self.tables.local_id_root.expect("literal outside any scope"),
767 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
770 if e == LitToConstError::UnparseableFloat {
771 self.errors.push(PatternError::FloatBug);
777 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
781 /// Converts an evaluated constant to a pattern (if possible).
782 /// This means aggregate values (like structs and enums) are converted
783 /// to a pattern that matches the value (as if you'd compare via eq).
786 instance: ty::Instance<'tcx>,
787 cv: &'tcx ty::Const<'tcx>,
791 debug!("const_to_pat: cv={:#?}", cv);
792 let adt_subpattern = |i, variant_opt| {
793 let field = Field::new(i);
794 let val = const_val_field(
795 self.tcx, self.param_env, instance,
796 variant_opt, field, cv,
797 ).expect("field access failed");
798 self.const_to_pat(instance, val, id, span)
800 let adt_subpatterns = |n, variant_opt| {
802 let field = Field::new(i);
805 pattern: adt_subpattern(i, variant_opt),
807 }).collect::<Vec<_>>()
809 let kind = match cv.ty.sty {
811 let id = self.tcx.hir.hir_to_node_id(id);
813 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
816 "floating-point types cannot be used in patterns",
818 PatternKind::Constant {
822 ty::TyAdt(adt_def, _) if adt_def.is_union() => {
823 // Matching on union fields is unsafe, we can't hide it in constants
824 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
827 ty::TyAdt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
828 let msg = format!("to use a constant of type `{}` in a pattern, \
829 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
830 self.tcx.item_path_str(adt_def.did),
831 self.tcx.item_path_str(adt_def.did));
832 self.tcx.sess.span_err(span, &msg);
835 ty::TyAdt(adt_def, substs) if adt_def.is_enum() => {
836 let variant_index = const_variant_index(
837 self.tcx, self.param_env, instance, cv
838 ).expect("const_variant_index failed");
839 let subpatterns = adt_subpatterns(
840 adt_def.variants[variant_index].fields.len(),
843 PatternKind::Variant {
850 ty::TyAdt(adt_def, _) => {
851 let struct_var = adt_def.non_enum_variant();
853 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
856 ty::TyTuple(fields) => {
858 subpatterns: adt_subpatterns(fields.len(), None),
861 ty::TyArray(_, n) => {
863 prefix: (0..n.unwrap_usize(self.tcx))
864 .map(|i| adt_subpattern(i as usize, None))
871 PatternKind::Constant {
880 kind: Box::new(kind),
885 pub trait PatternFoldable<'tcx> : Sized {
886 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
887 self.super_fold_with(folder)
890 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
893 pub trait PatternFolder<'tcx> : Sized {
894 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
895 pattern.super_fold_with(self)
898 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
899 kind.super_fold_with(self)
904 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
905 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
906 let content: T = (**self).fold_with(folder);
911 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
912 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
913 self.iter().map(|t| t.fold_with(folder)).collect()
917 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
918 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
919 self.as_ref().map(|t| t.fold_with(folder))
923 macro_rules! CloneImpls {
924 (<$lt_tcx:tt> $($ty:ty),+) => {
926 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
927 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
936 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
937 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
938 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>
941 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
942 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
944 field: self.field.fold_with(folder),
945 pattern: self.pattern.fold_with(folder)
950 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
951 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
952 folder.fold_pattern(self)
955 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
957 ty: self.ty.fold_with(folder),
958 span: self.span.fold_with(folder),
959 kind: self.kind.fold_with(folder)
964 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
965 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
966 folder.fold_pattern_kind(self)
969 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
971 PatternKind::Wild => PatternKind::Wild,
972 PatternKind::Binding {
979 } => PatternKind::Binding {
980 mutability: mutability.fold_with(folder),
981 name: name.fold_with(folder),
982 mode: mode.fold_with(folder),
983 var: var.fold_with(folder),
984 ty: ty.fold_with(folder),
985 subpattern: subpattern.fold_with(folder),
987 PatternKind::Variant {
992 } => PatternKind::Variant {
993 adt_def: adt_def.fold_with(folder),
994 substs: substs.fold_with(folder),
995 variant_index: variant_index.fold_with(folder),
996 subpatterns: subpatterns.fold_with(folder)
1000 } => PatternKind::Leaf {
1001 subpatterns: subpatterns.fold_with(folder),
1003 PatternKind::Deref {
1005 } => PatternKind::Deref {
1006 subpattern: subpattern.fold_with(folder),
1008 PatternKind::Constant {
1010 } => PatternKind::Constant {
1011 value: value.fold_with(folder)
1013 PatternKind::Range {
1017 } => PatternKind::Range {
1018 lo: lo.fold_with(folder),
1019 hi: hi.fold_with(folder),
1022 PatternKind::Slice {
1026 } => PatternKind::Slice {
1027 prefix: prefix.fold_with(folder),
1028 slice: slice.fold_with(folder),
1029 suffix: suffix.fold_with(folder)
1031 PatternKind::Array {
1035 } => PatternKind::Array {
1036 prefix: prefix.fold_with(folder),
1037 slice: slice.fold_with(folder),
1038 suffix: suffix.fold_with(folder)
1044 pub fn compare_const_vals<'a, 'tcx>(
1045 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1046 a: &'tcx ty::Const<'tcx>,
1047 b: &'tcx ty::Const<'tcx>,
1048 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1049 ) -> Option<Ordering> {
1050 trace!("compare_const_vals: {:?}, {:?}", a, b);
1052 let from_bool = |v: bool| {
1054 Some(Ordering::Equal)
1060 let fallback = || from_bool(a == b);
1062 // Use the fallback if any type differs
1063 if a.ty != b.ty || a.ty != ty.value {
1067 // FIXME: This should use assert_bits(ty) instead of use_bits
1068 // but triggers possibly bugs due to mismatching of arrays and slices
1069 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1070 use ::rustc_apfloat::Float;
1071 return match ty.value.sty {
1072 ty::TyFloat(ast::FloatTy::F32) => {
1073 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1074 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1077 ty::TyFloat(ast::FloatTy::F64) => {
1078 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1079 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1083 let layout = tcx.layout_of(ty).ok()?;
1084 let a = interpret::sign_extend(a, layout);
1085 let b = interpret::sign_extend(b, layout);
1086 Some((a as i128).cmp(&(b as i128)))
1088 _ => Some(a.cmp(&b)),
1092 if let ty::TyRef(_, rty, _) = ty.value.sty {
1093 if let ty::TyStr = rty.sty {
1094 match (a.val, b.val) {
1096 ConstValue::ScalarPair(
1100 ConstValue::ScalarPair(
1104 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1105 let len_a = len_a.unwrap_or_err().ok();
1106 let len_b = len_b.unwrap_or_err().ok();
1107 if len_a.is_none() || len_b.is_none() {
1108 tcx.sess.struct_err("str slice len is undef").delay_as_bug();
1112 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1113 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1115 let map = tcx.alloc_map.lock();
1116 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1117 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1118 if alloc_a.bytes.len() as u128 == len_a {
1119 return from_bool(alloc_a == alloc_b);
1133 #[derive(PartialEq)]
1134 enum LitToConstError {
1139 // FIXME: Combine with rustc_mir::hair::cx::const_eval_literal
1140 fn lit_to_const<'a, 'tcx>(lit: &'tcx ast::LitKind,
1141 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1144 -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
1147 use rustc::mir::interpret::*;
1148 let lit = match *lit {
1149 LitKind::Str(ref s, _) => {
1151 let id = tcx.allocate_bytes(s.as_bytes());
1152 let value = Scalar::Ptr(id.into()).to_value_with_len(s.len() as u64, tcx);
1153 ConstValue::from_byval_value(value).unwrap()
1155 LitKind::ByteStr(ref data) => {
1156 let id = tcx.allocate_bytes(data);
1157 ConstValue::Scalar(Scalar::Ptr(id.into()))
1159 LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
1163 LitKind::Int(n, _) => {
1168 let ity = match ty.sty {
1169 ty::TyInt(IntTy::Isize) => Int::Signed(tcx.sess.target.isize_ty),
1170 ty::TyInt(other) => Int::Signed(other),
1171 ty::TyUint(UintTy::Usize) => Int::Unsigned(tcx.sess.target.usize_ty),
1172 ty::TyUint(other) => Int::Unsigned(other),
1173 ty::TyError => { // Avoid ICE (#51963)
1174 return Err(LitToConstError::Propagated);
1176 _ => bug!("literal integer type with bad type ({:?})", ty.sty),
1178 // This converts from LitKind::Int (which is sign extended) to
1179 // Scalar::Bytes (which is zero extended)
1181 // FIXME(oli-obk): are these casts correct?
1182 Int::Signed(IntTy::I8) if neg =>
1183 (n as i8).overflowing_neg().0 as u8 as u128,
1184 Int::Signed(IntTy::I16) if neg =>
1185 (n as i16).overflowing_neg().0 as u16 as u128,
1186 Int::Signed(IntTy::I32) if neg =>
1187 (n as i32).overflowing_neg().0 as u32 as u128,
1188 Int::Signed(IntTy::I64) if neg =>
1189 (n as i64).overflowing_neg().0 as u64 as u128,
1190 Int::Signed(IntTy::I128) if neg =>
1191 (n as i128).overflowing_neg().0 as u128,
1192 Int::Signed(IntTy::I8) | Int::Unsigned(UintTy::U8) => n as u8 as u128,
1193 Int::Signed(IntTy::I16) | Int::Unsigned(UintTy::U16) => n as u16 as u128,
1194 Int::Signed(IntTy::I32) | Int::Unsigned(UintTy::U32) => n as u32 as u128,
1195 Int::Signed(IntTy::I64) | Int::Unsigned(UintTy::U64) => n as u64 as u128,
1196 Int::Signed(IntTy::I128)| Int::Unsigned(UintTy::U128) => n,
1199 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size.bytes() as u8;
1200 ConstValue::Scalar(Scalar::Bits {
1205 LitKind::Float(n, fty) => {
1206 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1208 LitKind::FloatUnsuffixed(n) => {
1209 let fty = match ty.sty {
1210 ty::TyFloat(fty) => fty,
1213 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1215 LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
1216 LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
1218 Ok(ty::Const::from_const_value(tcx, lit, ty))
1221 pub fn parse_float<'tcx>(
1225 ) -> Result<ConstValue<'tcx>, ()> {
1226 let num = num.as_str();
1227 use rustc_apfloat::ieee::{Single, Double};
1228 use rustc_apfloat::Float;
1229 let (bits, size) = match fty {
1230 ast::FloatTy::F32 => {
1231 num.parse::<f32>().map_err(|_| ())?;
1232 let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1233 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1240 ast::FloatTy::F64 => {
1241 num.parse::<f64>().map_err(|_| ())?;
1242 let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1243 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1252 Ok(ConstValue::Scalar(Scalar::Bits { bits, size }))