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