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