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