1 //! Code to validate patterns/matches
6 pub use self::check_match::check_crate;
7 pub(crate) use self::check_match::check_match;
9 use const_eval::{const_field, const_variant_index};
11 use hair::util::UserAnnotatedTyHelpers;
12 use hair::constant::*;
14 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
15 use rustc::mir::{ProjectionElem, UserTypeProjection, UserTypeProjections};
16 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
17 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, Lift};
18 use rustc::ty::{CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, UserTypeAnnotation};
19 use rustc::ty::subst::{Substs, Kind};
20 use rustc::ty::layout::VariantIdx;
21 use rustc::hir::{self, PatKind, RangeEnd};
22 use rustc::hir::def::{Def, CtorKind};
23 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
25 use rustc_data_structures::indexed_vec::Idx;
27 use std::cmp::Ordering;
33 #[derive(Clone, Debug)]
34 pub enum PatternError {
35 AssociatedConstInPattern(Span),
36 StaticInPattern(Span),
41 #[derive(Copy, Clone, Debug)]
42 pub enum BindingMode<'tcx> {
44 ByRef(Region<'tcx>, BorrowKind),
47 #[derive(Clone, Debug)]
48 pub struct FieldPattern<'tcx> {
50 pub pattern: Pattern<'tcx>,
53 #[derive(Clone, Debug)]
54 pub struct Pattern<'tcx> {
57 pub kind: Box<PatternKind<'tcx>>,
61 #[derive(Clone, Debug)]
62 pub(crate) struct PatternTypeProjections<'tcx> {
63 contents: Vec<(PatternTypeProjection<'tcx>, Span)>,
66 impl<'tcx> PatternTypeProjections<'tcx> {
67 pub(crate) fn user_ty(
69 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
70 ) -> UserTypeProjections<'tcx> {
71 UserTypeProjections::from_projections(
74 .map(|(pat_ty_proj, span)| (pat_ty_proj.user_ty(annotations, span), span))
78 pub(crate) fn none() -> Self {
79 PatternTypeProjections { contents: vec![] }
83 mut f: impl FnMut(&PatternTypeProjection<'tcx>) -> PatternTypeProjection<'tcx>)
86 PatternTypeProjections {
87 contents: self.contents
89 .map(|(proj, span)| (f(proj), *span))
93 pub(crate) fn index(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.index()) }
95 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
96 self.map_projs(|pat_ty_proj| pat_ty_proj.subslice(from, to))
99 pub(crate) fn deref(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.deref()) }
101 pub(crate) fn leaf(&self, field: Field) -> Self {
102 self.map_projs(|pat_ty_proj| pat_ty_proj.leaf(field))
105 pub(crate) fn variant(&self,
106 adt_def: &'tcx AdtDef,
107 variant_index: VariantIdx,
108 field: Field) -> Self {
109 self.map_projs(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
112 pub(crate) fn add_user_type(&self, user_ty: &PatternTypeProjection<'tcx>, sp: Span) -> Self {
113 let mut new = self.clone();
114 new.contents.push((user_ty.clone(), sp));
119 #[derive(Clone, Debug)]
120 pub struct PatternTypeProjection<'tcx> {
121 pub base: CanonicalUserTypeAnnotation<'tcx>,
122 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
125 impl<'tcx> PatternTypeProjection<'tcx> {
126 pub(crate) fn index(&self) -> Self {
127 let mut new = self.clone();
128 new.projs.push(ProjectionElem::Index(()));
132 pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
133 let mut new = self.clone();
134 new.projs.push(ProjectionElem::Subslice { from, to });
138 pub(crate) fn deref(&self) -> Self {
139 let mut new = self.clone();
140 new.projs.push(ProjectionElem::Deref);
144 pub(crate) fn leaf(&self, field: Field) -> Self {
145 let mut new = self.clone();
146 new.projs.push(ProjectionElem::Field(field, ()));
150 pub(crate) fn variant(&self,
151 adt_def: &'tcx AdtDef,
152 variant_index: VariantIdx,
153 field: Field) -> Self {
154 let mut new = self.clone();
155 new.projs.push(ProjectionElem::Downcast(adt_def, variant_index));
156 new.projs.push(ProjectionElem::Field(field, ()));
160 pub(crate) fn from_user_type(user_annotation: CanonicalUserTypeAnnotation<'tcx>) -> Self {
162 base: user_annotation,
167 pub(crate) fn user_ty(
169 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
171 ) -> UserTypeProjection<'tcx> {
172 let annotation_index = annotations.push((span, self.base));
174 base: annotation_index,
180 #[derive(Clone, Debug)]
181 pub enum PatternKind<'tcx> {
185 user_ty: PatternTypeProjection<'tcx>,
186 subpattern: Pattern<'tcx>,
190 /// x, ref x, x @ P, etc
192 mutability: Mutability,
194 mode: BindingMode<'tcx>,
197 subpattern: Option<Pattern<'tcx>>,
200 /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
202 adt_def: &'tcx AdtDef,
203 substs: &'tcx Substs<'tcx>,
204 variant_index: VariantIdx,
205 subpatterns: Vec<FieldPattern<'tcx>>,
208 /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
210 subpatterns: Vec<FieldPattern<'tcx>>,
213 /// box P, &P, &mut P, etc
215 subpattern: Pattern<'tcx>,
219 value: &'tcx ty::Const<'tcx>,
222 Range(PatternRange<'tcx>),
224 /// matches against a slice, checking the length and extracting elements.
225 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
226 /// e.g., `&[ref xs..]`.
228 prefix: Vec<Pattern<'tcx>>,
229 slice: Option<Pattern<'tcx>>,
230 suffix: Vec<Pattern<'tcx>>,
233 /// fixed match against an array, irrefutable
235 prefix: Vec<Pattern<'tcx>>,
236 slice: Option<Pattern<'tcx>>,
237 suffix: Vec<Pattern<'tcx>>,
241 #[derive(Clone, Copy, Debug, PartialEq)]
242 pub struct PatternRange<'tcx> {
243 pub lo: &'tcx ty::Const<'tcx>,
244 pub hi: &'tcx ty::Const<'tcx>,
249 impl<'tcx> fmt::Display for Pattern<'tcx> {
250 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
252 PatternKind::Wild => write!(f, "_"),
253 PatternKind::AscribeUserType { ref subpattern, .. } =>
254 write!(f, "{}: _", subpattern),
255 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
256 let is_mut = match mode {
257 BindingMode::ByValue => mutability == Mutability::Mut,
258 BindingMode::ByRef(_, bk) => {
260 match bk { BorrowKind::Mut { .. } => true, _ => false }
266 write!(f, "{}", name)?;
267 if let Some(ref subpattern) = *subpattern {
268 write!(f, " @ {}", subpattern)?;
272 PatternKind::Variant { ref subpatterns, .. } |
273 PatternKind::Leaf { ref subpatterns } => {
274 let variant = match *self.kind {
275 PatternKind::Variant { adt_def, variant_index, .. } => {
276 Some(&adt_def.variants[variant_index])
278 _ => if let ty::Adt(adt, _) = self.ty.sty {
280 Some(&adt.variants[VariantIdx::new(0)])
289 let mut first = true;
290 let mut start_or_continue = || if first { first = false; "" } else { ", " };
292 if let Some(variant) = variant {
293 write!(f, "{}", variant.ident)?;
295 // Only for Adt we can have `S {...}`,
296 // which we handle separately here.
297 if variant.ctor_kind == CtorKind::Fictive {
301 for p in subpatterns {
302 if let PatternKind::Wild = *p.pattern.kind {
305 let name = variant.fields[p.field.index()].ident;
306 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
310 if printed < variant.fields.len() {
311 write!(f, "{}..", start_or_continue())?;
314 return write!(f, " }}");
318 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
319 if num_fields != 0 || variant.is_none() {
321 for i in 0..num_fields {
322 write!(f, "{}", start_or_continue())?;
324 // Common case: the field is where we expect it.
325 if let Some(p) = subpatterns.get(i) {
326 if p.field.index() == i {
327 write!(f, "{}", p.pattern)?;
332 // Otherwise, we have to go looking for it.
333 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
334 write!(f, "{}", p.pattern)?;
344 PatternKind::Deref { ref subpattern } => {
346 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
347 ty::Ref(_, _, mutbl) => {
349 if mutbl == hir::MutMutable {
353 _ => bug!("{} is a bad Deref pattern type", self.ty)
355 write!(f, "{}", subpattern)
357 PatternKind::Constant { value } => {
358 fmt_const_val(f, value)
360 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
361 fmt_const_val(f, lo)?;
363 RangeEnd::Included => write!(f, "..=")?,
364 RangeEnd::Excluded => write!(f, "..")?,
368 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
369 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
370 let mut first = true;
371 let mut start_or_continue = || if first { first = false; "" } else { ", " };
374 write!(f, "{}{}", start_or_continue(), p)?;
376 if let Some(ref slice) = *slice {
377 write!(f, "{}", start_or_continue())?;
379 PatternKind::Wild => {}
380 _ => write!(f, "{}", slice)?
385 write!(f, "{}{}", start_or_continue(), p)?;
393 pub struct PatternContext<'a, 'tcx: 'a> {
394 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
395 pub param_env: ty::ParamEnv<'tcx>,
396 pub tables: &'a ty::TypeckTables<'tcx>,
397 pub substs: &'tcx Substs<'tcx>,
398 pub errors: Vec<PatternError>,
401 impl<'a, 'tcx> Pattern<'tcx> {
402 pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
403 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
404 tables: &'a ty::TypeckTables<'tcx>,
405 pat: &'tcx hir::Pat) -> Self {
406 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
407 let result = pcx.lower_pattern(pat);
408 if !pcx.errors.is_empty() {
409 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
410 tcx.sess.delay_span_bug(pat.span, &msg);
412 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
417 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
418 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
419 param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
420 tables: &'a ty::TypeckTables<'tcx>) -> Self {
423 param_env: param_env_and_substs.param_env,
425 substs: param_env_and_substs.value,
430 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
431 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
432 // pattern has the type that results *after* dereferencing. For example, in this code:
435 // match &&Some(0i32) {
436 // Some(n) => { ... },
441 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
442 // determined in rustc_typeck::check::match). The adjustments would be
444 // `vec![&&Option<i32>, &Option<i32>]`.
446 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
447 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
448 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
449 // gets the least-dereferenced type).
450 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
457 .fold(unadjusted_pat, |pat, ref_ty| {
458 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
462 kind: Box::new(PatternKind::Deref { subpattern: pat }),
468 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
469 let mut ty = self.tables.node_id_to_type(pat.hir_id);
471 let kind = match pat.node {
472 PatKind::Wild => PatternKind::Wild,
474 PatKind::Lit(ref value) => self.lower_lit(value),
476 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
477 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
478 (PatternKind::Constant { value: lo },
479 PatternKind::Constant { value: hi }) => {
480 use std::cmp::Ordering;
481 let cmp = compare_const_vals(
485 self.param_env.and(ty),
488 (RangeEnd::Excluded, Some(Ordering::Less)) =>
489 PatternKind::Range(PatternRange { lo, hi, ty, end }),
490 (RangeEnd::Excluded, _) => {
495 "lower range bound must be less than upper",
499 (RangeEnd::Included, Some(Ordering::Equal)) => {
500 PatternKind::Constant { value: lo }
502 (RangeEnd::Included, Some(Ordering::Less)) => {
503 PatternKind::Range(PatternRange { lo, hi, ty, end })
505 (RangeEnd::Included, _) => {
506 let mut err = struct_span_err!(
510 "lower range bound must be less than or equal to upper"
514 "lower bound larger than upper bound",
516 if self.tcx.sess.teach(&err.get_code().unwrap()) {
517 err.note("When matching against a range, the compiler \
518 verifies that the range is non-empty. Range \
519 patterns include both end-points, so this is \
520 equivalent to requiring the start of the range \
521 to be less than or equal to the end of the range.");
528 _ => PatternKind::Wild
532 PatKind::Path(ref qpath) => {
533 return self.lower_path(qpath, pat.hir_id, pat.span);
536 PatKind::Ref(ref subpattern, _) |
537 PatKind::Box(ref subpattern) => {
538 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
541 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
545 subpattern: Pattern {
548 kind: Box::new(self.slice_or_array_pattern(
549 pat.span, ty, prefix, slice, suffix))
554 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
555 ty::Error => { // Avoid ICE
556 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
561 "unexpanded type for vector pattern: {:?}",
566 PatKind::Tuple(ref subpatterns, ddpos) => {
568 ty::Tuple(ref tys) => {
571 .enumerate_and_adjust(tys.len(), ddpos)
572 .map(|(i, subpattern)| FieldPattern {
573 field: Field::new(i),
574 pattern: self.lower_pattern(subpattern)
578 PatternKind::Leaf { subpatterns }
580 ty::Error => { // Avoid ICE (#50577)
581 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
583 ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
587 PatKind::Binding(_, id, ident, ref sub) => {
588 let var_ty = self.tables.node_id_to_type(pat.hir_id);
589 let region = match var_ty.sty {
590 ty::Ref(r, _, _) => Some(r),
591 ty::Error => { // Avoid ICE
592 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
596 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
597 .expect("missing binding mode");
598 let (mutability, mode) = match bm {
599 ty::BindByValue(hir::MutMutable) =>
600 (Mutability::Mut, BindingMode::ByValue),
601 ty::BindByValue(hir::MutImmutable) =>
602 (Mutability::Not, BindingMode::ByValue),
603 ty::BindByReference(hir::MutMutable) =>
604 (Mutability::Not, BindingMode::ByRef(
605 region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
606 ty::BindByReference(hir::MutImmutable) =>
607 (Mutability::Not, BindingMode::ByRef(
608 region.unwrap(), BorrowKind::Shared)),
611 // A ref x pattern is the same node used for x, and as such it has
612 // x's type, which is &T, where we want T (the type being matched).
613 if let ty::BindByReference(_) = bm {
614 if let ty::Ref(_, rty, _) = ty.sty {
617 bug!("`ref {}` has wrong type {}", ident, ty);
621 PatternKind::Binding {
627 subpattern: self.lower_opt_pattern(sub),
631 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
632 let def = self.tables.qpath_def(qpath, pat.hir_id);
633 let adt_def = match ty.sty {
634 ty::Adt(adt_def, _) => adt_def,
635 ty::Error => { // Avoid ICE (#50585)
636 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
638 _ => span_bug!(pat.span,
639 "tuple struct pattern not applied to an ADT {:?}",
642 let variant_def = adt_def.variant_of_def(def);
646 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
647 .map(|(i, field)| FieldPattern {
648 field: Field::new(i),
649 pattern: self.lower_pattern(field),
653 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
656 PatKind::Struct(ref qpath, ref fields, _) => {
657 let def = self.tables.qpath_def(qpath, pat.hir_id);
662 field: Field::new(self.tcx.field_index(field.node.id,
664 pattern: self.lower_pattern(&field.node.pat),
669 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
676 kind: Box::new(kind),
680 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
681 pats.iter().map(|p| self.lower_pattern(p)).collect()
684 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
686 pat.as_ref().map(|p| self.lower_pattern(p))
689 fn flatten_nested_slice_patterns(
691 prefix: Vec<Pattern<'tcx>>,
692 slice: Option<Pattern<'tcx>>,
693 suffix: Vec<Pattern<'tcx>>)
694 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
696 let orig_slice = match slice {
697 Some(orig_slice) => orig_slice,
698 None => return (prefix, slice, suffix)
700 let orig_prefix = prefix;
701 let orig_suffix = suffix;
703 // dance because of intentional borrow-checker stupidity.
704 let kind = *orig_slice.kind;
706 PatternKind::Slice { prefix, slice, mut suffix } |
707 PatternKind::Array { prefix, slice, mut suffix } => {
708 let mut orig_prefix = orig_prefix;
710 orig_prefix.extend(prefix);
711 suffix.extend(orig_suffix);
713 (orig_prefix, slice, suffix)
716 (orig_prefix, Some(Pattern {
717 kind: box kind, ..orig_slice
723 fn slice_or_array_pattern(
727 prefix: &'tcx [P<hir::Pat>],
728 slice: &'tcx Option<P<hir::Pat>>,
729 suffix: &'tcx [P<hir::Pat>])
732 let prefix = self.lower_patterns(prefix);
733 let slice = self.lower_opt_pattern(slice);
734 let suffix = self.lower_patterns(suffix);
735 let (prefix, slice, suffix) =
736 self.flatten_nested_slice_patterns(prefix, slice, suffix);
740 // matching a slice or fixed-length array
741 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
744 ty::Array(_, len) => {
745 // fixed-length array
746 let len = len.unwrap_usize(self.tcx);
747 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
748 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
752 span_bug!(span, "bad slice pattern type {:?}", ty);
757 fn lower_variant_or_leaf(
763 subpatterns: Vec<FieldPattern<'tcx>>,
764 ) -> PatternKind<'tcx> {
765 let mut kind = match def {
766 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
767 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
768 let adt_def = self.tcx.adt_def(enum_id);
769 if adt_def.is_enum() {
770 let substs = match ty.sty {
772 ty::FnDef(_, substs) => substs,
773 ty::Error => { // Avoid ICE (#50585)
774 return PatternKind::Wild;
776 _ => bug!("inappropriate type for def: {:?}", ty.sty),
778 PatternKind::Variant {
781 variant_index: adt_def.variant_index_with_id(variant_id),
785 PatternKind::Leaf { subpatterns }
789 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
790 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
791 PatternKind::Leaf { subpatterns }
795 self.errors.push(PatternError::NonConstPath(span));
800 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
801 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
802 kind = PatternKind::AscribeUserType {
803 subpattern: Pattern {
806 kind: Box::new(kind),
808 user_ty: PatternTypeProjection::from_user_type(user_ty),
816 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
817 /// it to `const_to_pat`. Any other path (like enum variants without fields)
818 /// is converted to the corresponding pattern via `lower_variant_or_leaf`
819 fn lower_path(&mut self,
824 let ty = self.tables.node_id_to_type(id);
825 let def = self.tables.qpath_def(qpath, id);
826 let is_associated_const = match def {
827 Def::AssociatedConst(_) => true,
830 let kind = match def {
831 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
832 let substs = self.tables.node_substs(id);
833 match ty::Instance::resolve(
844 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
846 let pattern = self.const_to_pat(instance, value, id, span);
847 if !is_associated_const {
851 let user_provided_types = self.tables().user_provided_types();
852 return if let Some(u_ty) = user_provided_types.get(id) {
853 let user_ty = PatternTypeProjection::from_user_type(*u_ty);
857 PatternKind::AscribeUserType {
870 self.tcx.sess.span_err(
872 "could not evaluate constant pattern",
879 self.errors.push(if is_associated_const {
880 PatternError::AssociatedConstInPattern(span)
882 PatternError::StaticInPattern(span)
888 _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
894 kind: Box::new(kind),
898 /// Converts literals, paths and negation of literals to patterns.
899 /// The special case for negation exists to allow things like -128i8
900 /// which would overflow if we tried to evaluate 128i8 and then negate
902 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
904 hir::ExprKind::Lit(ref lit) => {
905 let ty = self.tables.expr_ty(expr);
906 match lit_to_const(&lit.node, self.tcx, ty, false) {
908 let instance = ty::Instance::new(
909 self.tables.local_id_root.expect("literal outside any scope"),
912 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
914 Err(LitToConstError::UnparseableFloat) => {
915 self.errors.push(PatternError::FloatBug);
918 Err(LitToConstError::Reported) => PatternKind::Wild,
921 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
922 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
923 let ty = self.tables.expr_ty(expr);
924 let lit = match expr.node {
925 hir::ExprKind::Lit(ref lit) => lit,
926 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
928 match lit_to_const(&lit.node, self.tcx, ty, true) {
930 let instance = ty::Instance::new(
931 self.tables.local_id_root.expect("literal outside any scope"),
934 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
936 Err(LitToConstError::UnparseableFloat) => {
937 self.errors.push(PatternError::FloatBug);
940 Err(LitToConstError::Reported) => PatternKind::Wild,
943 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
947 /// Converts an evaluated constant to a pattern (if possible).
948 /// This means aggregate values (like structs and enums) are converted
949 /// to a pattern that matches the value (as if you'd compare via eq).
952 instance: ty::Instance<'tcx>,
953 cv: &'tcx ty::Const<'tcx>,
957 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
958 let adt_subpattern = |i, variant_opt| {
959 let field = Field::new(i);
960 let val = const_field(
961 self.tcx, self.param_env, instance,
962 variant_opt, field, cv,
963 ).expect("field access failed");
964 self.const_to_pat(instance, val, id, span)
966 let adt_subpatterns = |n, variant_opt| {
968 let field = Field::new(i);
971 pattern: adt_subpattern(i, variant_opt),
973 }).collect::<Vec<_>>()
975 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
976 let kind = match cv.ty.sty {
978 let id = self.tcx.hir().hir_to_node_id(id);
980 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
983 "floating-point types cannot be used in patterns",
985 PatternKind::Constant {
989 ty::Adt(adt_def, _) if adt_def.is_union() => {
990 // Matching on union fields is unsafe, we can't hide it in constants
991 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
994 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
995 let msg = format!("to use a constant of type `{}` in a pattern, \
996 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
997 self.tcx.item_path_str(adt_def.did),
998 self.tcx.item_path_str(adt_def.did));
999 self.tcx.sess.span_err(span, &msg);
1002 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
1003 let variant_index = const_variant_index(
1004 self.tcx, self.param_env, instance, cv
1005 ).expect("const_variant_index failed");
1006 let subpatterns = adt_subpatterns(
1007 adt_def.variants[variant_index].fields.len(),
1008 Some(variant_index),
1010 PatternKind::Variant {
1017 ty::Adt(adt_def, _) => {
1018 let struct_var = adt_def.non_enum_variant();
1020 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1023 ty::Tuple(fields) => {
1025 subpatterns: adt_subpatterns(fields.len(), None),
1028 ty::Array(_, n) => {
1029 PatternKind::Array {
1030 prefix: (0..n.unwrap_usize(self.tcx))
1031 .map(|i| adt_subpattern(i as usize, None))
1038 PatternKind::Constant {
1047 kind: Box::new(kind),
1052 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1053 fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1057 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1063 pub trait PatternFoldable<'tcx> : Sized {
1064 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1065 self.super_fold_with(folder)
1068 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1071 pub trait PatternFolder<'tcx> : Sized {
1072 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1073 pattern.super_fold_with(self)
1076 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1077 kind.super_fold_with(self)
1082 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1083 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1084 let content: T = (**self).fold_with(folder);
1089 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1090 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1091 self.iter().map(|t| t.fold_with(folder)).collect()
1095 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1096 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1097 self.as_ref().map(|t| t.fold_with(folder))
1101 macro_rules! CloneImpls {
1102 (<$lt_tcx:tt> $($ty:ty),+) => {
1104 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1105 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1114 Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
1115 Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
1116 &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>,
1117 UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1120 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1121 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1123 field: self.field.fold_with(folder),
1124 pattern: self.pattern.fold_with(folder)
1129 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1130 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1131 folder.fold_pattern(self)
1134 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1136 ty: self.ty.fold_with(folder),
1137 span: self.span.fold_with(folder),
1138 kind: self.kind.fold_with(folder)
1143 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1144 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1145 folder.fold_pattern_kind(self)
1148 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1150 PatternKind::Wild => PatternKind::Wild,
1151 PatternKind::AscribeUserType {
1155 } => PatternKind::AscribeUserType {
1156 subpattern: subpattern.fold_with(folder),
1157 user_ty: user_ty.fold_with(folder),
1160 PatternKind::Binding {
1167 } => PatternKind::Binding {
1168 mutability: mutability.fold_with(folder),
1169 name: name.fold_with(folder),
1170 mode: mode.fold_with(folder),
1171 var: var.fold_with(folder),
1172 ty: ty.fold_with(folder),
1173 subpattern: subpattern.fold_with(folder),
1175 PatternKind::Variant {
1180 } => PatternKind::Variant {
1181 adt_def: adt_def.fold_with(folder),
1182 substs: substs.fold_with(folder),
1184 subpatterns: subpatterns.fold_with(folder)
1188 } => PatternKind::Leaf {
1189 subpatterns: subpatterns.fold_with(folder),
1191 PatternKind::Deref {
1193 } => PatternKind::Deref {
1194 subpattern: subpattern.fold_with(folder),
1196 PatternKind::Constant {
1198 } => PatternKind::Constant {
1199 value: value.fold_with(folder)
1201 PatternKind::Range(PatternRange {
1206 }) => PatternKind::Range(PatternRange {
1207 lo: lo.fold_with(folder),
1208 hi: hi.fold_with(folder),
1209 ty: ty.fold_with(folder),
1212 PatternKind::Slice {
1216 } => PatternKind::Slice {
1217 prefix: prefix.fold_with(folder),
1218 slice: slice.fold_with(folder),
1219 suffix: suffix.fold_with(folder)
1221 PatternKind::Array {
1225 } => PatternKind::Array {
1226 prefix: prefix.fold_with(folder),
1227 slice: slice.fold_with(folder),
1228 suffix: suffix.fold_with(folder)
1234 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1235 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1236 a: &'tcx ty::Const<'tcx>,
1237 b: &'tcx ty::Const<'tcx>,
1238 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1239 ) -> Option<Ordering> {
1240 trace!("compare_const_vals: {:?}, {:?}", a, b);
1242 let from_bool = |v: bool| {
1244 Some(Ordering::Equal)
1250 let fallback = || from_bool(a == b);
1252 // Use the fallback if any type differs
1253 if a.ty != b.ty || a.ty != ty.value {
1257 let tcx = tcx.global_tcx();
1258 let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1260 // FIXME: This should use assert_bits(ty) instead of use_bits
1261 // but triggers possibly bugs due to mismatching of arrays and slices
1262 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1263 use ::rustc_apfloat::Float;
1264 return match ty.value.sty {
1265 ty::Float(ast::FloatTy::F32) => {
1266 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1267 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1270 ty::Float(ast::FloatTy::F64) => {
1271 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1272 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1276 let layout = tcx.layout_of(ty).ok()?;
1277 assert!(layout.abi.is_signed());
1278 let a = sign_extend(a, layout.size);
1279 let b = sign_extend(b, layout.size);
1280 Some((a as i128).cmp(&(b as i128)))
1282 _ => Some(a.cmp(&b)),
1286 if let ty::Str = ty.value.sty {
1287 match (a.val, b.val) {
1289 ConstValue::ScalarPair(
1293 ConstValue::ScalarPair(
1297 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1298 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1299 if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1301 let map = tcx.alloc_map.lock();
1302 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1303 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1304 if alloc_a.bytes.len() as u128 == len_a {
1305 return from_bool(alloc_a == alloc_b);