1 //! Validation of patterns/matches.
7 pub(crate) use self::check_match::check_match;
9 use crate::hair::util::UserAnnotatedTyHelpers;
10 use crate::hair::constant::*;
12 use rustc::mir::{Field, BorrowKind, Mutability};
13 use rustc::mir::{UserTypeProjection};
14 use rustc::mir::interpret::{GlobalId, ConstValue, get_slice_bytes, sign_extend};
15 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, UserType, DefIdTree};
16 use rustc::ty::{CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations};
17 use rustc::ty::subst::{SubstsRef, GenericArg};
18 use rustc::ty::layout::VariantIdx;
19 use rustc::hir::{self, RangeEnd};
20 use rustc::hir::def::{CtorOf, Res, DefKind, CtorKind};
21 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
22 use rustc::hir::ptr::P;
24 use rustc_index::vec::Idx;
26 use std::cmp::Ordering;
31 #[derive(Clone, Debug)]
32 pub enum PatternError {
33 AssocConstInPattern(Span),
34 StaticInPattern(Span),
39 #[derive(Copy, Clone, Debug)]
40 pub enum BindingMode {
45 #[derive(Clone, Debug)]
46 pub struct FieldPat<'tcx> {
48 pub pattern: Pat<'tcx>,
51 #[derive(Clone, Debug)]
52 pub struct Pat<'tcx> {
55 pub kind: Box<PatKind<'tcx>>,
59 #[derive(Copy, Clone, Debug, PartialEq)]
60 pub struct PatTyProj<'tcx> {
61 pub user_ty: CanonicalUserType<'tcx>,
64 impl<'tcx> PatTyProj<'tcx> {
65 pub(crate) fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
67 user_ty: user_annotation,
71 pub(crate) fn user_ty(
73 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
74 inferred_ty: Ty<'tcx>,
76 ) -> UserTypeProjection {
78 base: annotations.push(CanonicalUserTypeAnnotation {
80 user_ty: self.user_ty,
88 #[derive(Copy, Clone, Debug, PartialEq)]
89 pub struct Ascription<'tcx> {
90 pub user_ty: PatTyProj<'tcx>,
91 /// Variance to use when relating the type `user_ty` to the **type of the value being
92 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
93 /// have a type that is some subtype of the ascribed type.
95 /// Note that this variance does not apply for any bindings within subpatterns. The type
96 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
98 /// The only place where this field is not `Covariant` is when matching constants, where
99 /// we currently use `Contravariant` -- this is because the constant type just needs to
100 /// be "comparable" to the type of the input value. So, for example:
103 /// match x { "foo" => .. }
106 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
107 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
108 /// of the old type-check for now. See #57280 for details.
109 pub variance: ty::Variance,
110 pub user_ty_span: Span,
113 #[derive(Clone, Debug)]
114 pub enum PatKind<'tcx> {
118 ascription: Ascription<'tcx>,
119 subpattern: Pat<'tcx>,
122 /// `x`, `ref x`, `x @ P`, etc.
124 mutability: Mutability,
129 subpattern: Option<Pat<'tcx>>,
132 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
133 /// multiple variants.
135 adt_def: &'tcx AdtDef,
136 substs: SubstsRef<'tcx>,
137 variant_index: VariantIdx,
138 subpatterns: Vec<FieldPat<'tcx>>,
141 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
142 /// a single variant.
144 subpatterns: Vec<FieldPat<'tcx>>,
147 /// `box P`, `&P`, `&mut P`, etc.
149 subpattern: Pat<'tcx>,
153 value: &'tcx ty::Const<'tcx>,
156 Range(PatRange<'tcx>),
158 /// Matches against a slice, checking the length and extracting elements.
159 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
160 /// e.g., `&[ref xs @ ..]`.
162 prefix: Vec<Pat<'tcx>>,
163 slice: Option<Pat<'tcx>>,
164 suffix: Vec<Pat<'tcx>>,
167 /// Fixed match against an array; irrefutable.
169 prefix: Vec<Pat<'tcx>>,
170 slice: Option<Pat<'tcx>>,
171 suffix: Vec<Pat<'tcx>>,
174 /// An or-pattern, e.g. `p | q`.
175 /// Invariant: `pats.len() >= 2`.
177 pats: Vec<Pat<'tcx>>,
181 #[derive(Copy, Clone, Debug, PartialEq)]
182 pub struct PatRange<'tcx> {
183 pub lo: &'tcx ty::Const<'tcx>,
184 pub hi: &'tcx ty::Const<'tcx>,
188 impl<'tcx> fmt::Display for Pat<'tcx> {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 // Printing lists is a chore.
191 let mut first = true;
192 let mut start_or_continue = |s| {
200 let mut start_or_comma = || start_or_continue(", ");
203 PatKind::Wild => write!(f, "_"),
204 PatKind::AscribeUserType { ref subpattern, .. } =>
205 write!(f, "{}: _", subpattern),
206 PatKind::Binding { mutability, name, mode, ref subpattern, .. } => {
207 let is_mut = match mode {
208 BindingMode::ByValue => mutability == Mutability::Mut,
209 BindingMode::ByRef(bk) => {
211 match bk { BorrowKind::Mut { .. } => true, _ => false }
217 write!(f, "{}", name)?;
218 if let Some(ref subpattern) = *subpattern {
219 write!(f, " @ {}", subpattern)?;
223 PatKind::Variant { ref subpatterns, .. } |
224 PatKind::Leaf { ref subpatterns } => {
225 let variant = match *self.kind {
226 PatKind::Variant { adt_def, variant_index, .. } => {
227 Some(&adt_def.variants[variant_index])
229 _ => if let ty::Adt(adt, _) = self.ty.kind {
231 Some(&adt.variants[VariantIdx::new(0)])
240 if let Some(variant) = variant {
241 write!(f, "{}", variant.ident)?;
243 // Only for Adt we can have `S {...}`,
244 // which we handle separately here.
245 if variant.ctor_kind == CtorKind::Fictive {
249 for p in subpatterns {
250 if let PatKind::Wild = *p.pattern.kind {
253 let name = variant.fields[p.field.index()].ident;
254 write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
258 if printed < variant.fields.len() {
259 write!(f, "{}..", start_or_comma())?;
262 return write!(f, " }}");
266 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
267 if num_fields != 0 || variant.is_none() {
269 for i in 0..num_fields {
270 write!(f, "{}", start_or_comma())?;
272 // Common case: the field is where we expect it.
273 if let Some(p) = subpatterns.get(i) {
274 if p.field.index() == i {
275 write!(f, "{}", p.pattern)?;
280 // Otherwise, we have to go looking for it.
281 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
282 write!(f, "{}", p.pattern)?;
292 PatKind::Deref { ref subpattern } => {
294 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
295 ty::Ref(_, _, mutbl) => {
296 write!(f, "&{}", mutbl.prefix_str())?;
298 _ => bug!("{} is a bad Deref pattern type", self.ty)
300 write!(f, "{}", subpattern)
302 PatKind::Constant { value } => {
303 write!(f, "{}", value)
305 PatKind::Range(PatRange { lo, hi, end }) => {
306 write!(f, "{}", lo)?;
307 write!(f, "{}", end)?;
310 PatKind::Slice { ref prefix, ref slice, ref suffix } |
311 PatKind::Array { ref prefix, ref slice, ref suffix } => {
314 write!(f, "{}{}", start_or_comma(), p)?;
316 if let Some(ref slice) = *slice {
317 write!(f, "{}", start_or_comma())?;
320 _ => write!(f, "{}", slice)?
325 write!(f, "{}{}", start_or_comma(), p)?;
329 PatKind::Or { ref pats } => {
331 write!(f, "{}{}", start_or_continue(" | "), pat)?;
339 pub struct PatCtxt<'a, 'tcx> {
340 pub tcx: TyCtxt<'tcx>,
341 pub param_env: ty::ParamEnv<'tcx>,
342 pub tables: &'a ty::TypeckTables<'tcx>,
343 pub substs: SubstsRef<'tcx>,
344 pub errors: Vec<PatternError>,
345 include_lint_checks: bool,
348 impl<'a, 'tcx> Pat<'tcx> {
351 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
352 tables: &'a ty::TypeckTables<'tcx>,
355 let mut pcx = PatCtxt::new(tcx, param_env_and_substs, tables);
356 let result = pcx.lower_pattern(pat);
357 if !pcx.errors.is_empty() {
358 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
359 tcx.sess.delay_span_bug(pat.span, &msg);
361 debug!("Pat::from_hir({:?}) = {:?}", pat, result);
366 impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
369 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
370 tables: &'a ty::TypeckTables<'tcx>,
374 param_env: param_env_and_substs.param_env,
376 substs: param_env_and_substs.value,
378 include_lint_checks: false,
382 pub fn include_lint_checks(&mut self) -> &mut Self {
383 self.include_lint_checks = true;
387 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pat<'tcx> {
388 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
389 // pattern has the type that results *after* dereferencing. For example, in this code:
392 // match &&Some(0i32) {
393 // Some(n) => { ... },
398 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
399 // determined in rustc_typeck::check::match). The adjustments would be
401 // `vec![&&Option<i32>, &Option<i32>]`.
403 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
404 // we wrap the unadjusted pattern in `PatKind::Deref` repeatedly, consuming the
405 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
406 // gets the least-dereferenced type).
407 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
414 .fold(unadjusted_pat, |pat, ref_ty| {
415 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
419 kind: Box::new(PatKind::Deref { subpattern: pat }),
427 expr: &'tcx hir::Expr,
428 ) -> (PatKind<'tcx>, Option<Ascription<'tcx>>) {
429 match self.lower_lit(expr) {
430 PatKind::AscribeUserType {
431 ascription: lo_ascription,
432 subpattern: Pat { kind: box kind, .. },
433 } => (kind, Some(lo_ascription)),
434 kind => (kind, None),
438 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pat<'tcx> {
439 let mut ty = self.tables.node_type(pat.hir_id);
441 let kind = match pat.kind {
442 hir::PatKind::Wild => PatKind::Wild,
444 hir::PatKind::Lit(ref value) => self.lower_lit(value),
446 hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
447 let (lo, lo_ascription) = self.lower_range_expr(lo_expr);
448 let (hi, hi_ascription) = self.lower_range_expr(hi_expr);
450 let mut kind = match (lo, hi) {
451 (PatKind::Constant { value: lo }, PatKind::Constant { value: hi }) => {
452 assert_eq!(lo.ty, ty);
453 assert_eq!(hi.ty, ty);
454 let cmp = compare_const_vals(
462 (RangeEnd::Excluded, Some(Ordering::Less)) =>
463 PatKind::Range(PatRange { lo, hi, end }),
464 (RangeEnd::Excluded, _) => {
469 "lower range bound must be less than upper",
473 (RangeEnd::Included, Some(Ordering::Equal)) => {
474 PatKind::Constant { value: lo }
476 (RangeEnd::Included, Some(Ordering::Less)) => {
477 PatKind::Range(PatRange { lo, hi, end })
479 (RangeEnd::Included, _) => {
480 let mut err = struct_span_err!(
484 "lower range bound must be less than or equal to upper"
488 "lower bound larger than upper bound",
490 if self.tcx.sess.teach(&err.get_code().unwrap()) {
491 err.note("When matching against a range, the compiler \
492 verifies that the range is non-empty. Range \
493 patterns include both end-points, so this is \
494 equivalent to requiring the start of the range \
495 to be less than or equal to the end of the range.");
503 self.tcx.sess.delay_span_bug(
506 "found bad range pattern `{:?}` outside of error recovery",
515 // If we are handling a range with associated constants (e.g.
516 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
517 // constants somewhere. Have them on the range pattern.
518 for ascription in &[lo_ascription, hi_ascription] {
519 if let Some(ascription) = ascription {
520 kind = PatKind::AscribeUserType {
521 ascription: *ascription,
522 subpattern: Pat { span: pat.span, ty, kind: Box::new(kind), },
530 hir::PatKind::Path(ref qpath) => {
531 return self.lower_path(qpath, pat.hir_id, pat.span);
534 hir::PatKind::Ref(ref subpattern, _) |
535 hir::PatKind::Box(ref subpattern) => {
536 PatKind::Deref { subpattern: self.lower_pattern(subpattern) }
539 hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => {
546 kind: Box::new(self.slice_or_array_pattern(
547 pat.span, ty, prefix, slice, suffix))
552 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
553 ty::Error => { // Avoid ICE
554 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
559 "unexpanded type for vector pattern: {:?}",
564 hir::PatKind::Tuple(ref subpatterns, ddpos) => {
566 ty::Tuple(ref tys) => {
569 .enumerate_and_adjust(tys.len(), ddpos)
570 .map(|(i, subpattern)| FieldPat {
571 field: Field::new(i),
572 pattern: self.lower_pattern(subpattern)
576 PatKind::Leaf { subpatterns }
578 ty::Error => { // Avoid ICE (#50577)
579 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
581 _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty),
585 hir::PatKind::Binding(_, id, ident, ref sub) => {
586 let var_ty = self.tables.node_type(pat.hir_id);
587 if let ty::Error = var_ty.kind {
589 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
591 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
592 .expect("missing binding mode");
593 let (mutability, mode) = match bm {
594 ty::BindByValue(hir::MutMutable) =>
595 (Mutability::Mut, BindingMode::ByValue),
596 ty::BindByValue(hir::MutImmutable) =>
597 (Mutability::Not, BindingMode::ByValue),
598 ty::BindByReference(hir::MutMutable) =>
599 (Mutability::Not, BindingMode::ByRef(
600 BorrowKind::Mut { allow_two_phase_borrow: false })),
601 ty::BindByReference(hir::MutImmutable) =>
602 (Mutability::Not, BindingMode::ByRef(
603 BorrowKind::Shared)),
606 // A ref x pattern is the same node used for x, and as such it has
607 // x's type, which is &T, where we want T (the type being matched).
608 if let ty::BindByReference(_) = bm {
609 if let ty::Ref(_, rty, _) = ty.kind {
612 bug!("`ref {}` has wrong type {}", ident, ty);
622 subpattern: self.lower_opt_pattern(sub),
626 hir::PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
627 let res = self.tables.qpath_res(qpath, pat.hir_id);
628 let adt_def = match ty.kind {
629 ty::Adt(adt_def, _) => adt_def,
630 ty::Error => { // Avoid ICE (#50585)
631 return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) };
633 _ => span_bug!(pat.span,
634 "tuple struct pattern not applied to an ADT {:?}",
637 let variant_def = adt_def.variant_of_res(res);
641 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
642 .map(|(i, field)| FieldPat {
643 field: Field::new(i),
644 pattern: self.lower_pattern(field),
648 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
651 hir::PatKind::Struct(ref qpath, ref fields, _) => {
652 let res = self.tables.qpath_res(qpath, pat.hir_id);
657 field: Field::new(self.tcx.field_index(field.hir_id,
659 pattern: self.lower_pattern(&field.pat),
664 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
667 hir::PatKind::Or(ref pats) => {
669 pats: pats.iter().map(|p| self.lower_pattern(p)).collect(),
677 kind: Box::new(kind),
681 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pat<'tcx>> {
682 pats.iter().map(|p| self.lower_pattern(p)).collect()
685 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pat<'tcx>>
687 pat.as_ref().map(|p| self.lower_pattern(p))
690 fn flatten_nested_slice_patterns(
692 prefix: Vec<Pat<'tcx>>,
693 slice: Option<Pat<'tcx>>,
694 suffix: Vec<Pat<'tcx>>)
695 -> (Vec<Pat<'tcx>>, Option<Pat<'tcx>>, Vec<Pat<'tcx>>)
697 let orig_slice = match slice {
698 Some(orig_slice) => orig_slice,
699 None => return (prefix, slice, suffix)
701 let orig_prefix = prefix;
702 let orig_suffix = suffix;
704 // dance because of intentional borrow-checker stupidity.
705 let kind = *orig_slice.kind;
707 PatKind::Slice { prefix, slice, mut suffix } |
708 PatKind::Array { prefix, slice, mut suffix } => {
709 let mut orig_prefix = orig_prefix;
711 orig_prefix.extend(prefix);
712 suffix.extend(orig_suffix);
714 (orig_prefix, slice, suffix)
717 (orig_prefix, Some(Pat {
718 kind: box kind, ..orig_slice
724 fn slice_or_array_pattern(
728 prefix: &'tcx [P<hir::Pat>],
729 slice: &'tcx Option<P<hir::Pat>>,
730 suffix: &'tcx [P<hir::Pat>])
733 let prefix = self.lower_patterns(prefix);
734 let slice = self.lower_opt_pattern(slice);
735 let suffix = self.lower_patterns(suffix);
736 let (prefix, slice, suffix) =
737 self.flatten_nested_slice_patterns(prefix, slice, suffix);
741 // matching a slice or fixed-length array
742 PatKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
745 ty::Array(_, len) => {
746 // fixed-length array
747 let len = len.eval_usize(self.tcx, self.param_env);
748 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
749 PatKind::Array { prefix: prefix, slice: slice, suffix: suffix }
753 span_bug!(span, "bad slice pattern type {:?}", ty);
758 fn lower_variant_or_leaf(
764 subpatterns: Vec<FieldPat<'tcx>>,
766 let res = match res {
767 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
768 let variant_id = self.tcx.parent(variant_ctor_id).unwrap();
769 Res::Def(DefKind::Variant, variant_id)
774 let mut kind = match res {
775 Res::Def(DefKind::Variant, variant_id) => {
776 let enum_id = self.tcx.parent(variant_id).unwrap();
777 let adt_def = self.tcx.adt_def(enum_id);
778 if adt_def.is_enum() {
779 let substs = match ty.kind {
781 ty::FnDef(_, substs) => substs,
782 ty::Error => { // Avoid ICE (#50585)
783 return PatKind::Wild;
785 _ => bug!("inappropriate type for def: {:?}", ty),
790 variant_index: adt_def.variant_index_with_id(variant_id),
794 PatKind::Leaf { subpatterns }
798 Res::Def(DefKind::Struct, _)
799 | Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _)
800 | Res::Def(DefKind::Union, _)
801 | Res::Def(DefKind::TyAlias, _)
802 | Res::Def(DefKind::AssocTy, _)
804 | Res::SelfCtor(..) => {
805 PatKind::Leaf { subpatterns }
809 self.errors.push(PatternError::NonConstPath(span));
814 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
815 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
816 kind = PatKind::AscribeUserType {
820 kind: Box::new(kind),
822 ascription: Ascription {
823 user_ty: PatTyProj::from_user_type(user_ty),
825 variance: ty::Variance::Covariant,
833 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
834 /// it to `const_to_pat`. Any other path (like enum variants without fields)
835 /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
836 fn lower_path(&mut self,
841 let ty = self.tables.node_type(id);
842 let res = self.tables.qpath_res(qpath, id);
843 let is_associated_const = match res {
844 Res::Def(DefKind::AssocConst, _) => true,
847 let kind = match res {
848 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
849 let substs = self.tables.node_substs(id);
850 match ty::Instance::resolve(
861 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
863 let pattern = self.const_to_pat(value, id, span);
864 if !is_associated_const {
868 let user_provided_types = self.tables().user_provided_types();
869 return if let Some(u_ty) = user_provided_types.get(id) {
870 let user_ty = PatTyProj::from_user_type(*u_ty);
874 PatKind::AscribeUserType {
876 ascription: Ascription {
877 /// Note that use `Contravariant` here. See the
878 /// `variance` field documentation for details.
879 variance: ty::Variance::Contravariant,
892 self.tcx.sess.span_err(
894 "could not evaluate constant pattern",
901 self.errors.push(if is_associated_const {
902 PatternError::AssocConstInPattern(span)
904 PatternError::StaticInPattern(span)
910 _ => self.lower_variant_or_leaf(res, id, span, ty, vec![]),
916 kind: Box::new(kind),
920 /// Converts literals, paths and negation of literals to patterns.
921 /// The special case for negation exists to allow things like `-128_i8`
922 /// which would overflow if we tried to evaluate `128_i8` and then negate
924 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatKind<'tcx> {
926 hir::ExprKind::Lit(ref lit) => {
927 let ty = self.tables.expr_ty(expr);
928 match lit_to_const(&lit.node, self.tcx, ty, false) {
930 *self.const_to_pat(val, expr.hir_id, lit.span).kind
932 Err(LitToConstError::UnparseableFloat) => {
933 self.errors.push(PatternError::FloatBug);
936 Err(LitToConstError::Reported) => PatKind::Wild,
939 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
940 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
941 let ty = self.tables.expr_ty(expr);
942 let lit = match expr.kind {
943 hir::ExprKind::Lit(ref lit) => lit,
944 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
946 match lit_to_const(&lit.node, self.tcx, ty, true) {
948 *self.const_to_pat(val, expr.hir_id, lit.span).kind
950 Err(LitToConstError::UnparseableFloat) => {
951 self.errors.push(PatternError::FloatBug);
954 Err(LitToConstError::Reported) => PatKind::Wild,
957 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
962 impl UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> {
963 fn tcx(&self) -> TyCtxt<'tcx> {
967 fn tables(&self) -> &ty::TypeckTables<'tcx> {
973 pub trait PatternFoldable<'tcx> : Sized {
974 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
975 self.super_fold_with(folder)
978 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
981 pub trait PatternFolder<'tcx> : Sized {
982 fn fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx> {
983 pattern.super_fold_with(self)
986 fn fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx> {
987 kind.super_fold_with(self)
992 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
993 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
994 let content: T = (**self).fold_with(folder);
999 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1000 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1001 self.iter().map(|t| t.fold_with(folder)).collect()
1005 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1006 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1007 self.as_ref().map(|t| t.fold_with(folder))
1011 macro_rules! CloneImpls {
1012 (<$lt_tcx:tt> $($ty:ty),+) => {
1014 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1015 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1024 Span, Field, Mutability, ast::Name, hir::HirId, usize, ty::Const<'tcx>,
1025 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1026 SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
1027 UserTypeProjection, PatTyProj<'tcx>
1030 impl<'tcx> PatternFoldable<'tcx> for FieldPat<'tcx> {
1031 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1033 field: self.field.fold_with(folder),
1034 pattern: self.pattern.fold_with(folder)
1039 impl<'tcx> PatternFoldable<'tcx> for Pat<'tcx> {
1040 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1041 folder.fold_pattern(self)
1044 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1046 ty: self.ty.fold_with(folder),
1047 span: self.span.fold_with(folder),
1048 kind: self.kind.fold_with(folder)
1053 impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
1054 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1055 folder.fold_pattern_kind(self)
1058 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1060 PatKind::Wild => PatKind::Wild,
1061 PatKind::AscribeUserType {
1063 ascription: Ascription {
1068 } => PatKind::AscribeUserType {
1069 subpattern: subpattern.fold_with(folder),
1070 ascription: Ascription {
1071 user_ty: user_ty.fold_with(folder),
1083 } => PatKind::Binding {
1084 mutability: mutability.fold_with(folder),
1085 name: name.fold_with(folder),
1086 mode: mode.fold_with(folder),
1087 var: var.fold_with(folder),
1088 ty: ty.fold_with(folder),
1089 subpattern: subpattern.fold_with(folder),
1096 } => PatKind::Variant {
1097 adt_def: adt_def.fold_with(folder),
1098 substs: substs.fold_with(folder),
1100 subpatterns: subpatterns.fold_with(folder)
1104 } => PatKind::Leaf {
1105 subpatterns: subpatterns.fold_with(folder),
1109 } => PatKind::Deref {
1110 subpattern: subpattern.fold_with(folder),
1114 } => PatKind::Constant {
1117 PatKind::Range(range) => PatKind::Range(range),
1122 } => PatKind::Slice {
1123 prefix: prefix.fold_with(folder),
1124 slice: slice.fold_with(folder),
1125 suffix: suffix.fold_with(folder)
1131 } => PatKind::Array {
1132 prefix: prefix.fold_with(folder),
1133 slice: slice.fold_with(folder),
1134 suffix: suffix.fold_with(folder)
1136 PatKind::Or { ref pats } => PatKind::Or { pats: pats.fold_with(folder) },
1141 pub fn compare_const_vals<'tcx>(
1143 a: &'tcx ty::Const<'tcx>,
1144 b: &'tcx ty::Const<'tcx>,
1145 param_env: ty::ParamEnv<'tcx>,
1147 ) -> Option<Ordering> {
1148 trace!("compare_const_vals: {:?}, {:?}", a, b);
1150 let from_bool = |v: bool| {
1152 Some(Ordering::Equal)
1158 let fallback = || from_bool(a == b);
1160 // Use the fallback if any type differs
1161 if a.ty != b.ty || a.ty != ty {
1165 let a_bits = a.try_eval_bits(tcx, param_env, ty);
1166 let b_bits = b.try_eval_bits(tcx, param_env, ty);
1168 if let (Some(a), Some(b)) = (a_bits, b_bits) {
1169 use ::rustc_apfloat::Float;
1170 return match ty.kind {
1171 ty::Float(ast::FloatTy::F32) => {
1172 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1173 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1176 ty::Float(ast::FloatTy::F64) => {
1177 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1178 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1182 use rustc::ty::layout::{Integer, IntegerExt};
1183 use syntax::attr::SignedInt;
1184 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
1185 let a = sign_extend(a, size);
1186 let b = sign_extend(b, size);
1187 Some((a as i128).cmp(&(b as i128)))
1189 _ => Some(a.cmp(&b)),
1193 if let ty::Str = ty.kind {
1194 match (a.val, b.val) {
1195 (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
1196 let a_bytes = get_slice_bytes(&tcx, a.val);
1197 let b_bytes = get_slice_bytes(&tcx, b.val);
1198 return from_bool(a_bytes == b_bytes);