]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/mod.rs
Type annotations in associated constant patterns.
[rust.git] / src / librustc_mir / hair / pattern / mod.rs
1 //! Code to validate patterns/matches
2
3 mod _match;
4 mod check_match;
5
6 pub use self::check_match::check_crate;
7 pub(crate) use self::check_match::check_match;
8
9 use const_eval::{const_field, const_variant_index};
10
11 use hair::util::UserAnnotatedTyHelpers;
12 use hair::constant::*;
13
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;
24
25 use rustc_data_structures::indexed_vec::Idx;
26
27 use std::cmp::Ordering;
28 use std::fmt;
29 use syntax::ast;
30 use syntax::ptr::P;
31 use syntax_pos::Span;
32
33 #[derive(Clone, Debug)]
34 pub enum PatternError {
35     AssociatedConstInPattern(Span),
36     StaticInPattern(Span),
37     FloatBug,
38     NonConstPath(Span),
39 }
40
41 #[derive(Copy, Clone, Debug)]
42 pub enum BindingMode<'tcx> {
43     ByValue,
44     ByRef(Region<'tcx>, BorrowKind),
45 }
46
47 #[derive(Clone, Debug)]
48 pub struct FieldPattern<'tcx> {
49     pub field: Field,
50     pub pattern: Pattern<'tcx>,
51 }
52
53 #[derive(Clone, Debug)]
54 pub struct Pattern<'tcx> {
55     pub ty: Ty<'tcx>,
56     pub span: Span,
57     pub kind: Box<PatternKind<'tcx>>,
58 }
59
60
61 #[derive(Clone, Debug)]
62 pub(crate) struct PatternTypeProjections<'tcx> {
63     contents: Vec<(PatternTypeProjection<'tcx>, Span)>,
64 }
65
66 impl<'tcx> PatternTypeProjections<'tcx> {
67     pub(crate) fn user_ty(
68         self,
69         annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
70     ) -> UserTypeProjections<'tcx> {
71         UserTypeProjections::from_projections(
72             self.contents
73                 .into_iter()
74                 .map(|(pat_ty_proj, span)| (pat_ty_proj.user_ty(annotations, span), span))
75         )
76     }
77
78     pub(crate) fn none() -> Self {
79         PatternTypeProjections { contents: vec![] }
80     }
81
82     pub(crate) fn ref_binding(&self) -> Self {
83         // FIXME(#55401): ignore for now
84         PatternTypeProjections { contents: vec![] }
85     }
86
87     fn map_projs(&self,
88                  mut f: impl FnMut(&PatternTypeProjection<'tcx>) -> PatternTypeProjection<'tcx>)
89                  -> Self
90     {
91         PatternTypeProjections {
92             contents: self.contents
93                 .iter()
94                 .map(|(proj, span)| (f(proj), *span))
95                 .collect(), }
96     }
97
98     pub(crate) fn index(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.index()) }
99
100     pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
101         self.map_projs(|pat_ty_proj| pat_ty_proj.subslice(from, to))
102     }
103
104     pub(crate) fn deref(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.deref()) }
105
106     pub(crate) fn leaf(&self, field: Field) -> Self {
107         self.map_projs(|pat_ty_proj| pat_ty_proj.leaf(field))
108     }
109
110     pub(crate) fn variant(&self,
111                           adt_def: &'tcx AdtDef,
112                           variant_index: VariantIdx,
113                           field: Field) -> Self {
114         self.map_projs(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
115     }
116
117     pub(crate) fn add_user_type(&self, user_ty: &PatternTypeProjection<'tcx>, sp: Span) -> Self {
118         let mut new = self.clone();
119         new.contents.push((user_ty.clone(), sp));
120         new
121     }
122 }
123
124 #[derive(Clone, Debug)]
125 pub struct PatternTypeProjection<'tcx> {
126     pub base: CanonicalUserTypeAnnotation<'tcx>,
127     pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
128 }
129
130 impl<'tcx> PatternTypeProjection<'tcx> {
131     pub(crate) fn index(&self) -> Self {
132         let mut new = self.clone();
133         new.projs.push(ProjectionElem::Index(()));
134         new
135     }
136
137     pub(crate) fn subslice(&self, from: u32, to: u32) -> Self {
138         let mut new = self.clone();
139         new.projs.push(ProjectionElem::Subslice { from, to });
140         new
141     }
142
143     pub(crate) fn deref(&self) -> Self {
144         let mut new = self.clone();
145         new.projs.push(ProjectionElem::Deref);
146         new
147     }
148
149     pub(crate) fn leaf(&self, field: Field) -> Self {
150         let mut new = self.clone();
151         new.projs.push(ProjectionElem::Field(field, ()));
152         new
153     }
154
155     pub(crate) fn variant(&self,
156                           adt_def: &'tcx AdtDef,
157                           variant_index: VariantIdx,
158                           field: Field) -> Self {
159         let mut new = self.clone();
160         new.projs.push(ProjectionElem::Downcast(adt_def, variant_index));
161         new.projs.push(ProjectionElem::Field(field, ()));
162         new
163     }
164
165     pub(crate) fn from_user_type(user_annotation: CanonicalUserTypeAnnotation<'tcx>) -> Self {
166         Self {
167             base: user_annotation,
168             projs: Vec::new(),
169         }
170     }
171
172     pub(crate) fn user_ty(
173         self,
174         annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
175         span: Span,
176     ) -> UserTypeProjection<'tcx> {
177         let annotation_index = annotations.push((span, self.base));
178         UserTypeProjection {
179             base: annotation_index,
180             projs: self.projs
181         }
182     }
183 }
184
185 #[derive(Clone, Debug)]
186 pub enum PatternKind<'tcx> {
187     Wild,
188
189     AscribeUserType {
190         user_ty: PatternTypeProjection<'tcx>,
191         subpattern: Pattern<'tcx>,
192         user_ty_span: Span,
193     },
194
195     /// x, ref x, x @ P, etc
196     Binding {
197         mutability: Mutability,
198         name: ast::Name,
199         mode: BindingMode<'tcx>,
200         var: ast::NodeId,
201         ty: Ty<'tcx>,
202         subpattern: Option<Pattern<'tcx>>,
203     },
204
205     /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
206     Variant {
207         adt_def: &'tcx AdtDef,
208         substs: &'tcx Substs<'tcx>,
209         variant_index: VariantIdx,
210         subpatterns: Vec<FieldPattern<'tcx>>,
211     },
212
213     /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
214     Leaf {
215         subpatterns: Vec<FieldPattern<'tcx>>,
216     },
217
218     /// box P, &P, &mut P, etc
219     Deref {
220         subpattern: Pattern<'tcx>,
221     },
222
223     Constant {
224         value: &'tcx ty::Const<'tcx>,
225     },
226
227     Range(PatternRange<'tcx>),
228
229     /// matches against a slice, checking the length and extracting elements.
230     /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
231     /// e.g., `&[ref xs..]`.
232     Slice {
233         prefix: Vec<Pattern<'tcx>>,
234         slice: Option<Pattern<'tcx>>,
235         suffix: Vec<Pattern<'tcx>>,
236     },
237
238     /// fixed match against an array, irrefutable
239     Array {
240         prefix: Vec<Pattern<'tcx>>,
241         slice: Option<Pattern<'tcx>>,
242         suffix: Vec<Pattern<'tcx>>,
243     },
244 }
245
246 #[derive(Clone, Copy, Debug, PartialEq)]
247 pub struct PatternRange<'tcx> {
248     pub lo: &'tcx ty::Const<'tcx>,
249     pub hi: &'tcx ty::Const<'tcx>,
250     pub ty: Ty<'tcx>,
251     pub end: RangeEnd,
252 }
253
254 impl<'tcx> fmt::Display for Pattern<'tcx> {
255     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
256         match *self.kind {
257             PatternKind::Wild => write!(f, "_"),
258             PatternKind::AscribeUserType { ref subpattern, .. } =>
259                 write!(f, "{}: _", subpattern),
260             PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
261                 let is_mut = match mode {
262                     BindingMode::ByValue => mutability == Mutability::Mut,
263                     BindingMode::ByRef(_, bk) => {
264                         write!(f, "ref ")?;
265                         match bk { BorrowKind::Mut { .. } => true, _ => false }
266                     }
267                 };
268                 if is_mut {
269                     write!(f, "mut ")?;
270                 }
271                 write!(f, "{}", name)?;
272                 if let Some(ref subpattern) = *subpattern {
273                     write!(f, " @ {}", subpattern)?;
274                 }
275                 Ok(())
276             }
277             PatternKind::Variant { ref subpatterns, .. } |
278             PatternKind::Leaf { ref subpatterns } => {
279                 let variant = match *self.kind {
280                     PatternKind::Variant { adt_def, variant_index, .. } => {
281                         Some(&adt_def.variants[variant_index])
282                     }
283                     _ => if let ty::Adt(adt, _) = self.ty.sty {
284                         if !adt.is_enum() {
285                             Some(&adt.variants[VariantIdx::new(0)])
286                         } else {
287                             None
288                         }
289                     } else {
290                         None
291                     }
292                 };
293
294                 let mut first = true;
295                 let mut start_or_continue = || if first { first = false; "" } else { ", " };
296
297                 if let Some(variant) = variant {
298                     write!(f, "{}", variant.ident)?;
299
300                     // Only for Adt we can have `S {...}`,
301                     // which we handle separately here.
302                     if variant.ctor_kind == CtorKind::Fictive {
303                         write!(f, " {{ ")?;
304
305                         let mut printed = 0;
306                         for p in subpatterns {
307                             if let PatternKind::Wild = *p.pattern.kind {
308                                 continue;
309                             }
310                             let name = variant.fields[p.field.index()].ident;
311                             write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
312                             printed += 1;
313                         }
314
315                         if printed < variant.fields.len() {
316                             write!(f, "{}..", start_or_continue())?;
317                         }
318
319                         return write!(f, " }}");
320                     }
321                 }
322
323                 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
324                 if num_fields != 0 || variant.is_none() {
325                     write!(f, "(")?;
326                     for i in 0..num_fields {
327                         write!(f, "{}", start_or_continue())?;
328
329                         // Common case: the field is where we expect it.
330                         if let Some(p) = subpatterns.get(i) {
331                             if p.field.index() == i {
332                                 write!(f, "{}", p.pattern)?;
333                                 continue;
334                             }
335                         }
336
337                         // Otherwise, we have to go looking for it.
338                         if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
339                             write!(f, "{}", p.pattern)?;
340                         } else {
341                             write!(f, "_")?;
342                         }
343                     }
344                     write!(f, ")")?;
345                 }
346
347                 Ok(())
348             }
349             PatternKind::Deref { ref subpattern } => {
350                 match self.ty.sty {
351                     ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
352                     ty::Ref(_, _, mutbl) => {
353                         write!(f, "&")?;
354                         if mutbl == hir::MutMutable {
355                             write!(f, "mut ")?;
356                         }
357                     }
358                     _ => bug!("{} is a bad Deref pattern type", self.ty)
359                 }
360                 write!(f, "{}", subpattern)
361             }
362             PatternKind::Constant { value } => {
363                 fmt_const_val(f, value)
364             }
365             PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
366                 fmt_const_val(f, lo)?;
367                 match end {
368                     RangeEnd::Included => write!(f, "..=")?,
369                     RangeEnd::Excluded => write!(f, "..")?,
370                 }
371                 fmt_const_val(f, hi)
372             }
373             PatternKind::Slice { ref prefix, ref slice, ref suffix } |
374             PatternKind::Array { ref prefix, ref slice, ref suffix } => {
375                 let mut first = true;
376                 let mut start_or_continue = || if first { first = false; "" } else { ", " };
377                 write!(f, "[")?;
378                 for p in prefix {
379                     write!(f, "{}{}", start_or_continue(), p)?;
380                 }
381                 if let Some(ref slice) = *slice {
382                     write!(f, "{}", start_or_continue())?;
383                     match *slice.kind {
384                         PatternKind::Wild => {}
385                         _ => write!(f, "{}", slice)?
386                     }
387                     write!(f, "..")?;
388                 }
389                 for p in suffix {
390                     write!(f, "{}{}", start_or_continue(), p)?;
391                 }
392                 write!(f, "]")
393             }
394         }
395     }
396 }
397
398 pub struct PatternContext<'a, 'tcx: 'a> {
399     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
400     pub param_env: ty::ParamEnv<'tcx>,
401     pub tables: &'a ty::TypeckTables<'tcx>,
402     pub substs: &'tcx Substs<'tcx>,
403     pub errors: Vec<PatternError>,
404 }
405
406 impl<'a, 'tcx> Pattern<'tcx> {
407     pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
408                     param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
409                     tables: &'a ty::TypeckTables<'tcx>,
410                     pat: &'tcx hir::Pat) -> Self {
411         let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
412         let result = pcx.lower_pattern(pat);
413         if !pcx.errors.is_empty() {
414             let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
415             tcx.sess.delay_span_bug(pat.span, &msg);
416         }
417         debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
418         result
419     }
420 }
421
422 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
423     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
424                param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
425                tables: &'a ty::TypeckTables<'tcx>) -> Self {
426         PatternContext {
427             tcx,
428             param_env: param_env_and_substs.param_env,
429             tables,
430             substs: param_env_and_substs.value,
431             errors: vec![]
432         }
433     }
434
435     pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
436         // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
437         // pattern has the type that results *after* dereferencing. For example, in this code:
438         //
439         // ```
440         // match &&Some(0i32) {
441         //     Some(n) => { ... },
442         //     _ => { ... },
443         // }
444         // ```
445         //
446         // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
447         // determined in rustc_typeck::check::match). The adjustments would be
448         //
449         // `vec![&&Option<i32>, &Option<i32>]`.
450         //
451         // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
452         // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
453         // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
454         // gets the least-dereferenced type).
455         let unadjusted_pat = self.lower_pattern_unadjusted(pat);
456         self.tables
457             .pat_adjustments()
458             .get(pat.hir_id)
459             .unwrap_or(&vec![])
460             .iter()
461             .rev()
462             .fold(unadjusted_pat, |pat, ref_ty| {
463                     debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
464                     Pattern {
465                         span: pat.span,
466                         ty: ref_ty,
467                         kind: Box::new(PatternKind::Deref { subpattern: pat }),
468                     }
469                 },
470             )
471     }
472
473     fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
474         let mut ty = self.tables.node_id_to_type(pat.hir_id);
475
476         let kind = match pat.node {
477             PatKind::Wild => PatternKind::Wild,
478
479             PatKind::Lit(ref value) => self.lower_lit(value),
480
481             PatKind::Range(ref lo_expr, ref hi_expr, end) => {
482                 match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
483                     (PatternKind::Constant { value: lo },
484                      PatternKind::Constant { value: hi }) => {
485                         use std::cmp::Ordering;
486                         let cmp = compare_const_vals(
487                             self.tcx,
488                             lo,
489                             hi,
490                             self.param_env.and(ty),
491                         );
492                         match (end, cmp) {
493                             (RangeEnd::Excluded, Some(Ordering::Less)) =>
494                                 PatternKind::Range(PatternRange { lo, hi, ty, end }),
495                             (RangeEnd::Excluded, _) => {
496                                 span_err!(
497                                     self.tcx.sess,
498                                     lo_expr.span,
499                                     E0579,
500                                     "lower range bound must be less than upper",
501                                 );
502                                 PatternKind::Wild
503                             }
504                             (RangeEnd::Included, Some(Ordering::Equal)) => {
505                                 PatternKind::Constant { value: lo }
506                             }
507                             (RangeEnd::Included, Some(Ordering::Less)) => {
508                                 PatternKind::Range(PatternRange { lo, hi, ty, end })
509                             }
510                             (RangeEnd::Included, _) => {
511                                 let mut err = struct_span_err!(
512                                     self.tcx.sess,
513                                     lo_expr.span,
514                                     E0030,
515                                     "lower range bound must be less than or equal to upper"
516                                 );
517                                 err.span_label(
518                                     lo_expr.span,
519                                     "lower bound larger than upper bound",
520                                 );
521                                 if self.tcx.sess.teach(&err.get_code().unwrap()) {
522                                     err.note("When matching against a range, the compiler \
523                                               verifies that the range is non-empty. Range \
524                                               patterns include both end-points, so this is \
525                                               equivalent to requiring the start of the range \
526                                               to be less than or equal to the end of the range.");
527                                 }
528                                 err.emit();
529                                 PatternKind::Wild
530                             }
531                         }
532                     }
533                     _ => PatternKind::Wild
534                 }
535             }
536
537             PatKind::Path(ref qpath) => {
538                 return self.lower_path(qpath, pat.hir_id, pat.span);
539             }
540
541             PatKind::Ref(ref subpattern, _) |
542             PatKind::Box(ref subpattern) => {
543                 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
544             }
545
546             PatKind::Slice(ref prefix, ref slice, ref suffix) => {
547                 match ty.sty {
548                     ty::Ref(_, ty, _) =>
549                         PatternKind::Deref {
550                             subpattern: Pattern {
551                                 ty,
552                                 span: pat.span,
553                                 kind: Box::new(self.slice_or_array_pattern(
554                                     pat.span, ty, prefix, slice, suffix))
555                             },
556                         },
557                     ty::Slice(..) |
558                     ty::Array(..) =>
559                         self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
560                     ty::Error => { // Avoid ICE
561                         return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
562                     }
563                     ref sty =>
564                         span_bug!(
565                             pat.span,
566                             "unexpanded type for vector pattern: {:?}",
567                             sty),
568                 }
569             }
570
571             PatKind::Tuple(ref subpatterns, ddpos) => {
572                 match ty.sty {
573                     ty::Tuple(ref tys) => {
574                         let subpatterns =
575                             subpatterns.iter()
576                                        .enumerate_and_adjust(tys.len(), ddpos)
577                                        .map(|(i, subpattern)| FieldPattern {
578                                             field: Field::new(i),
579                                             pattern: self.lower_pattern(subpattern)
580                                        })
581                                        .collect();
582
583                         PatternKind::Leaf { subpatterns }
584                     }
585                     ty::Error => { // Avoid ICE (#50577)
586                         return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
587                     }
588                     ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
589                 }
590             }
591
592             PatKind::Binding(_, id, ident, ref sub) => {
593                 let var_ty = self.tables.node_id_to_type(pat.hir_id);
594                 let region = match var_ty.sty {
595                     ty::Ref(r, _, _) => Some(r),
596                     ty::Error => { // Avoid ICE
597                         return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
598                     }
599                     _ => None,
600                 };
601                 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
602                                                          .expect("missing binding mode");
603                 let (mutability, mode) = match bm {
604                     ty::BindByValue(hir::MutMutable) =>
605                         (Mutability::Mut, BindingMode::ByValue),
606                     ty::BindByValue(hir::MutImmutable) =>
607                         (Mutability::Not, BindingMode::ByValue),
608                     ty::BindByReference(hir::MutMutable) =>
609                         (Mutability::Not, BindingMode::ByRef(
610                             region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
611                     ty::BindByReference(hir::MutImmutable) =>
612                         (Mutability::Not, BindingMode::ByRef(
613                             region.unwrap(), BorrowKind::Shared)),
614                 };
615
616                 // A ref x pattern is the same node used for x, and as such it has
617                 // x's type, which is &T, where we want T (the type being matched).
618                 if let ty::BindByReference(_) = bm {
619                     if let ty::Ref(_, rty, _) = ty.sty {
620                         ty = rty;
621                     } else {
622                         bug!("`ref {}` has wrong type {}", ident, ty);
623                     }
624                 }
625
626                 PatternKind::Binding {
627                     mutability,
628                     mode,
629                     name: ident.name,
630                     var: id,
631                     ty: var_ty,
632                     subpattern: self.lower_opt_pattern(sub),
633                 }
634             }
635
636             PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
637                 let def = self.tables.qpath_def(qpath, pat.hir_id);
638                 let adt_def = match ty.sty {
639                     ty::Adt(adt_def, _) => adt_def,
640                     ty::Error => { // Avoid ICE (#50585)
641                         return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
642                     }
643                     _ => span_bug!(pat.span,
644                                    "tuple struct pattern not applied to an ADT {:?}",
645                                    ty.sty),
646                 };
647                 let variant_def = adt_def.variant_of_def(def);
648
649                 let subpatterns =
650                         subpatterns.iter()
651                                    .enumerate_and_adjust(variant_def.fields.len(), ddpos)
652                                    .map(|(i, field)| FieldPattern {
653                                        field: Field::new(i),
654                                        pattern: self.lower_pattern(field),
655                                    })
656                     .collect();
657
658                 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
659             }
660
661             PatKind::Struct(ref qpath, ref fields, _) => {
662                 let def = self.tables.qpath_def(qpath, pat.hir_id);
663                 let subpatterns =
664                     fields.iter()
665                           .map(|field| {
666                               FieldPattern {
667                                   field: Field::new(self.tcx.field_index(field.node.id,
668                                                                          self.tables)),
669                                   pattern: self.lower_pattern(&field.node.pat),
670                               }
671                           })
672                           .collect();
673
674                 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
675             }
676         };
677
678         Pattern {
679             span: pat.span,
680             ty,
681             kind: Box::new(kind),
682         }
683     }
684
685     fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
686         pats.iter().map(|p| self.lower_pattern(p)).collect()
687     }
688
689     fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
690     {
691         pat.as_ref().map(|p| self.lower_pattern(p))
692     }
693
694     fn flatten_nested_slice_patterns(
695         &mut self,
696         prefix: Vec<Pattern<'tcx>>,
697         slice: Option<Pattern<'tcx>>,
698         suffix: Vec<Pattern<'tcx>>)
699         -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
700     {
701         let orig_slice = match slice {
702             Some(orig_slice) => orig_slice,
703             None => return (prefix, slice, suffix)
704         };
705         let orig_prefix = prefix;
706         let orig_suffix = suffix;
707
708         // dance because of intentional borrow-checker stupidity.
709         let kind = *orig_slice.kind;
710         match kind {
711             PatternKind::Slice { prefix, slice, mut suffix } |
712             PatternKind::Array { prefix, slice, mut suffix } => {
713                 let mut orig_prefix = orig_prefix;
714
715                 orig_prefix.extend(prefix);
716                 suffix.extend(orig_suffix);
717
718                 (orig_prefix, slice, suffix)
719             }
720             _ => {
721                 (orig_prefix, Some(Pattern {
722                     kind: box kind, ..orig_slice
723                 }), orig_suffix)
724             }
725         }
726     }
727
728     fn slice_or_array_pattern(
729         &mut self,
730         span: Span,
731         ty: Ty<'tcx>,
732         prefix: &'tcx [P<hir::Pat>],
733         slice: &'tcx Option<P<hir::Pat>>,
734         suffix: &'tcx [P<hir::Pat>])
735         -> PatternKind<'tcx>
736     {
737         let prefix = self.lower_patterns(prefix);
738         let slice = self.lower_opt_pattern(slice);
739         let suffix = self.lower_patterns(suffix);
740         let (prefix, slice, suffix) =
741             self.flatten_nested_slice_patterns(prefix, slice, suffix);
742
743         match ty.sty {
744             ty::Slice(..) => {
745                 // matching a slice or fixed-length array
746                 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
747             }
748
749             ty::Array(_, len) => {
750                 // fixed-length array
751                 let len = len.unwrap_usize(self.tcx);
752                 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
753                 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
754             }
755
756             _ => {
757                 span_bug!(span, "bad slice pattern type {:?}", ty);
758             }
759         }
760     }
761
762     fn lower_variant_or_leaf(
763         &mut self,
764         def: Def,
765         hir_id: hir::HirId,
766         span: Span,
767         ty: Ty<'tcx>,
768         subpatterns: Vec<FieldPattern<'tcx>>,
769     ) -> PatternKind<'tcx> {
770         let mut kind = match def {
771             Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
772                 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
773                 let adt_def = self.tcx.adt_def(enum_id);
774                 if adt_def.is_enum() {
775                     let substs = match ty.sty {
776                         ty::Adt(_, substs) |
777                         ty::FnDef(_, substs) => substs,
778                         ty::Error => {  // Avoid ICE (#50585)
779                             return PatternKind::Wild;
780                         }
781                         _ => bug!("inappropriate type for def: {:?}", ty.sty),
782                     };
783                     PatternKind::Variant {
784                         adt_def,
785                         substs,
786                         variant_index: adt_def.variant_index_with_id(variant_id),
787                         subpatterns,
788                     }
789                 } else {
790                     PatternKind::Leaf { subpatterns }
791                 }
792             }
793
794             Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
795             Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
796                 PatternKind::Leaf { subpatterns }
797             }
798
799             _ => {
800                 self.errors.push(PatternError::NonConstPath(span));
801                 PatternKind::Wild
802             }
803         };
804
805         if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
806             debug!("lower_variant_or_leaf: user_ty={:?} span={:?}", user_ty, span);
807             kind = PatternKind::AscribeUserType {
808                 subpattern: Pattern {
809                     span,
810                     ty,
811                     kind: Box::new(kind),
812                 },
813                 user_ty: PatternTypeProjection::from_user_type(user_ty),
814                 user_ty_span: span,
815             };
816         }
817
818         kind
819     }
820
821     /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
822     /// it to `const_to_pat`. Any other path (like enum variants without fields)
823     /// is converted to the corresponding pattern via `lower_variant_or_leaf`
824     fn lower_path(&mut self,
825                   qpath: &hir::QPath,
826                   id: hir::HirId,
827                   span: Span)
828                   -> Pattern<'tcx> {
829         let ty = self.tables.node_id_to_type(id);
830         let def = self.tables.qpath_def(qpath, id);
831         let is_associated_const = match def {
832             Def::AssociatedConst(_) => true,
833             _ => false,
834         };
835         let kind = match def {
836             Def::Const(def_id) | Def::AssociatedConst(def_id) => {
837                 let substs = self.tables.node_substs(id);
838                 match ty::Instance::resolve(
839                     self.tcx,
840                     self.param_env,
841                     def_id,
842                     substs,
843                 ) {
844                     Some(instance) => {
845                         let cid = GlobalId {
846                             instance,
847                             promoted: None,
848                         };
849                         match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
850                             Ok(value) => {
851                                 let pattern = self.const_to_pat(instance, value, id, span);
852                                 if !is_associated_const {
853                                     return pattern;
854                                 }
855
856                                 let user_provided_types = self.tables().user_provided_types();
857                                 return if let Some(u_ty) = user_provided_types.get(id) {
858                                     let user_ty = PatternTypeProjection::from_user_type(*u_ty);
859                                     Pattern {
860                                         span,
861                                         kind: Box::new(
862                                             PatternKind::AscribeUserType {
863                                                 subpattern: pattern,
864                                                 user_ty,
865                                                 user_ty_span: span,
866                                             }
867                                         ),
868                                         ty: value.ty,
869                                     }
870                                 } else {
871                                     pattern
872                                 }
873                             },
874                             Err(_) => {
875                                 self.tcx.sess.span_err(
876                                     span,
877                                     "could not evaluate constant pattern",
878                                 );
879                                 PatternKind::Wild
880                             }
881                         }
882                     },
883                     None => {
884                         self.errors.push(if is_associated_const {
885                             PatternError::AssociatedConstInPattern(span)
886                         } else {
887                             PatternError::StaticInPattern(span)
888                         });
889                         PatternKind::Wild
890                     },
891                 }
892             }
893             _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
894         };
895
896         Pattern {
897             span,
898             ty,
899             kind: Box::new(kind),
900         }
901     }
902
903     /// Converts literals, paths and negation of literals to patterns.
904     /// The special case for negation exists to allow things like -128i8
905     /// which would overflow if we tried to evaluate 128i8 and then negate
906     /// afterwards.
907     fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
908         match expr.node {
909             hir::ExprKind::Lit(ref lit) => {
910                 let ty = self.tables.expr_ty(expr);
911                 match lit_to_const(&lit.node, self.tcx, ty, false) {
912                     Ok(val) => {
913                         let instance = ty::Instance::new(
914                             self.tables.local_id_root.expect("literal outside any scope"),
915                             self.substs,
916                         );
917                         *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
918                     },
919                     Err(LitToConstError::UnparseableFloat) => {
920                         self.errors.push(PatternError::FloatBug);
921                         PatternKind::Wild
922                     },
923                     Err(LitToConstError::Reported) => PatternKind::Wild,
924                 }
925             },
926             hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
927             hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
928                 let ty = self.tables.expr_ty(expr);
929                 let lit = match expr.node {
930                     hir::ExprKind::Lit(ref lit) => lit,
931                     _ => span_bug!(expr.span, "not a literal: {:?}", expr),
932                 };
933                 match lit_to_const(&lit.node, self.tcx, ty, true) {
934                     Ok(val) => {
935                         let instance = ty::Instance::new(
936                             self.tables.local_id_root.expect("literal outside any scope"),
937                             self.substs,
938                         );
939                         *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
940                     },
941                     Err(LitToConstError::UnparseableFloat) => {
942                         self.errors.push(PatternError::FloatBug);
943                         PatternKind::Wild
944                     },
945                     Err(LitToConstError::Reported) => PatternKind::Wild,
946                 }
947             }
948             _ => span_bug!(expr.span, "not a literal: {:?}", expr),
949         }
950     }
951
952     /// Converts an evaluated constant to a pattern (if possible).
953     /// This means aggregate values (like structs and enums) are converted
954     /// to a pattern that matches the value (as if you'd compare via eq).
955     fn const_to_pat(
956         &self,
957         instance: ty::Instance<'tcx>,
958         cv: &'tcx ty::Const<'tcx>,
959         id: hir::HirId,
960         span: Span,
961     ) -> Pattern<'tcx> {
962         debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
963         let adt_subpattern = |i, variant_opt| {
964             let field = Field::new(i);
965             let val = const_field(
966                 self.tcx, self.param_env, instance,
967                 variant_opt, field, cv,
968             ).expect("field access failed");
969             self.const_to_pat(instance, val, id, span)
970         };
971         let adt_subpatterns = |n, variant_opt| {
972             (0..n).map(|i| {
973                 let field = Field::new(i);
974                 FieldPattern {
975                     field,
976                     pattern: adt_subpattern(i, variant_opt),
977                 }
978             }).collect::<Vec<_>>()
979         };
980         debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
981         let kind = match cv.ty.sty {
982             ty::Float(_) => {
983                 let id = self.tcx.hir().hir_to_node_id(id);
984                 self.tcx.lint_node(
985                     ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
986                     id,
987                     span,
988                     "floating-point types cannot be used in patterns",
989                 );
990                 PatternKind::Constant {
991                     value: cv,
992                 }
993             },
994             ty::Adt(adt_def, _) if adt_def.is_union() => {
995                 // Matching on union fields is unsafe, we can't hide it in constants
996                 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
997                 PatternKind::Wild
998             }
999             ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
1000                 let msg = format!("to use a constant of type `{}` in a pattern, \
1001                                     `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
1002                                     self.tcx.item_path_str(adt_def.did),
1003                                     self.tcx.item_path_str(adt_def.did));
1004                 self.tcx.sess.span_err(span, &msg);
1005                 PatternKind::Wild
1006             },
1007             ty::Adt(adt_def, substs) if adt_def.is_enum() => {
1008                 let variant_index = const_variant_index(
1009                     self.tcx, self.param_env, instance, cv
1010                 ).expect("const_variant_index failed");
1011                 let subpatterns = adt_subpatterns(
1012                     adt_def.variants[variant_index].fields.len(),
1013                     Some(variant_index),
1014                 );
1015                 PatternKind::Variant {
1016                     adt_def,
1017                     substs,
1018                     variant_index,
1019                     subpatterns,
1020                 }
1021             },
1022             ty::Adt(adt_def, _) => {
1023                 let struct_var = adt_def.non_enum_variant();
1024                 PatternKind::Leaf {
1025                     subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1026                 }
1027             }
1028             ty::Tuple(fields) => {
1029                 PatternKind::Leaf {
1030                     subpatterns: adt_subpatterns(fields.len(), None),
1031                 }
1032             }
1033             ty::Array(_, n) => {
1034                 PatternKind::Array {
1035                     prefix: (0..n.unwrap_usize(self.tcx))
1036                         .map(|i| adt_subpattern(i as usize, None))
1037                         .collect(),
1038                     slice: None,
1039                     suffix: Vec::new(),
1040                 }
1041             }
1042             _ => {
1043                 PatternKind::Constant {
1044                     value: cv,
1045                 }
1046             },
1047         };
1048
1049         Pattern {
1050             span,
1051             ty: cv.ty,
1052             kind: Box::new(kind),
1053         }
1054     }
1055 }
1056
1057 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1058     fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1059         self.tcx
1060     }
1061
1062     fn tables(&self) -> &ty::TypeckTables<'tcx> {
1063         self.tables
1064     }
1065 }
1066
1067
1068 pub trait PatternFoldable<'tcx> : Sized {
1069     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1070         self.super_fold_with(folder)
1071     }
1072
1073     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1074 }
1075
1076 pub trait PatternFolder<'tcx> : Sized {
1077     fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1078         pattern.super_fold_with(self)
1079     }
1080
1081     fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1082         kind.super_fold_with(self)
1083     }
1084 }
1085
1086
1087 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1088     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1089         let content: T = (**self).fold_with(folder);
1090         box content
1091     }
1092 }
1093
1094 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1095     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1096         self.iter().map(|t| t.fold_with(folder)).collect()
1097     }
1098 }
1099
1100 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1101     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1102         self.as_ref().map(|t| t.fold_with(folder))
1103     }
1104 }
1105
1106 macro_rules! CloneImpls {
1107     (<$lt_tcx:tt> $($ty:ty),+) => {
1108         $(
1109             impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1110                 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1111                     Clone::clone(self)
1112                 }
1113             }
1114         )+
1115     }
1116 }
1117
1118 CloneImpls!{ <'tcx>
1119     Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
1120     Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
1121     &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>,
1122     UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1123 }
1124
1125 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1126     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1127         FieldPattern {
1128             field: self.field.fold_with(folder),
1129             pattern: self.pattern.fold_with(folder)
1130         }
1131     }
1132 }
1133
1134 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1135     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1136         folder.fold_pattern(self)
1137     }
1138
1139     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1140         Pattern {
1141             ty: self.ty.fold_with(folder),
1142             span: self.span.fold_with(folder),
1143             kind: self.kind.fold_with(folder)
1144         }
1145     }
1146 }
1147
1148 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1149     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1150         folder.fold_pattern_kind(self)
1151     }
1152
1153     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1154         match *self {
1155             PatternKind::Wild => PatternKind::Wild,
1156             PatternKind::AscribeUserType {
1157                 ref subpattern,
1158                 ref user_ty,
1159                 user_ty_span,
1160             } => PatternKind::AscribeUserType {
1161                 subpattern: subpattern.fold_with(folder),
1162                 user_ty: user_ty.fold_with(folder),
1163                 user_ty_span,
1164             },
1165             PatternKind::Binding {
1166                 mutability,
1167                 name,
1168                 mode,
1169                 var,
1170                 ty,
1171                 ref subpattern,
1172             } => PatternKind::Binding {
1173                 mutability: mutability.fold_with(folder),
1174                 name: name.fold_with(folder),
1175                 mode: mode.fold_with(folder),
1176                 var: var.fold_with(folder),
1177                 ty: ty.fold_with(folder),
1178                 subpattern: subpattern.fold_with(folder),
1179             },
1180             PatternKind::Variant {
1181                 adt_def,
1182                 substs,
1183                 variant_index,
1184                 ref subpatterns,
1185             } => PatternKind::Variant {
1186                 adt_def: adt_def.fold_with(folder),
1187                 substs: substs.fold_with(folder),
1188                 variant_index,
1189                 subpatterns: subpatterns.fold_with(folder)
1190             },
1191             PatternKind::Leaf {
1192                 ref subpatterns,
1193             } => PatternKind::Leaf {
1194                 subpatterns: subpatterns.fold_with(folder),
1195             },
1196             PatternKind::Deref {
1197                 ref subpattern,
1198             } => PatternKind::Deref {
1199                 subpattern: subpattern.fold_with(folder),
1200             },
1201             PatternKind::Constant {
1202                 value
1203             } => PatternKind::Constant {
1204                 value: value.fold_with(folder)
1205             },
1206             PatternKind::Range(PatternRange {
1207                 lo,
1208                 hi,
1209                 ty,
1210                 end,
1211             }) => PatternKind::Range(PatternRange {
1212                 lo: lo.fold_with(folder),
1213                 hi: hi.fold_with(folder),
1214                 ty: ty.fold_with(folder),
1215                 end,
1216             }),
1217             PatternKind::Slice {
1218                 ref prefix,
1219                 ref slice,
1220                 ref suffix,
1221             } => PatternKind::Slice {
1222                 prefix: prefix.fold_with(folder),
1223                 slice: slice.fold_with(folder),
1224                 suffix: suffix.fold_with(folder)
1225             },
1226             PatternKind::Array {
1227                 ref prefix,
1228                 ref slice,
1229                 ref suffix
1230             } => PatternKind::Array {
1231                 prefix: prefix.fold_with(folder),
1232                 slice: slice.fold_with(folder),
1233                 suffix: suffix.fold_with(folder)
1234             },
1235         }
1236     }
1237 }
1238
1239 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1240     tcx: TyCtxt<'a, 'gcx, 'tcx>,
1241     a: &'tcx ty::Const<'tcx>,
1242     b: &'tcx ty::Const<'tcx>,
1243     ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1244 ) -> Option<Ordering> {
1245     trace!("compare_const_vals: {:?}, {:?}", a, b);
1246
1247     let from_bool = |v: bool| {
1248         if v {
1249             Some(Ordering::Equal)
1250         } else {
1251             None
1252         }
1253     };
1254
1255     let fallback = || from_bool(a == b);
1256
1257     // Use the fallback if any type differs
1258     if a.ty != b.ty || a.ty != ty.value {
1259         return fallback();
1260     }
1261
1262     let tcx = tcx.global_tcx();
1263     let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1264
1265     // FIXME: This should use assert_bits(ty) instead of use_bits
1266     // but triggers possibly bugs due to mismatching of arrays and slices
1267     if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1268         use ::rustc_apfloat::Float;
1269         return match ty.value.sty {
1270             ty::Float(ast::FloatTy::F32) => {
1271                 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1272                 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1273                 l.partial_cmp(&r)
1274             },
1275             ty::Float(ast::FloatTy::F64) => {
1276                 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1277                 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1278                 l.partial_cmp(&r)
1279             },
1280             ty::Int(_) => {
1281                 let layout = tcx.layout_of(ty).ok()?;
1282                 assert!(layout.abi.is_signed());
1283                 let a = sign_extend(a, layout.size);
1284                 let b = sign_extend(b, layout.size);
1285                 Some((a as i128).cmp(&(b as i128)))
1286             },
1287             _ => Some(a.cmp(&b)),
1288         }
1289     }
1290
1291     if let ty::Str = ty.value.sty {
1292         match (a.val, b.val) {
1293             (
1294                 ConstValue::ScalarPair(
1295                     Scalar::Ptr(ptr_a),
1296                     len_a,
1297                 ),
1298                 ConstValue::ScalarPair(
1299                     Scalar::Ptr(ptr_b),
1300                     len_b,
1301                 ),
1302             ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1303                 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1304                     if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1305                         if len_a == len_b {
1306                             let map = tcx.alloc_map.lock();
1307                             let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1308                             let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1309                             if alloc_a.bytes.len() as u128 == len_a {
1310                                 return from_bool(alloc_a == alloc_b);
1311                             }
1312                         }
1313                     }
1314                 }
1315             }
1316             _ => (),
1317         }
1318     }
1319
1320     fallback()
1321 }