1 //! Validation of patterns/matches.
6 pub(crate) use self::check_match::check_match;
8 use crate::const_eval::const_variant_index;
10 use crate::hair::util::UserAnnotatedTyHelpers;
11 use crate::hair::constant::*;
14 use rustc::mir::{Field, BorrowKind, Mutability};
15 use rustc::mir::{UserTypeProjection};
16 use rustc::mir::interpret::{GlobalId, ConstValue, sign_extend, AllocId, Pointer};
17 use rustc::traits::{ObligationCause, PredicateObligation};
18 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, UserType, DefIdTree};
19 use rustc::ty::{CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations};
20 use rustc::ty::subst::{SubstsRef, Kind};
21 use rustc::ty::layout::{VariantIdx, Size};
22 use rustc::hir::{self, PatKind, RangeEnd};
23 use rustc::hir::def::{CtorOf, Res, DefKind, CtorKind};
24 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
25 use rustc::hir::ptr::P;
27 use rustc_data_structures::indexed_vec::Idx;
28 use rustc_data_structures::fx::FxHashSet;
30 use std::cmp::Ordering;
33 use syntax::symbol::sym;
36 #[derive(Clone, Debug)]
37 pub enum PatternError {
38 AssocConstInPattern(Span),
39 StaticInPattern(Span),
44 #[derive(Copy, Clone, Debug)]
45 pub enum BindingMode {
50 #[derive(Clone, Debug)]
51 pub struct FieldPattern<'tcx> {
53 pub pattern: Pattern<'tcx>,
56 #[derive(Clone, Debug)]
57 pub struct Pattern<'tcx> {
60 pub kind: Box<PatternKind<'tcx>>,
64 #[derive(Copy, Clone, Debug, PartialEq)]
65 pub struct PatternTypeProjection<'tcx> {
66 pub user_ty: CanonicalUserType<'tcx>,
69 impl<'tcx> PatternTypeProjection<'tcx> {
70 pub(crate) fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
72 user_ty: user_annotation,
76 pub(crate) fn user_ty(
78 annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
79 inferred_ty: Ty<'tcx>,
81 ) -> UserTypeProjection {
83 base: annotations.push(CanonicalUserTypeAnnotation {
85 user_ty: self.user_ty,
93 #[derive(Copy, Clone, Debug, PartialEq)]
94 pub struct Ascription<'tcx> {
95 pub user_ty: PatternTypeProjection<'tcx>,
96 /// Variance to use when relating the type `user_ty` to the **type of the value being
97 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
98 /// have a type that is some subtype of the ascribed type.
100 /// Note that this variance does not apply for any bindings within subpatterns. The type
101 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
103 /// The only place where this field is not `Covariant` is when matching constants, where
104 /// we currently use `Contravariant` -- this is because the constant type just needs to
105 /// be "comparable" to the type of the input value. So, for example:
108 /// match x { "foo" => .. }
111 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
112 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
113 /// of the old type-check for now. See #57280 for details.
114 pub variance: ty::Variance,
115 pub user_ty_span: Span,
118 #[derive(Clone, Debug)]
119 pub enum PatternKind<'tcx> {
123 ascription: Ascription<'tcx>,
124 subpattern: Pattern<'tcx>,
127 /// `x`, `ref x`, `x @ P`, etc.
129 mutability: Mutability,
134 subpattern: Option<Pattern<'tcx>>,
137 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
138 /// multiple variants.
140 adt_def: &'tcx AdtDef,
141 substs: SubstsRef<'tcx>,
142 variant_index: VariantIdx,
143 subpatterns: Vec<FieldPattern<'tcx>>,
146 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
147 /// a single variant.
149 subpatterns: Vec<FieldPattern<'tcx>>,
152 /// `box P`, `&P`, `&mut P`, etc.
154 subpattern: Pattern<'tcx>,
158 value: &'tcx ty::Const<'tcx>,
161 Range(PatternRange<'tcx>),
163 /// Matches against a slice, checking the length and extracting elements.
164 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
165 /// e.g., `&[ref xs @ ..]`.
167 prefix: Vec<Pattern<'tcx>>,
168 slice: Option<Pattern<'tcx>>,
169 suffix: Vec<Pattern<'tcx>>,
172 /// Fixed match against an array; irrefutable.
174 prefix: Vec<Pattern<'tcx>>,
175 slice: Option<Pattern<'tcx>>,
176 suffix: Vec<Pattern<'tcx>>,
180 #[derive(Copy, Clone, Debug, PartialEq)]
181 pub struct PatternRange<'tcx> {
182 pub lo: &'tcx ty::Const<'tcx>,
183 pub hi: &'tcx ty::Const<'tcx>,
188 impl<'tcx> fmt::Display for Pattern<'tcx> {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 PatternKind::Wild => write!(f, "_"),
192 PatternKind::AscribeUserType { ref subpattern, .. } =>
193 write!(f, "{}: _", subpattern),
194 PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
195 let is_mut = match mode {
196 BindingMode::ByValue => mutability == Mutability::Mut,
197 BindingMode::ByRef(bk) => {
199 match bk { BorrowKind::Mut { .. } => true, _ => false }
205 write!(f, "{}", name)?;
206 if let Some(ref subpattern) = *subpattern {
207 write!(f, " @ {}", subpattern)?;
211 PatternKind::Variant { ref subpatterns, .. } |
212 PatternKind::Leaf { ref subpatterns } => {
213 let variant = match *self.kind {
214 PatternKind::Variant { adt_def, variant_index, .. } => {
215 Some(&adt_def.variants[variant_index])
217 _ => if let ty::Adt(adt, _) = self.ty.sty {
219 Some(&adt.variants[VariantIdx::new(0)])
228 let mut first = true;
229 let mut start_or_continue = || if first { first = false; "" } else { ", " };
231 if let Some(variant) = variant {
232 write!(f, "{}", variant.ident)?;
234 // Only for Adt we can have `S {...}`,
235 // which we handle separately here.
236 if variant.ctor_kind == CtorKind::Fictive {
240 for p in subpatterns {
241 if let PatternKind::Wild = *p.pattern.kind {
244 let name = variant.fields[p.field.index()].ident;
245 write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
249 if printed < variant.fields.len() {
250 write!(f, "{}..", start_or_continue())?;
253 return write!(f, " }}");
257 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
258 if num_fields != 0 || variant.is_none() {
260 for i in 0..num_fields {
261 write!(f, "{}", start_or_continue())?;
263 // Common case: the field is where we expect it.
264 if let Some(p) = subpatterns.get(i) {
265 if p.field.index() == i {
266 write!(f, "{}", p.pattern)?;
271 // Otherwise, we have to go looking for it.
272 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
273 write!(f, "{}", p.pattern)?;
283 PatternKind::Deref { ref subpattern } => {
285 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
286 ty::Ref(_, _, mutbl) => {
288 if mutbl == hir::MutMutable {
292 _ => bug!("{} is a bad Deref pattern type", self.ty)
294 write!(f, "{}", subpattern)
296 PatternKind::Constant { value } => {
297 write!(f, "{}", value)
299 PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
300 write!(f, "{}", lo)?;
302 RangeEnd::Included => write!(f, "..=")?,
303 RangeEnd::Excluded => write!(f, "..")?,
307 PatternKind::Slice { ref prefix, ref slice, ref suffix } |
308 PatternKind::Array { ref prefix, ref slice, ref suffix } => {
309 let mut first = true;
310 let mut start_or_continue = || if first { first = false; "" } else { ", " };
313 write!(f, "{}{}", start_or_continue(), p)?;
315 if let Some(ref slice) = *slice {
316 write!(f, "{}", start_or_continue())?;
318 PatternKind::Wild => {}
319 _ => write!(f, "{}", slice)?
324 write!(f, "{}{}", start_or_continue(), p)?;
332 pub struct PatternContext<'a, 'tcx> {
333 pub tcx: TyCtxt<'tcx>,
334 pub param_env: ty::ParamEnv<'tcx>,
335 pub tables: &'a ty::TypeckTables<'tcx>,
336 pub substs: SubstsRef<'tcx>,
337 pub errors: Vec<PatternError>,
338 include_lint_checks: bool,
341 impl<'a, 'tcx> Pattern<'tcx> {
344 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
345 tables: &'a ty::TypeckTables<'tcx>,
348 let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
349 let result = pcx.lower_pattern(pat);
350 if !pcx.errors.is_empty() {
351 let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
352 tcx.sess.delay_span_bug(pat.span, &msg);
354 debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
359 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
362 param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>,
363 tables: &'a ty::TypeckTables<'tcx>,
367 param_env: param_env_and_substs.param_env,
369 substs: param_env_and_substs.value,
371 include_lint_checks: false,
375 pub fn include_lint_checks(&mut self) -> &mut Self {
376 self.include_lint_checks = true;
380 pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
381 // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
382 // pattern has the type that results *after* dereferencing. For example, in this code:
385 // match &&Some(0i32) {
386 // Some(n) => { ... },
391 // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
392 // determined in rustc_typeck::check::match). The adjustments would be
394 // `vec![&&Option<i32>, &Option<i32>]`.
396 // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
397 // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
398 // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
399 // gets the least-dereferenced type).
400 let unadjusted_pat = self.lower_pattern_unadjusted(pat);
407 .fold(unadjusted_pat, |pat, ref_ty| {
408 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
412 kind: Box::new(PatternKind::Deref { subpattern: pat }),
420 expr: &'tcx hir::Expr,
421 ) -> (PatternKind<'tcx>, Option<Ascription<'tcx>>) {
422 match self.lower_lit(expr) {
423 PatternKind::AscribeUserType {
424 ascription: lo_ascription,
425 subpattern: Pattern { kind: box kind, .. },
426 } => (kind, Some(lo_ascription)),
427 kind => (kind, None),
431 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
432 let mut ty = self.tables.node_type(pat.hir_id);
434 let kind = match pat.node {
435 PatKind::Wild => PatternKind::Wild,
437 PatKind::Lit(ref value) => self.lower_lit(value),
439 PatKind::Range(ref lo_expr, ref hi_expr, end) => {
440 let (lo, lo_ascription) = self.lower_range_expr(lo_expr);
441 let (hi, hi_ascription) = self.lower_range_expr(hi_expr);
443 let mut kind = match (lo, hi) {
444 (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => {
445 let cmp = compare_const_vals(
449 self.param_env.and(ty),
452 (RangeEnd::Excluded, Some(Ordering::Less)) =>
453 PatternKind::Range(PatternRange { lo, hi, ty, end }),
454 (RangeEnd::Excluded, _) => {
459 "lower range bound must be less than upper",
463 (RangeEnd::Included, Some(Ordering::Equal)) => {
464 PatternKind::Constant { value: lo }
466 (RangeEnd::Included, Some(Ordering::Less)) => {
467 PatternKind::Range(PatternRange { lo, hi, ty, end })
469 (RangeEnd::Included, _) => {
470 let mut err = struct_span_err!(
474 "lower range bound must be less than or equal to upper"
478 "lower bound larger than upper bound",
480 if self.tcx.sess.teach(&err.get_code().unwrap()) {
481 err.note("When matching against a range, the compiler \
482 verifies that the range is non-empty. Range \
483 patterns include both end-points, so this is \
484 equivalent to requiring the start of the range \
485 to be less than or equal to the end of the range.");
493 self.tcx.sess.delay_span_bug(
496 "found bad range pattern `{:?}` outside of error recovery",
505 // If we are handling a range with associated constants (e.g.
506 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
507 // constants somewhere. Have them on the range pattern.
508 for ascription in &[lo_ascription, hi_ascription] {
509 if let Some(ascription) = ascription {
510 kind = PatternKind::AscribeUserType {
511 ascription: *ascription,
512 subpattern: Pattern { span: pat.span, ty, kind: Box::new(kind), },
520 PatKind::Path(ref qpath) => {
521 return self.lower_path(qpath, pat.hir_id, pat.span);
524 PatKind::Ref(ref subpattern, _) |
525 PatKind::Box(ref subpattern) => {
526 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
529 PatKind::Slice(ref prefix, ref slice, ref suffix) => {
533 subpattern: Pattern {
536 kind: Box::new(self.slice_or_array_pattern(
537 pat.span, ty, prefix, slice, suffix))
542 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
543 ty::Error => { // Avoid ICE
544 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
549 "unexpanded type for vector pattern: {:?}",
554 PatKind::Tuple(ref subpatterns, ddpos) => {
556 ty::Tuple(ref tys) => {
559 .enumerate_and_adjust(tys.len(), ddpos)
560 .map(|(i, subpattern)| FieldPattern {
561 field: Field::new(i),
562 pattern: self.lower_pattern(subpattern)
566 PatternKind::Leaf { subpatterns }
568 ty::Error => { // Avoid ICE (#50577)
569 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
571 _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty),
575 PatKind::Binding(_, id, ident, ref sub) => {
576 let var_ty = self.tables.node_type(pat.hir_id);
577 if let ty::Error = var_ty.sty {
579 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
581 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
582 .expect("missing binding mode");
583 let (mutability, mode) = match bm {
584 ty::BindByValue(hir::MutMutable) =>
585 (Mutability::Mut, BindingMode::ByValue),
586 ty::BindByValue(hir::MutImmutable) =>
587 (Mutability::Not, BindingMode::ByValue),
588 ty::BindByReference(hir::MutMutable) =>
589 (Mutability::Not, BindingMode::ByRef(
590 BorrowKind::Mut { allow_two_phase_borrow: false })),
591 ty::BindByReference(hir::MutImmutable) =>
592 (Mutability::Not, BindingMode::ByRef(
593 BorrowKind::Shared)),
596 // A ref x pattern is the same node used for x, and as such it has
597 // x's type, which is &T, where we want T (the type being matched).
598 if let ty::BindByReference(_) = bm {
599 if let ty::Ref(_, rty, _) = ty.sty {
602 bug!("`ref {}` has wrong type {}", ident, ty);
606 PatternKind::Binding {
612 subpattern: self.lower_opt_pattern(sub),
616 PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
617 let res = self.tables.qpath_res(qpath, pat.hir_id);
618 let adt_def = match ty.sty {
619 ty::Adt(adt_def, _) => adt_def,
620 ty::Error => { // Avoid ICE (#50585)
621 return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
623 _ => span_bug!(pat.span,
624 "tuple struct pattern not applied to an ADT {:?}",
627 let variant_def = adt_def.variant_of_res(res);
631 .enumerate_and_adjust(variant_def.fields.len(), ddpos)
632 .map(|(i, field)| FieldPattern {
633 field: Field::new(i),
634 pattern: self.lower_pattern(field),
638 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
641 PatKind::Struct(ref qpath, ref fields, _) => {
642 let res = self.tables.qpath_res(qpath, pat.hir_id);
647 field: Field::new(self.tcx.field_index(field.node.hir_id,
649 pattern: self.lower_pattern(&field.node.pat),
654 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
661 kind: Box::new(kind),
665 fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
666 pats.iter().map(|p| self.lower_pattern(p)).collect()
669 fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
671 pat.as_ref().map(|p| self.lower_pattern(p))
674 fn flatten_nested_slice_patterns(
676 prefix: Vec<Pattern<'tcx>>,
677 slice: Option<Pattern<'tcx>>,
678 suffix: Vec<Pattern<'tcx>>)
679 -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
681 let orig_slice = match slice {
682 Some(orig_slice) => orig_slice,
683 None => return (prefix, slice, suffix)
685 let orig_prefix = prefix;
686 let orig_suffix = suffix;
688 // dance because of intentional borrow-checker stupidity.
689 let kind = *orig_slice.kind;
691 PatternKind::Slice { prefix, slice, mut suffix } |
692 PatternKind::Array { prefix, slice, mut suffix } => {
693 let mut orig_prefix = orig_prefix;
695 orig_prefix.extend(prefix);
696 suffix.extend(orig_suffix);
698 (orig_prefix, slice, suffix)
701 (orig_prefix, Some(Pattern {
702 kind: box kind, ..orig_slice
708 fn slice_or_array_pattern(
712 prefix: &'tcx [P<hir::Pat>],
713 slice: &'tcx Option<P<hir::Pat>>,
714 suffix: &'tcx [P<hir::Pat>])
717 let prefix = self.lower_patterns(prefix);
718 let slice = self.lower_opt_pattern(slice);
719 let suffix = self.lower_patterns(suffix);
720 let (prefix, slice, suffix) =
721 self.flatten_nested_slice_patterns(prefix, slice, suffix);
725 // matching a slice or fixed-length array
726 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
729 ty::Array(_, len) => {
730 // fixed-length array
731 let len = len.unwrap_usize(self.tcx);
732 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
733 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
737 span_bug!(span, "bad slice pattern type {:?}", ty);
742 fn lower_variant_or_leaf(
748 subpatterns: Vec<FieldPattern<'tcx>>,
749 ) -> PatternKind<'tcx> {
750 let res = match res {
751 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
752 let variant_id = self.tcx.parent(variant_ctor_id).unwrap();
753 Res::Def(DefKind::Variant, variant_id)
758 let mut kind = match res {
759 Res::Def(DefKind::Variant, variant_id) => {
760 let enum_id = self.tcx.parent(variant_id).unwrap();
761 let adt_def = self.tcx.adt_def(enum_id);
762 if adt_def.is_enum() {
763 let substs = match ty.sty {
765 ty::FnDef(_, substs) => substs,
766 ty::Error => { // Avoid ICE (#50585)
767 return PatternKind::Wild;
769 _ => bug!("inappropriate type for def: {:?}", ty),
771 PatternKind::Variant {
774 variant_index: adt_def.variant_index_with_id(variant_id),
778 PatternKind::Leaf { subpatterns }
782 Res::Def(DefKind::Struct, _)
783 | Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _)
784 | Res::Def(DefKind::Union, _)
785 | Res::Def(DefKind::TyAlias, _)
786 | Res::Def(DefKind::AssocTy, _)
788 | Res::SelfCtor(..) => {
789 PatternKind::Leaf { subpatterns }
793 self.errors.push(PatternError::NonConstPath(span));
798 if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
799 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
800 kind = PatternKind::AscribeUserType {
801 subpattern: Pattern {
804 kind: Box::new(kind),
806 ascription: Ascription {
807 user_ty: PatternTypeProjection::from_user_type(user_ty),
809 variance: ty::Variance::Covariant,
817 /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
818 /// it to `const_to_pat`. Any other path (like enum variants without fields)
819 /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
820 fn lower_path(&mut self,
825 let ty = self.tables.node_type(id);
826 let res = self.tables.qpath_res(qpath, id);
827 let is_associated_const = match res {
828 Res::Def(DefKind::AssocConst, _) => true,
831 let kind = match res {
832 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
833 let substs = self.tables.node_substs(id);
834 match ty::Instance::resolve(
845 match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
847 let pattern = self.const_to_pat(instance, value, id, span);
848 if !is_associated_const {
852 let user_provided_types = self.tables().user_provided_types();
853 return if let Some(u_ty) = user_provided_types.get(id) {
854 let user_ty = PatternTypeProjection::from_user_type(*u_ty);
858 PatternKind::AscribeUserType {
860 ascription: Ascription {
861 /// Note that use `Contravariant` here. See the
862 /// `variance` field documentation for details.
863 variance: ty::Variance::Contravariant,
876 self.tcx.sess.span_err(
878 "could not evaluate constant pattern",
885 self.errors.push(if is_associated_const {
886 PatternError::AssocConstInPattern(span)
888 PatternError::StaticInPattern(span)
894 _ => self.lower_variant_or_leaf(res, id, span, ty, vec![]),
900 kind: Box::new(kind),
904 /// Converts literals, paths and negation of literals to patterns.
905 /// The special case for negation exists to allow things like `-128_i8`
906 /// which would overflow if we tried to evaluate `128_i8` and then negate
908 fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
910 hir::ExprKind::Lit(ref lit) => {
911 let ty = self.tables.expr_ty(expr);
912 match lit_to_const(&lit.node, self.tcx, ty, false) {
914 let instance = ty::Instance::new(
915 self.tables.local_id_root.expect("literal outside any scope"),
918 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
920 Err(LitToConstError::UnparseableFloat) => {
921 self.errors.push(PatternError::FloatBug);
924 Err(LitToConstError::Reported) => PatternKind::Wild,
927 hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
928 hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
929 let ty = self.tables.expr_ty(expr);
930 let lit = match expr.node {
931 hir::ExprKind::Lit(ref lit) => lit,
932 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
934 match lit_to_const(&lit.node, self.tcx, ty, true) {
936 let instance = ty::Instance::new(
937 self.tables.local_id_root.expect("literal outside any scope"),
940 *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
942 Err(LitToConstError::UnparseableFloat) => {
943 self.errors.push(PatternError::FloatBug);
946 Err(LitToConstError::Reported) => PatternKind::Wild,
949 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
953 /// Converts an evaluated constant to a pattern (if possible).
954 /// This means aggregate values (like structs and enums) are converted
955 /// to a pattern that matches the value (as if you'd compared via structural equality).
958 instance: ty::Instance<'tcx>,
959 cv: &'tcx ty::Const<'tcx>,
963 // This method is just a warpper handling a validity check; the heavy lifting is
964 // performed by the recursive const_to_pat_inner method, which is not meant to be
965 // invoked except by this method.
967 // once indirect_structural_match is a full fledged error, this
968 // level of indirection can be eliminated
970 debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
971 debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
973 let mut saw_error = false;
974 let inlined_const_as_pat = self.const_to_pat_inner(instance, cv, id, span, &mut saw_error);
976 if self.include_lint_checks && !saw_error {
977 // If we were able to successfully convert the const to some pat, double-check
978 // that the type of the const obeys `#[structural_match]` constraint.
979 if let Some(adt_def) = search_for_adt_without_structural_match(self.tcx, cv.ty) {
981 let path = self.tcx.def_path_str(adt_def.did);
983 "to use a constant of type `{}` in a pattern, \
984 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
989 // before issuing lint, double-check there even *is* a
990 // semantic PartialEq for us to dispatch to.
992 // (If there isn't, then we can safely issue a hard
993 // error, because that's never worked, due to compiler
994 // using PartialEq::eq in this scenario in the past.)
996 let ty_is_partial_eq: bool = {
997 let partial_eq_trait_id = self.tcx.lang_items().eq_trait().unwrap();
998 let obligation: PredicateObligation<'_> =
999 self.tcx.predicate_for_trait_def(self.param_env,
1000 ObligationCause::misc(span, id),
1001 partial_eq_trait_id,
1007 .enter(|infcx| infcx.predicate_may_hold(&obligation))
1010 if !ty_is_partial_eq {
1011 // span_fatal avoids ICE from resolution of non-existent method (rare case).
1012 self.tcx.sess.span_fatal(span, &msg);
1014 self.tcx.lint_hir(lint::builtin::INDIRECT_STRUCTURAL_MATCH, id, span, &msg);
1019 inlined_const_as_pat
1022 /// Recursive helper for `const_to_pat`; invoke that (instead of calling this directly).
1023 fn const_to_pat_inner(
1025 instance: ty::Instance<'tcx>,
1026 cv: &'tcx ty::Const<'tcx>,
1029 // This tracks if we signal some hard error for a given const
1030 // value, so that we will not subsequently issue an irrelevant
1031 // lint for the same const value.
1032 saw_const_match_error: &mut bool,
1033 ) -> Pattern<'tcx> {
1035 let mut adt_subpattern = |i, variant_opt| {
1036 let field = Field::new(i);
1037 let val = crate::const_eval::const_field(
1038 self.tcx, self.param_env, variant_opt, field, cv
1040 self.const_to_pat_inner(instance, val, id, span, saw_const_match_error)
1042 let mut adt_subpatterns = |n, variant_opt| {
1044 let field = Field::new(i);
1047 pattern: adt_subpattern(i, variant_opt),
1049 }).collect::<Vec<_>>()
1053 let kind = match cv.ty.sty {
1056 ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
1059 "floating-point types cannot be used in patterns",
1061 PatternKind::Constant {
1065 ty::Adt(adt_def, _) if adt_def.is_union() => {
1066 // Matching on union fields is unsafe, we can't hide it in constants
1067 *saw_const_match_error = true;
1068 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
1071 // keep old code until future-compat upgraded to errors.
1072 ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, sym::structural_match) => {
1073 let path = self.tcx.def_path_str(adt_def.did);
1075 "to use a constant of type `{}` in a pattern, \
1076 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
1080 *saw_const_match_error = true;
1081 self.tcx.sess.span_err(span, &msg);
1084 // keep old code until future-compat upgraded to errors.
1085 ty::Ref(_, ty::TyS { sty: ty::Adt(adt_def, _), .. }, _)
1086 if !self.tcx.has_attr(adt_def.did, sym::structural_match) => {
1087 // HACK(estebank): Side-step ICE #53708, but anything other than erroring here
1088 // would be wrong. Returnging `PatternKind::Wild` is not technically correct.
1089 let path = self.tcx.def_path_str(adt_def.did);
1091 "to use a constant of type `{}` in a pattern, \
1092 `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
1096 *saw_const_match_error = true;
1097 self.tcx.sess.span_err(span, &msg);
1100 ty::Adt(adt_def, substs) if adt_def.is_enum() => {
1101 let variant_index = const_variant_index(self.tcx, self.param_env, cv);
1102 let subpatterns = adt_subpatterns(
1103 adt_def.variants[variant_index].fields.len(),
1104 Some(variant_index),
1106 PatternKind::Variant {
1113 ty::Adt(adt_def, _) => {
1114 let struct_var = adt_def.non_enum_variant();
1116 subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1119 ty::Tuple(fields) => {
1121 subpatterns: adt_subpatterns(fields.len(), None),
1124 ty::Array(_, n) => {
1125 PatternKind::Array {
1126 prefix: (0..n.unwrap_usize(self.tcx))
1127 .map(|i| adt_subpattern(i as usize, None))
1134 PatternKind::Constant {
1143 kind: Box::new(kind),
1148 /// This method traverses the structure of `ty`, trying to find an
1149 /// instance of an ADT (i.e. struct or enum) that was declared without
1150 /// the `#[structural_match]` attribute.
1152 /// The "structure of a type" includes all components that would be
1153 /// considered when doing a pattern match on a constant of that
1156 /// * This means this method descends into fields of structs/enums,
1157 /// and also descends into the inner type `T` of `&T` and `&mut T`
1159 /// * The traversal doesn't dereference unsafe pointers (`*const T`,
1160 /// `*mut T`), and it does not visit the type arguments of an
1161 /// instantiated generic like `PhantomData<T>`.
1163 /// The reason we do this search is Rust currently require all ADT's
1164 /// reachable from a constant's type to be annotated with
1165 /// `#[structural_match]`, an attribute which essentially says that
1166 /// the implementation of `PartialEq::eq` behaves *equivalently* to a
1167 /// comparison against the unfolded structure.
1169 /// For more background on why Rust has this requirement, and issues
1170 /// that arose when the requirement was not enforced completely, see
1171 /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307.
1172 fn search_for_adt_without_structural_match<'tcx>(tcx: TyCtxt<'tcx>,
1174 -> Option<&'tcx AdtDef>
1176 // Import here (not mod level), because `TypeFoldable::fold_with`
1177 // conflicts with `PatternFoldable::fold_with`
1178 use crate::rustc::ty::fold::TypeVisitor;
1179 use crate::rustc::ty::TypeFoldable;
1181 let mut search = Search { tcx, found: None, seen: FxHashSet::default() };
1182 ty.visit_with(&mut search);
1183 return search.found;
1185 struct Search<'tcx> {
1188 // records the first ADT we find without `#[structural_match`
1189 found: Option<&'tcx AdtDef>,
1191 // tracks ADT's previously encountered during search, so that
1192 // we will not recur on them again.
1193 seen: FxHashSet<&'tcx AdtDef>,
1196 impl<'tcx> TypeVisitor<'tcx> for Search<'tcx> {
1197 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
1198 debug!("Search visiting ty: {:?}", ty);
1200 let (adt_def, substs) = match ty.sty {
1201 ty::Adt(adt_def, substs) => (adt_def, substs),
1203 // `#[structural_match]` ignores substructure of
1204 // `*const _`/`*mut _`, so skip super_visit_with
1206 // (But still tell caller to continue search.)
1209 ty::Array(_, n) if n.assert_usize(self.tcx) == Some(0) => {
1210 // rust-lang/rust#62336: ignore type of contents
1215 ty.super_visit_with(self);
1220 if !self.tcx.has_attr(adt_def.did, sym::structural_match) {
1221 self.found = Some(&adt_def);
1222 debug!("Search found adt_def: {:?}", adt_def);
1223 return true // Halt visiting!
1226 if self.seen.contains(adt_def) {
1227 debug!("Search already seen adt_def: {:?}", adt_def);
1228 // let caller continue its search
1232 self.seen.insert(adt_def);
1234 // `#[structural_match]` does not care about the
1235 // instantiation of the generics in an ADT (it
1236 // instead looks directly at its fields outside
1237 // this match), so we skip super_visit_with.
1239 // (Must not recur on substs for `PhantomData<T>` cf
1240 // rust-lang/rust#55028 and rust-lang/rust#55837; but also
1241 // want to skip substs when only uses of generic are
1242 // behind unsafe pointers `*const T`/`*mut T`.)
1244 // even though we skip super_visit_with, we must recur on
1247 for field_ty in adt_def.all_fields().map(|field| field.ty(tcx, substs)) {
1248 if field_ty.visit_with(self) {
1249 // found an ADT without `#[structural_match]`; halt visiting!
1250 assert!(self.found.is_some());
1255 // Even though we do not want to recur on substs, we do
1256 // want our caller to continue its own search.
1262 impl UserAnnotatedTyHelpers<'tcx> for PatternContext<'_, 'tcx> {
1263 fn tcx(&self) -> TyCtxt<'tcx> {
1267 fn tables(&self) -> &ty::TypeckTables<'tcx> {
1273 pub trait PatternFoldable<'tcx> : Sized {
1274 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1275 self.super_fold_with(folder)
1278 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1281 pub trait PatternFolder<'tcx> : Sized {
1282 fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1283 pattern.super_fold_with(self)
1286 fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1287 kind.super_fold_with(self)
1292 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1293 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1294 let content: T = (**self).fold_with(folder);
1299 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1300 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1301 self.iter().map(|t| t.fold_with(folder)).collect()
1305 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1306 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1307 self.as_ref().map(|t| t.fold_with(folder))
1311 macro_rules! CloneImpls {
1312 (<$lt_tcx:tt> $($ty:ty),+) => {
1314 impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1315 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1324 Span, Field, Mutability, ast::Name, hir::HirId, usize, ty::Const<'tcx>,
1325 Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1326 SubstsRef<'tcx>, &'tcx Kind<'tcx>, UserType<'tcx>,
1327 UserTypeProjection, PatternTypeProjection<'tcx>
1330 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1331 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1333 field: self.field.fold_with(folder),
1334 pattern: self.pattern.fold_with(folder)
1339 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1340 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1341 folder.fold_pattern(self)
1344 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1346 ty: self.ty.fold_with(folder),
1347 span: self.span.fold_with(folder),
1348 kind: self.kind.fold_with(folder)
1353 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1354 fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1355 folder.fold_pattern_kind(self)
1358 fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1360 PatternKind::Wild => PatternKind::Wild,
1361 PatternKind::AscribeUserType {
1363 ascription: Ascription {
1368 } => PatternKind::AscribeUserType {
1369 subpattern: subpattern.fold_with(folder),
1370 ascription: Ascription {
1371 user_ty: user_ty.fold_with(folder),
1376 PatternKind::Binding {
1383 } => PatternKind::Binding {
1384 mutability: mutability.fold_with(folder),
1385 name: name.fold_with(folder),
1386 mode: mode.fold_with(folder),
1387 var: var.fold_with(folder),
1388 ty: ty.fold_with(folder),
1389 subpattern: subpattern.fold_with(folder),
1391 PatternKind::Variant {
1396 } => PatternKind::Variant {
1397 adt_def: adt_def.fold_with(folder),
1398 substs: substs.fold_with(folder),
1400 subpatterns: subpatterns.fold_with(folder)
1404 } => PatternKind::Leaf {
1405 subpatterns: subpatterns.fold_with(folder),
1407 PatternKind::Deref {
1409 } => PatternKind::Deref {
1410 subpattern: subpattern.fold_with(folder),
1412 PatternKind::Constant {
1414 } => PatternKind::Constant {
1417 PatternKind::Range(PatternRange {
1422 }) => PatternKind::Range(PatternRange {
1425 ty: ty.fold_with(folder),
1428 PatternKind::Slice {
1432 } => PatternKind::Slice {
1433 prefix: prefix.fold_with(folder),
1434 slice: slice.fold_with(folder),
1435 suffix: suffix.fold_with(folder)
1437 PatternKind::Array {
1441 } => PatternKind::Array {
1442 prefix: prefix.fold_with(folder),
1443 slice: slice.fold_with(folder),
1444 suffix: suffix.fold_with(folder)
1450 pub fn compare_const_vals<'tcx>(
1452 a: &'tcx ty::Const<'tcx>,
1453 b: &'tcx ty::Const<'tcx>,
1454 ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1455 ) -> Option<Ordering> {
1456 trace!("compare_const_vals: {:?}, {:?}", a, b);
1458 let from_bool = |v: bool| {
1460 Some(Ordering::Equal)
1466 let fallback = || from_bool(a == b);
1468 // Use the fallback if any type differs
1469 if a.ty != b.ty || a.ty != ty.value {
1473 // FIXME: This should use assert_bits(ty) instead of use_bits
1474 // but triggers possibly bugs due to mismatching of arrays and slices
1475 if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1476 use ::rustc_apfloat::Float;
1477 return match ty.value.sty {
1478 ty::Float(ast::FloatTy::F32) => {
1479 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1480 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1483 ty::Float(ast::FloatTy::F64) => {
1484 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1485 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1489 use rustc::ty::layout::{Integer, IntegerExt};
1490 use syntax::attr::SignedInt;
1491 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
1492 let a = sign_extend(a, size);
1493 let b = sign_extend(b, size);
1494 Some((a as i128).cmp(&(b as i128)))
1496 _ => Some(a.cmp(&b)),
1500 if let ty::Str = ty.value.sty {
1501 match (a.val, b.val) {
1503 ConstValue::Slice { data: alloc_a, start: offset_a, end: end_a },
1504 ConstValue::Slice { data: alloc_b, start: offset_b, end: end_b },
1506 let len_a = end_a - offset_a;
1507 let len_b = end_b - offset_b;
1508 let a = alloc_a.get_bytes(
1510 // invent a pointer, only the offset is relevant anyway
1511 Pointer::new(AllocId(0), Size::from_bytes(offset_a as u64)),
1512 Size::from_bytes(len_a as u64),
1514 let b = alloc_b.get_bytes(
1516 // invent a pointer, only the offset is relevant anyway
1517 Pointer::new(AllocId(0), Size::from_bytes(offset_b as u64)),
1518 Size::from_bytes(len_b as u64),
1520 if let (Ok(a), Ok(b)) = (a, b) {
1521 return from_bool(a == b);