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_field, const_variant_index};
21 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
22 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
23 use rustc::ty::{self, CanonicalTy, 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> {
70 user_ty: CanonicalTy<'tcx>,
71 subpattern: Pattern<'tcx>,
74 /// x, ref x, x @ P, etc
76 mutability: Mutability,
78 mode: BindingMode<'tcx>,
81 subpattern: Option<Pattern<'tcx>>,
84 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
86 adt_def: &'tcx AdtDef,
87 substs: &'tcx Substs<'tcx>,
89 subpatterns: Vec<FieldPattern<'tcx>>,
92 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
94 subpatterns: Vec<FieldPattern<'tcx>>,
97 /// box P, &P, &mut P, etc
99 subpattern: Pattern<'tcx>,
103 value: &'tcx ty::Const<'tcx>,
107 lo: &'tcx ty::Const<'tcx>,
108 hi: &'tcx ty::Const<'tcx>,
113 /// matches against a slice, checking the length and extracting elements.
114 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
115 /// e.g. `&[ref xs..]`.
117 prefix: Vec<Pattern<'tcx>>,
118 slice: Option<Pattern<'tcx>>,
119 suffix: Vec<Pattern<'tcx>>,
122 /// fixed match against an array, irrefutable
124 prefix: Vec<Pattern<'tcx>>,
125 slice: Option<Pattern<'tcx>>,
126 suffix: Vec<Pattern<'tcx>>,
130 impl<'tcx> fmt::Display for Pattern<'tcx> {
131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133 PatternKind::Wild => write!(f, "_"),
134 PatternKind::AscribeUserType { ref subpattern, .. } =>
135 write!(f, "{}: _", subpattern),
136 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
137 let is_mut = match mode {
138 BindingMode::ByValue => mutability == Mutability::Mut,
139 BindingMode::ByRef(_, bk) => {
141 match bk { BorrowKind::Mut { .. } => true, _ => false }
147 write!(f, "{}", name)?;
148 if let Some(ref subpattern) = *subpattern {
149 write!(f, " @ {}", subpattern)?;
153 PatternKind::Variant { ref subpatterns, .. } |
154 PatternKind::Leaf { ref subpatterns } => {
155 let variant = match *self.kind {
156 PatternKind::Variant { adt_def, variant_index, .. } => {
157 Some(&adt_def.variants[variant_index])
159 _ => if let ty::Adt(adt, _) = self.ty.sty {
161 Some(&adt.variants[0])
170 let mut first = true;
171 let mut start_or_continue = || if first { first = false; "" } else { ", " };
173 if let Some(variant) = variant {
174 write!(f, "{}", variant.name)?;
176 // Only for Adt we can have `S {...}`,
177 // which we handle separately here.
178 if variant.ctor_kind == CtorKind::Fictive {
182 for p in subpatterns {
183 if let PatternKind::Wild = *p.pattern.kind {
186 let name = variant.fields[p.field.index()].ident;
187 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
191 if printed < variant.fields.len() {
192 write!(f, "{}..", start_or_continue())?;
195 return write!(f, " }}");
199 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
200 if num_fields != 0 || variant.is_none() {
202 for i in 0..num_fields {
203 write!(f, "{}", start_or_continue())?;
205 // Common case: the field is where we expect it.
206 if let Some(p) = subpatterns.get(i) {
207 if p.field.index() == i {
208 write!(f, "{}", p.pattern)?;
213 // Otherwise, we have to go looking for it.
214 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
215 write!(f, "{}", p.pattern)?;
225 PatternKind::Deref { ref subpattern } => {
227 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
228 ty::Ref(_, _, mutbl) => {
230 if mutbl == hir::MutMutable {
234 _ => bug!("{} is a bad Deref pattern type", self.ty)
236 write!(f, "{}", subpattern)
238 PatternKind::Constant { value } => {
239 fmt_const_val(f, value)
241 PatternKind::Range { lo, hi, ty: _, end } => {
242 fmt_const_val(f, lo)?;
244 RangeEnd::Included => write!(f, "..=")?,
245 RangeEnd::Excluded => write!(f, "..")?,
249 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
250 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
251 let mut first = true;
252 let mut start_or_continue = || if first { first = false; "" } else { ", " };
255 write!(f, "{}{}", start_or_continue(), p)?;
257 if let Some(ref slice) = *slice {
258 write!(f, "{}", start_or_continue())?;
260 PatternKind::Wild => {}
261 _ => write!(f, "{}", slice)?
266 write!(f, "{}{}", start_or_continue(), p)?;
274 pub struct PatternContext<'a, 'tcx: 'a> {
275 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
276 pub param_env: ty::ParamEnv<'tcx>,
277 pub tables: &'a ty::TypeckTables<'tcx>,
278 pub substs: &'tcx Substs<'tcx>,
279 pub errors: Vec<PatternError>,
282 impl<'a, 'tcx> Pattern<'tcx> {
283 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
284 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
285 tables: &'a ty::TypeckTables<'tcx>,
286 pat: &'tcx hir::Pat) -> Self {
287 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
288 let result = pcx.lower_pattern(pat);
289 if !pcx.errors.is_empty() {
290 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
291 tcx.sess.delay_span_bug(pat.span, &msg);
293 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
298 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
299 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
300 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
301 tables: &'a ty::TypeckTables<'tcx>) -> Self {
304 param_env: param_env_and_substs.param_env,
306 substs: param_env_and_substs.value,
311 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
312 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
313 // pattern has the type that results *after* dereferencing. For example, in this code:
316 // match &&Some(0i32) {
317 // Some(n) => { ... },
322 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
323 // determined in rustc_typeck::check::match). The adjustments would be
325 // `vec![&&Option<i32>, &Option<i32>]`.
327 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
328 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
329 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
330 // gets the least-dereferenced type).
331 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
338 .fold(unadjusted_pat, |pat, ref_ty| {
339 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
343 kind: Box::new(PatternKind::Deref { subpattern: pat }),
349 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
350 let mut ty = self.tables.node_id_to_type(pat.hir_id);
352 let kind = match pat.node {
353 PatKind::Wild => PatternKind::Wild,
355 PatKind::Lit(ref value) => self.lower_lit(value),
357 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
358 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
359 (PatternKind::Constant { value: lo },
360 PatternKind::Constant { value: hi }) => {
361 use std::cmp::Ordering;
362 let cmp = compare_const_vals(
366 self.param_env.and(ty),
369 (RangeEnd::Excluded, Some(Ordering::Less)) =>
370 PatternKind::Range { lo, hi, ty, end },
371 (RangeEnd::Excluded, _) => {
376 "lower range bound must be less than upper",
380 (RangeEnd::Included, Some(Ordering::Equal)) => {
381 PatternKind::Constant { value: lo }
383 (RangeEnd::Included, Some(Ordering::Less)) => {
384 PatternKind::Range { lo, hi, ty, end }
386 (RangeEnd::Included, _) => {
387 let mut err = struct_span_err!(
391 "lower range bound must be less than or equal to upper"
395 "lower bound larger than upper bound",
397 if self.tcx.sess.teach(&err.get_code().unwrap()) {
398 err.note("When matching against a range, the compiler \
399 verifies that the range is non-empty. Range \
400 patterns include both end-points, so this is \
401 equivalent to requiring the start of the range \
402 to be less than or equal to the end of the range.");
409 _ => PatternKind::Wild
413 PatKind::Path(ref qpath) => {
414 return self.lower_path(qpath, pat.hir_id, pat.span);
417 PatKind::Ref(ref subpattern, _) |
418 PatKind::Box(ref subpattern) => {
419 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
422 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
426 subpattern: Pattern {
429 kind: Box::new(self.slice_or_array_pattern(
430 pat.span, ty, prefix, slice, suffix))
435 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
436 ty::Error => { // Avoid ICE
437 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
442 "unexpanded type for vector pattern: {:?}",
447 PatKind::Tuple(ref subpatterns, ddpos) => {
449 ty::Tuple(ref tys) => {
452 .enumerate_and_adjust(tys.len(), ddpos)
453 .map(|(i, subpattern)| FieldPattern {
454 field: Field::new(i),
455 pattern: self.lower_pattern(subpattern)
459 PatternKind::Leaf { subpatterns: subpatterns }
461 ty::Error => { // Avoid ICE (#50577)
462 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
464 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
468 PatKind::Binding(_, id, ident, ref sub) => {
469 let var_ty = self.tables.node_id_to_type(pat.hir_id);
470 let region = match var_ty.sty {
471 ty::Ref(r, _, _) => Some(r),
472 ty::Error => { // Avoid ICE
473 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
477 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
478 .expect("missing binding mode");
479 let (mutability, mode) = match bm {
480 ty::BindByValue(hir::MutMutable) =>
481 (Mutability::Mut, BindingMode::ByValue),
482 ty::BindByValue(hir::MutImmutable) =>
483 (Mutability::Not, BindingMode::ByValue),
484 ty::BindByReference(hir::MutMutable) =>
485 (Mutability::Not, BindingMode::ByRef(
486 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
487 ty::BindByReference(hir::MutImmutable) =>
488 (Mutability::Not, BindingMode::ByRef(
489 region.unwrap(), BorrowKind::Shared)),
492 // A ref x pattern is the same node used for x, and as such it has
493 // x's type, which is &T, where we want T (the type being matched).
494 if let ty::BindByReference(_) = bm {
495 if let ty::Ref(_, rty, _) = ty.sty {
498 bug!("`ref {}` has wrong type {}", ident, ty);
502 PatternKind::Binding {
508 subpattern: self.lower_opt_pattern(sub),
512 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
513 let def = self.tables.qpath_def(qpath, pat.hir_id);
514 let adt_def = match ty.sty {
515 ty::Adt(adt_def, _) => adt_def,
516 ty::Error => { // Avoid ICE (#50585)
517 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
519 _ => span_bug!(pat.span,
520 "tuple struct pattern not applied to an ADT {:?}",
523 let variant_def = adt_def.variant_of_def(def);
527 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
528 .map(|(i, field)| FieldPattern {
529 field: Field::new(i),
530 pattern: self.lower_pattern(field),
533 self.lower_variant_or_leaf(def, pat.span, ty, subpatterns)
536 PatKind::Struct(ref qpath, ref fields, _) => {
537 let def = self.tables.qpath_def(qpath, pat.hir_id);
542 field: Field::new(self.tcx.field_index(field.node.id,
544 pattern: self.lower_pattern(&field.node.pat),
549 self.lower_variant_or_leaf(def, pat.span, ty, subpatterns)
556 kind: Box::new(kind),
560 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
561 pats.iter().map(|p| self.lower_pattern(p)).collect()
564 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
566 pat.as_ref().map(|p| self.lower_pattern(p))
569 fn flatten_nested_slice_patterns(
571 prefix: Vec<Pattern<'tcx>>,
572 slice: Option<Pattern<'tcx>>,
573 suffix: Vec<Pattern<'tcx>>)
574 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
576 let orig_slice = match slice {
577 Some(orig_slice) => orig_slice,
578 None => return (prefix, slice, suffix)
580 let orig_prefix = prefix;
581 let orig_suffix = suffix;
583 // dance because of intentional borrow-checker stupidity.
584 let kind = *orig_slice.kind;
586 PatternKind::Slice { prefix, slice, mut suffix } |
587 PatternKind::Array { prefix, slice, mut suffix } => {
588 let mut orig_prefix = orig_prefix;
590 orig_prefix.extend(prefix);
591 suffix.extend(orig_suffix);
593 (orig_prefix, slice, suffix)
596 (orig_prefix, Some(Pattern {
597 kind: box kind, ..orig_slice
603 fn slice_or_array_pattern(
607 prefix: &'tcx [P<hir::Pat>],
608 slice: &'tcx Option<P<hir::Pat>>,
609 suffix: &'tcx [P<hir::Pat>])
612 let prefix = self.lower_patterns(prefix);
613 let slice = self.lower_opt_pattern(slice);
614 let suffix = self.lower_patterns(suffix);
615 let (prefix, slice, suffix) =
616 self.flatten_nested_slice_patterns(prefix, slice, suffix);
620 // matching a slice or fixed-length array
621 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
624 ty::Array(_, len) => {
625 // fixed-length array
626 let len = len.unwrap_usize(self.tcx);
627 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
628 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
632 span_bug!(span, "bad slice pattern type {:?}", ty);
637 fn lower_variant_or_leaf(
642 subpatterns: Vec<FieldPattern<'tcx>>)
646 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
647 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
648 let adt_def = self.tcx.adt_def(enum_id);
649 if adt_def.is_enum() {
650 let substs = match ty.sty {
652 ty::FnDef(_, substs) => substs,
653 ty::Error => { // Avoid ICE (#50585)
654 return PatternKind::Wild;
656 _ => bug!("inappropriate type for def: {:?}", ty.sty),
658 PatternKind::Variant {
661 variant_index: adt_def.variant_index_with_id(variant_id),
665 PatternKind::Leaf { subpatterns: subpatterns }
669 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
670 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
671 PatternKind::Leaf { subpatterns: subpatterns }
675 self.errors.push(PatternError::NonConstPath(span));
681 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
682 /// it to `const_to_pat`. Any other path (like enum variants without fields)
683 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
684 fn lower_path(&mut self,
689 let ty = self.tables.node_id_to_type(id);
690 let def = self.tables.qpath_def(qpath, id);
691 let is_associated_const = match def {
692 Def::AssociatedConst(_) => true,
695 let kind = match def {
696 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
697 let substs = self.tables.node_substs(id);
698 match ty::Instance::resolve(
709 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
711 return self.const_to_pat(instance, value, id, span)
716 "could not evaluate constant pattern",
723 self.errors.push(if is_associated_const {
724 PatternError::AssociatedConstInPattern(span)
726 PatternError::StaticInPattern(span)
732 _ => self.lower_variant_or_leaf(def, span, ty, vec![]),
738 kind: Box::new(kind),
742 /// Converts literals, paths and negation of literals to patterns.
743 /// The special case for negation exists to allow things like -128i8
744 /// which would overflow if we tried to evaluate 128i8 and then negate
746 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
748 hir::ExprKind::Lit(ref lit) => {
749 let ty = self.tables.expr_ty(expr);
750 match lit_to_const(&lit.node, self.tcx, ty, false) {
752 let instance = ty::Instance::new(
753 self.tables.local_id_root.expect("literal outside any scope"),
756 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
759 if e == LitToConstError::UnparseableFloat {
760 self.errors.push(PatternError::FloatBug);
766 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
767 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
768 let ty = self.tables.expr_ty(expr);
769 let lit = match expr.node {
770 hir::ExprKind::Lit(ref lit) => lit,
771 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
773 match lit_to_const(&lit.node, self.tcx, ty, true) {
775 let instance = ty::Instance::new(
776 self.tables.local_id_root.expect("literal outside any scope"),
779 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
782 if e == LitToConstError::UnparseableFloat {
783 self.errors.push(PatternError::FloatBug);
789 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
793 /// Converts an evaluated constant to a pattern (if possible).
794 /// This means aggregate values (like structs and enums) are converted
795 /// to a pattern that matches the value (as if you'd compare via eq).
798 instance: ty::Instance<'tcx>,
799 cv: &'tcx ty::Const<'tcx>,
803 debug!("const_to_pat: cv={:#?}", cv);
804 let adt_subpattern = |i, variant_opt| {
805 let field = Field::new(i);
806 let val = const_field(
807 self.tcx, self.param_env, instance,
808 variant_opt, field, cv,
809 ).expect("field access failed");
810 self.const_to_pat(instance, val, id, span)
812 let adt_subpatterns = |n, variant_opt| {
814 let field = Field::new(i);
817 pattern: adt_subpattern(i, variant_opt),
819 }).collect::<Vec<_>>()
821 let kind = match cv.ty.sty {
823 let id = self.tcx.hir.hir_to_node_id(id);
825 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
828 "floating-point types cannot be used in patterns",
830 PatternKind::Constant {
834 ty::Adt(adt_def, _) if adt_def.is_union() => {
835 // Matching on union fields is unsafe, we can't hide it in constants
836 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
839 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
840 let msg = format!("to use a constant of type `{}` in a pattern, \
841 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
842 self.tcx.item_path_str(adt_def.did),
843 self.tcx.item_path_str(adt_def.did));
844 self.tcx.sess.span_err(span, &msg);
847 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
848 let variant_index = const_variant_index(
849 self.tcx, self.param_env, instance, cv
850 ).expect("const_variant_index failed");
851 let subpatterns = adt_subpatterns(
852 adt_def.variants[variant_index].fields.len(),
855 PatternKind::Variant {
862 ty::Adt(adt_def, _) => {
863 let struct_var = adt_def.non_enum_variant();
865 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
868 ty::Tuple(fields) => {
870 subpatterns: adt_subpatterns(fields.len(), None),
875 prefix: (0..n.unwrap_usize(self.tcx))
876 .map(|i| adt_subpattern(i as usize, None))
883 PatternKind::Constant {
892 kind: Box::new(kind),
897 pub trait PatternFoldable<'tcx> : Sized {
898 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
899 self.super_fold_with(folder)
902 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
905 pub trait PatternFolder<'tcx> : Sized {
906 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
907 pattern.super_fold_with(self)
910 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
911 kind.super_fold_with(self)
916 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
917 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
918 let content: T = (**self).fold_with(folder);
923 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
924 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
925 self.iter().map(|t| t.fold_with(folder)).collect()
929 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
930 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
931 self.as_ref().map(|t| t.fold_with(folder))
935 macro_rules! CloneImpls {
936 (<$lt_tcx:tt> $($ty:ty),+) => {
938 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
939 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
948 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
949 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
950 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, CanonicalTy<'tcx>
953 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
954 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
956 field: self.field.fold_with(folder),
957 pattern: self.pattern.fold_with(folder)
962 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
963 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
964 folder.fold_pattern(self)
967 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
969 ty: self.ty.fold_with(folder),
970 span: self.span.fold_with(folder),
971 kind: self.kind.fold_with(folder)
976 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
977 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
978 folder.fold_pattern_kind(self)
981 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
983 PatternKind::Wild => PatternKind::Wild,
984 PatternKind::AscribeUserType {
987 } => PatternKind::AscribeUserType {
988 subpattern: subpattern.fold_with(folder),
989 user_ty: user_ty.fold_with(folder),
991 PatternKind::Binding {
998 } => PatternKind::Binding {
999 mutability: mutability.fold_with(folder),
1000 name: name.fold_with(folder),
1001 mode: mode.fold_with(folder),
1002 var: var.fold_with(folder),
1003 ty: ty.fold_with(folder),
1004 subpattern: subpattern.fold_with(folder),
1006 PatternKind::Variant {
1011 } => PatternKind::Variant {
1012 adt_def: adt_def.fold_with(folder),
1013 substs: substs.fold_with(folder),
1014 variant_index: variant_index.fold_with(folder),
1015 subpatterns: subpatterns.fold_with(folder)
1019 } => PatternKind::Leaf {
1020 subpatterns: subpatterns.fold_with(folder),
1022 PatternKind::Deref {
1024 } => PatternKind::Deref {
1025 subpattern: subpattern.fold_with(folder),
1027 PatternKind::Constant {
1029 } => PatternKind::Constant {
1030 value: value.fold_with(folder)
1032 PatternKind::Range {
1037 } => PatternKind::Range {
1038 lo: lo.fold_with(folder),
1039 hi: hi.fold_with(folder),
1040 ty: ty.fold_with(folder),
1043 PatternKind::Slice {
1047 } => PatternKind::Slice {
1048 prefix: prefix.fold_with(folder),
1049 slice: slice.fold_with(folder),
1050 suffix: suffix.fold_with(folder)
1052 PatternKind::Array {
1056 } => PatternKind::Array {
1057 prefix: prefix.fold_with(folder),
1058 slice: slice.fold_with(folder),
1059 suffix: suffix.fold_with(folder)
1065 pub fn compare_const_vals<'a, 'tcx>(
1066 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1067 a: &'tcx ty::Const<'tcx>,
1068 b: &'tcx ty::Const<'tcx>,
1069 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1070 ) -> Option<Ordering> {
1071 trace!("compare_const_vals: {:?}, {:?}", a, b);
1073 let from_bool = |v: bool| {
1075 Some(Ordering::Equal)
1081 let fallback = || from_bool(a == b);
1083 // Use the fallback if any type differs
1084 if a.ty != b.ty || a.ty != ty.value {
1088 // FIXME: This should use assert_bits(ty) instead of use_bits
1089 // but triggers possibly bugs due to mismatching of arrays and slices
1090 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1091 use ::rustc_apfloat::Float;
1092 return match ty.value.sty {
1093 ty::Float(ast::FloatTy::F32) => {
1094 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1095 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1098 ty::Float(ast::FloatTy::F64) => {
1099 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1100 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1104 let layout = tcx.layout_of(ty).ok()?;
1105 assert!(layout.abi.is_signed());
1106 let a = sign_extend(a, layout.size);
1107 let b = sign_extend(b, layout.size);
1108 Some((a as i128).cmp(&(b as i128)))
1110 _ => Some(a.cmp(&b)),
1114 if let ty::Ref(_, rty, _) = ty.value.sty {
1115 if let ty::Str = rty.sty {
1116 match (a.val, b.val) {
1118 ConstValue::ScalarPair(
1122 ConstValue::ScalarPair(
1126 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1127 let len_a = len_a.not_undef().ok();
1128 let len_b = len_b.not_undef().ok();
1129 if len_a.is_none() || len_b.is_none() {
1130 tcx.sess.struct_err("str slice len is undef").delay_as_bug();
1134 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1135 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1137 let map = tcx.alloc_map.lock();
1138 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1139 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1140 if alloc_a.bytes.len() as u128 == len_a {
1141 return from_bool(alloc_a == alloc_b);
1155 #[derive(PartialEq)]
1156 enum LitToConstError {
1161 // FIXME: Combine with rustc_mir::hair::cx::const_eval_literal
1162 fn lit_to_const<'a, 'tcx>(lit: &'tcx ast::LitKind,
1163 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1166 -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
1169 use rustc::mir::interpret::*;
1170 let lit = match *lit {
1171 LitKind::Str(ref s, _) => {
1173 let id = tcx.allocate_bytes(s.as_bytes());
1174 ConstValue::new_slice(Scalar::Ptr(id.into()), s.len() as u64, tcx)
1176 LitKind::ByteStr(ref data) => {
1177 let id = tcx.allocate_bytes(data);
1178 ConstValue::Scalar(Scalar::Ptr(id.into()))
1180 LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
1184 LitKind::Int(n, _) => {
1189 let ity = match ty.sty {
1190 ty::Int(IntTy::Isize) => Int::Signed(tcx.sess.target.isize_ty),
1191 ty::Int(other) => Int::Signed(other),
1192 ty::Uint(UintTy::Usize) => Int::Unsigned(tcx.sess.target.usize_ty),
1193 ty::Uint(other) => Int::Unsigned(other),
1194 ty::Error => { // Avoid ICE (#51963)
1195 return Err(LitToConstError::Propagated);
1197 _ => bug!("literal integer type with bad type ({:?})", ty.sty),
1199 // This converts from LitKind::Int (which is sign extended) to
1200 // Scalar::Bytes (which is zero extended)
1202 // FIXME(oli-obk): are these casts correct?
1203 Int::Signed(IntTy::I8) if neg =>
1204 (n as i8).overflowing_neg().0 as u8 as u128,
1205 Int::Signed(IntTy::I16) if neg =>
1206 (n as i16).overflowing_neg().0 as u16 as u128,
1207 Int::Signed(IntTy::I32) if neg =>
1208 (n as i32).overflowing_neg().0 as u32 as u128,
1209 Int::Signed(IntTy::I64) if neg =>
1210 (n as i64).overflowing_neg().0 as u64 as u128,
1211 Int::Signed(IntTy::I128) if neg =>
1212 (n as i128).overflowing_neg().0 as u128,
1213 Int::Signed(IntTy::I8) | Int::Unsigned(UintTy::U8) => n as u8 as u128,
1214 Int::Signed(IntTy::I16) | Int::Unsigned(UintTy::U16) => n as u16 as u128,
1215 Int::Signed(IntTy::I32) | Int::Unsigned(UintTy::U32) => n as u32 as u128,
1216 Int::Signed(IntTy::I64) | Int::Unsigned(UintTy::U64) => n as u64 as u128,
1217 Int::Signed(IntTy::I128)| Int::Unsigned(UintTy::U128) => n,
1220 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size.bytes() as u8;
1221 ConstValue::Scalar(Scalar::Bits {
1226 LitKind::Float(n, fty) => {
1227 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1229 LitKind::FloatUnsuffixed(n) => {
1230 let fty = match ty.sty {
1231 ty::Float(fty) => fty,
1234 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1236 LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
1237 LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
1239 Ok(ty::Const::from_const_value(tcx, lit, ty))
1242 pub fn parse_float<'tcx>(
1246 ) -> Result<ConstValue<'tcx>, ()> {
1247 let num = num.as_str();
1248 use rustc_apfloat::ieee::{Single, Double};
1249 use rustc_apfloat::Float;
1250 let (bits, size) = match fty {
1251 ast::FloatTy::F32 => {
1252 num.parse::<f32>().map_err(|_| ())?;
1253 let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1254 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1261 ast::FloatTy::F64 => {
1262 num.parse::<f64>().map_err(|_| ())?;
1263 let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1264 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1273 Ok(ConstValue::Scalar(Scalar::Bits { bits, size }))