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