]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/mod.rs
Refactor `UserTypeAnnotation`.
[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                                 return self.const_to_pat(instance, value, id, span)
852                             },
853                             Err(_) => {
854                                 self.tcx.sess.span_err(
855                                     span,
856                                     "could not evaluate constant pattern",
857                                 );
858                                 PatternKind::Wild
859                             }
860                         }
861                     },
862                     None => {
863                         self.errors.push(if is_associated_const {
864                             PatternError::AssociatedConstInPattern(span)
865                         } else {
866                             PatternError::StaticInPattern(span)
867                         });
868                         PatternKind::Wild
869                     },
870                 }
871             }
872             _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
873         };
874
875         Pattern {
876             span,
877             ty,
878             kind: Box::new(kind),
879         }
880     }
881
882     /// Converts literals, paths and negation of literals to patterns.
883     /// The special case for negation exists to allow things like -128i8
884     /// which would overflow if we tried to evaluate 128i8 and then negate
885     /// afterwards.
886     fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
887         match expr.node {
888             hir::ExprKind::Lit(ref lit) => {
889                 let ty = self.tables.expr_ty(expr);
890                 match lit_to_const(&lit.node, self.tcx, ty, false) {
891                     Ok(val) => {
892                         let instance = ty::Instance::new(
893                             self.tables.local_id_root.expect("literal outside any scope"),
894                             self.substs,
895                         );
896                         *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
897                     },
898                     Err(LitToConstError::UnparseableFloat) => {
899                         self.errors.push(PatternError::FloatBug);
900                         PatternKind::Wild
901                     },
902                     Err(LitToConstError::Reported) => PatternKind::Wild,
903                 }
904             },
905             hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
906             hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
907                 let ty = self.tables.expr_ty(expr);
908                 let lit = match expr.node {
909                     hir::ExprKind::Lit(ref lit) => lit,
910                     _ => span_bug!(expr.span, "not a literal: {:?}", expr),
911                 };
912                 match lit_to_const(&lit.node, self.tcx, ty, true) {
913                     Ok(val) => {
914                         let instance = ty::Instance::new(
915                             self.tables.local_id_root.expect("literal outside any scope"),
916                             self.substs,
917                         );
918                         *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
919                     },
920                     Err(LitToConstError::UnparseableFloat) => {
921                         self.errors.push(PatternError::FloatBug);
922                         PatternKind::Wild
923                     },
924                     Err(LitToConstError::Reported) => PatternKind::Wild,
925                 }
926             }
927             _ => span_bug!(expr.span, "not a literal: {:?}", expr),
928         }
929     }
930
931     /// Converts an evaluated constant to a pattern (if possible).
932     /// This means aggregate values (like structs and enums) are converted
933     /// to a pattern that matches the value (as if you'd compare via eq).
934     fn const_to_pat(
935         &self,
936         instance: ty::Instance<'tcx>,
937         cv: &'tcx ty::Const<'tcx>,
938         id: hir::HirId,
939         span: Span,
940     ) -> Pattern<'tcx> {
941         debug!("const_to_pat: cv={:#?}", cv);
942         let adt_subpattern = |i, variant_opt| {
943             let field = Field::new(i);
944             let val = const_field(
945                 self.tcx, self.param_env, instance,
946                 variant_opt, field, cv,
947             ).expect("field access failed");
948             self.const_to_pat(instance, val, id, span)
949         };
950         let adt_subpatterns = |n, variant_opt| {
951             (0..n).map(|i| {
952                 let field = Field::new(i);
953                 FieldPattern {
954                     field,
955                     pattern: adt_subpattern(i, variant_opt),
956                 }
957             }).collect::<Vec<_>>()
958         };
959         let kind = match cv.ty.sty {
960             ty::Float(_) => {
961                 let id = self.tcx.hir().hir_to_node_id(id);
962                 self.tcx.lint_node(
963                     ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
964                     id,
965                     span,
966                     "floating-point types cannot be used in patterns",
967                 );
968                 PatternKind::Constant {
969                     value: cv,
970                 }
971             },
972             ty::Adt(adt_def, _) if adt_def.is_union() => {
973                 // Matching on union fields is unsafe, we can't hide it in constants
974                 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
975                 PatternKind::Wild
976             }
977             ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
978                 let msg = format!("to use a constant of type `{}` in a pattern, \
979                                     `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
980                                     self.tcx.item_path_str(adt_def.did),
981                                     self.tcx.item_path_str(adt_def.did));
982                 self.tcx.sess.span_err(span, &msg);
983                 PatternKind::Wild
984             },
985             ty::Adt(adt_def, substs) if adt_def.is_enum() => {
986                 let variant_index = const_variant_index(
987                     self.tcx, self.param_env, instance, cv
988                 ).expect("const_variant_index failed");
989                 let subpatterns = adt_subpatterns(
990                     adt_def.variants[variant_index].fields.len(),
991                     Some(variant_index),
992                 );
993                 PatternKind::Variant {
994                     adt_def,
995                     substs,
996                     variant_index,
997                     subpatterns,
998                 }
999             },
1000             ty::Adt(adt_def, _) => {
1001                 let struct_var = adt_def.non_enum_variant();
1002                 PatternKind::Leaf {
1003                     subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1004                 }
1005             }
1006             ty::Tuple(fields) => {
1007                 PatternKind::Leaf {
1008                     subpatterns: adt_subpatterns(fields.len(), None),
1009                 }
1010             }
1011             ty::Array(_, n) => {
1012                 PatternKind::Array {
1013                     prefix: (0..n.unwrap_usize(self.tcx))
1014                         .map(|i| adt_subpattern(i as usize, None))
1015                         .collect(),
1016                     slice: None,
1017                     suffix: Vec::new(),
1018                 }
1019             }
1020             _ => {
1021                 PatternKind::Constant {
1022                     value: cv,
1023                 }
1024             },
1025         };
1026
1027         Pattern {
1028             span,
1029             ty: cv.ty,
1030             kind: Box::new(kind),
1031         }
1032     }
1033 }
1034
1035 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1036     fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1037         self.tcx
1038     }
1039
1040     fn tables(&self) -> &ty::TypeckTables<'tcx> {
1041         self.tables
1042     }
1043 }
1044
1045
1046 pub trait PatternFoldable<'tcx> : Sized {
1047     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1048         self.super_fold_with(folder)
1049     }
1050
1051     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1052 }
1053
1054 pub trait PatternFolder<'tcx> : Sized {
1055     fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1056         pattern.super_fold_with(self)
1057     }
1058
1059     fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1060         kind.super_fold_with(self)
1061     }
1062 }
1063
1064
1065 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1066     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1067         let content: T = (**self).fold_with(folder);
1068         box content
1069     }
1070 }
1071
1072 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1073     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1074         self.iter().map(|t| t.fold_with(folder)).collect()
1075     }
1076 }
1077
1078 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1079     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1080         self.as_ref().map(|t| t.fold_with(folder))
1081     }
1082 }
1083
1084 macro_rules! CloneImpls {
1085     (<$lt_tcx:tt> $($ty:ty),+) => {
1086         $(
1087             impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1088                 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1089                     Clone::clone(self)
1090                 }
1091             }
1092         )+
1093     }
1094 }
1095
1096 CloneImpls!{ <'tcx>
1097     Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
1098     Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
1099     &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>,
1100     UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1101 }
1102
1103 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1104     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1105         FieldPattern {
1106             field: self.field.fold_with(folder),
1107             pattern: self.pattern.fold_with(folder)
1108         }
1109     }
1110 }
1111
1112 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1113     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1114         folder.fold_pattern(self)
1115     }
1116
1117     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1118         Pattern {
1119             ty: self.ty.fold_with(folder),
1120             span: self.span.fold_with(folder),
1121             kind: self.kind.fold_with(folder)
1122         }
1123     }
1124 }
1125
1126 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1127     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1128         folder.fold_pattern_kind(self)
1129     }
1130
1131     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1132         match *self {
1133             PatternKind::Wild => PatternKind::Wild,
1134             PatternKind::AscribeUserType {
1135                 ref subpattern,
1136                 ref user_ty,
1137                 user_ty_span,
1138             } => PatternKind::AscribeUserType {
1139                 subpattern: subpattern.fold_with(folder),
1140                 user_ty: user_ty.fold_with(folder),
1141                 user_ty_span,
1142             },
1143             PatternKind::Binding {
1144                 mutability,
1145                 name,
1146                 mode,
1147                 var,
1148                 ty,
1149                 ref subpattern,
1150             } => PatternKind::Binding {
1151                 mutability: mutability.fold_with(folder),
1152                 name: name.fold_with(folder),
1153                 mode: mode.fold_with(folder),
1154                 var: var.fold_with(folder),
1155                 ty: ty.fold_with(folder),
1156                 subpattern: subpattern.fold_with(folder),
1157             },
1158             PatternKind::Variant {
1159                 adt_def,
1160                 substs,
1161                 variant_index,
1162                 ref subpatterns,
1163             } => PatternKind::Variant {
1164                 adt_def: adt_def.fold_with(folder),
1165                 substs: substs.fold_with(folder),
1166                 variant_index,
1167                 subpatterns: subpatterns.fold_with(folder)
1168             },
1169             PatternKind::Leaf {
1170                 ref subpatterns,
1171             } => PatternKind::Leaf {
1172                 subpatterns: subpatterns.fold_with(folder),
1173             },
1174             PatternKind::Deref {
1175                 ref subpattern,
1176             } => PatternKind::Deref {
1177                 subpattern: subpattern.fold_with(folder),
1178             },
1179             PatternKind::Constant {
1180                 value
1181             } => PatternKind::Constant {
1182                 value: value.fold_with(folder)
1183             },
1184             PatternKind::Range(PatternRange {
1185                 lo,
1186                 hi,
1187                 ty,
1188                 end,
1189             }) => PatternKind::Range(PatternRange {
1190                 lo: lo.fold_with(folder),
1191                 hi: hi.fold_with(folder),
1192                 ty: ty.fold_with(folder),
1193                 end,
1194             }),
1195             PatternKind::Slice {
1196                 ref prefix,
1197                 ref slice,
1198                 ref suffix,
1199             } => PatternKind::Slice {
1200                 prefix: prefix.fold_with(folder),
1201                 slice: slice.fold_with(folder),
1202                 suffix: suffix.fold_with(folder)
1203             },
1204             PatternKind::Array {
1205                 ref prefix,
1206                 ref slice,
1207                 ref suffix
1208             } => PatternKind::Array {
1209                 prefix: prefix.fold_with(folder),
1210                 slice: slice.fold_with(folder),
1211                 suffix: suffix.fold_with(folder)
1212             },
1213         }
1214     }
1215 }
1216
1217 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1218     tcx: TyCtxt<'a, 'gcx, 'tcx>,
1219     a: &'tcx ty::Const<'tcx>,
1220     b: &'tcx ty::Const<'tcx>,
1221     ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1222 ) -> Option<Ordering> {
1223     trace!("compare_const_vals: {:?}, {:?}", a, b);
1224
1225     let from_bool = |v: bool| {
1226         if v {
1227             Some(Ordering::Equal)
1228         } else {
1229             None
1230         }
1231     };
1232
1233     let fallback = || from_bool(a == b);
1234
1235     // Use the fallback if any type differs
1236     if a.ty != b.ty || a.ty != ty.value {
1237         return fallback();
1238     }
1239
1240     let tcx = tcx.global_tcx();
1241     let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1242
1243     // FIXME: This should use assert_bits(ty) instead of use_bits
1244     // but triggers possibly bugs due to mismatching of arrays and slices
1245     if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1246         use ::rustc_apfloat::Float;
1247         return match ty.value.sty {
1248             ty::Float(ast::FloatTy::F32) => {
1249                 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1250                 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1251                 l.partial_cmp(&r)
1252             },
1253             ty::Float(ast::FloatTy::F64) => {
1254                 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1255                 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1256                 l.partial_cmp(&r)
1257             },
1258             ty::Int(_) => {
1259                 let layout = tcx.layout_of(ty).ok()?;
1260                 assert!(layout.abi.is_signed());
1261                 let a = sign_extend(a, layout.size);
1262                 let b = sign_extend(b, layout.size);
1263                 Some((a as i128).cmp(&(b as i128)))
1264             },
1265             _ => Some(a.cmp(&b)),
1266         }
1267     }
1268
1269     if let ty::Str = ty.value.sty {
1270         match (a.val, b.val) {
1271             (
1272                 ConstValue::ScalarPair(
1273                     Scalar::Ptr(ptr_a),
1274                     len_a,
1275                 ),
1276                 ConstValue::ScalarPair(
1277                     Scalar::Ptr(ptr_b),
1278                     len_b,
1279                 ),
1280             ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1281                 if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1282                     if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1283                         if len_a == len_b {
1284                             let map = tcx.alloc_map.lock();
1285                             let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1286                             let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1287                             if alloc_a.bytes.len() as u128 == len_a {
1288                                 return from_bool(alloc_a == alloc_b);
1289                             }
1290                         }
1291                     }
1292                 }
1293             }
1294             _ => (),
1295         }
1296     }
1297
1298     fallback()
1299 }