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