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