]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/mod.rs
Auto merge of #52712 - oli-obk:const_eval_cleanups, r=RalfJung
[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};
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::ExprKind::Lit(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(e) => {
747                         if e == LitToConstError::UnparseableFloat {
748                             self.errors.push(PatternError::FloatBug);
749                         }
750                         PatternKind::Wild
751                     },
752                 }
753             },
754             hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
755             hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
756                 let ty = self.tables.expr_ty(expr);
757                 let lit = match expr.node {
758                     hir::ExprKind::Lit(ref lit) => lit,
759                     _ => span_bug!(expr.span, "not a literal: {:?}", expr),
760                 };
761                 match lit_to_const(&lit.node, self.tcx, ty, true) {
762                     Ok(val) => {
763                         let instance = ty::Instance::new(
764                             self.tables.local_id_root.expect("literal outside any scope"),
765                             self.substs,
766                         );
767                         *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
768                     },
769                     Err(e) => {
770                         if e == LitToConstError::UnparseableFloat {
771                             self.errors.push(PatternError::FloatBug);
772                         }
773                         PatternKind::Wild
774                     },
775                 }
776             }
777             _ => span_bug!(expr.span, "not a literal: {:?}", expr),
778         }
779     }
780
781     /// Converts an evaluated constant to a pattern (if possible).
782     /// This means aggregate values (like structs and enums) are converted
783     /// to a pattern that matches the value (as if you'd compare via eq).
784     fn const_to_pat(
785         &self,
786         instance: ty::Instance<'tcx>,
787         cv: &'tcx ty::Const<'tcx>,
788         id: hir::HirId,
789         span: Span,
790     ) -> Pattern<'tcx> {
791         debug!("const_to_pat: cv={:#?}", cv);
792         let adt_subpattern = |i, variant_opt| {
793             let field = Field::new(i);
794             let val = const_val_field(
795                 self.tcx, self.param_env, instance,
796                 variant_opt, field, cv,
797             ).expect("field access failed");
798             self.const_to_pat(instance, val, id, span)
799         };
800         let adt_subpatterns = |n, variant_opt| {
801             (0..n).map(|i| {
802                 let field = Field::new(i);
803                 FieldPattern {
804                     field,
805                     pattern: adt_subpattern(i, variant_opt),
806                 }
807             }).collect::<Vec<_>>()
808         };
809         let kind = match cv.ty.sty {
810             ty::TyFloat(_) => {
811                 let id = self.tcx.hir.hir_to_node_id(id);
812                 self.tcx.lint_node(
813                     ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
814                     id,
815                     span,
816                     "floating-point types cannot be used in patterns",
817                 );
818                 PatternKind::Constant {
819                     value: cv,
820                 }
821             },
822             ty::TyAdt(adt_def, _) if adt_def.is_union() => {
823                 // Matching on union fields is unsafe, we can't hide it in constants
824                 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
825                 PatternKind::Wild
826             }
827             ty::TyAdt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
828                 let msg = format!("to use a constant of type `{}` in a pattern, \
829                                     `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
830                                     self.tcx.item_path_str(adt_def.did),
831                                     self.tcx.item_path_str(adt_def.did));
832                 self.tcx.sess.span_err(span, &msg);
833                 PatternKind::Wild
834             },
835             ty::TyAdt(adt_def, substs) if adt_def.is_enum() => {
836                 let variant_index = const_variant_index(
837                     self.tcx, self.param_env, instance, cv
838                 ).expect("const_variant_index failed");
839                 let subpatterns = adt_subpatterns(
840                     adt_def.variants[variant_index].fields.len(),
841                     Some(variant_index),
842                 );
843                 PatternKind::Variant {
844                     adt_def,
845                     substs,
846                     variant_index,
847                     subpatterns,
848                 }
849             },
850             ty::TyAdt(adt_def, _) => {
851                 let struct_var = adt_def.non_enum_variant();
852                 PatternKind::Leaf {
853                     subpatterns: adt_subpatterns(struct_var.fields.len(), None),
854                 }
855             }
856             ty::TyTuple(fields) => {
857                 PatternKind::Leaf {
858                     subpatterns: adt_subpatterns(fields.len(), None),
859                 }
860             }
861             ty::TyArray(_, n) => {
862                 PatternKind::Array {
863                     prefix: (0..n.unwrap_usize(self.tcx))
864                         .map(|i| adt_subpattern(i as usize, None))
865                         .collect(),
866                     slice: None,
867                     suffix: Vec::new(),
868                 }
869             }
870             _ => {
871                 PatternKind::Constant {
872                     value: cv,
873                 }
874             },
875         };
876
877         Pattern {
878             span,
879             ty: cv.ty,
880             kind: Box::new(kind),
881         }
882     }
883 }
884
885 pub trait PatternFoldable<'tcx> : Sized {
886     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
887         self.super_fold_with(folder)
888     }
889
890     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
891 }
892
893 pub trait PatternFolder<'tcx> : Sized {
894     fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
895         pattern.super_fold_with(self)
896     }
897
898     fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
899         kind.super_fold_with(self)
900     }
901 }
902
903
904 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
905     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
906         let content: T = (**self).fold_with(folder);
907         box content
908     }
909 }
910
911 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
912     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
913         self.iter().map(|t| t.fold_with(folder)).collect()
914     }
915 }
916
917 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
918     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
919         self.as_ref().map(|t| t.fold_with(folder))
920     }
921 }
922
923 macro_rules! CloneImpls {
924     (<$lt_tcx:tt> $($ty:ty),+) => {
925         $(
926             impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
927                 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
928                     Clone::clone(self)
929                 }
930             }
931         )+
932     }
933 }
934
935 CloneImpls!{ <'tcx>
936     Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
937     Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
938     &'tcx Substs<'tcx>, &'tcx Kind<'tcx>
939 }
940
941 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
942     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
943         FieldPattern {
944             field: self.field.fold_with(folder),
945             pattern: self.pattern.fold_with(folder)
946         }
947     }
948 }
949
950 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
951     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
952         folder.fold_pattern(self)
953     }
954
955     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
956         Pattern {
957             ty: self.ty.fold_with(folder),
958             span: self.span.fold_with(folder),
959             kind: self.kind.fold_with(folder)
960         }
961     }
962 }
963
964 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
965     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
966         folder.fold_pattern_kind(self)
967     }
968
969     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
970         match *self {
971             PatternKind::Wild => PatternKind::Wild,
972             PatternKind::Binding {
973                 mutability,
974                 name,
975                 mode,
976                 var,
977                 ty,
978                 ref subpattern,
979             } => PatternKind::Binding {
980                 mutability: mutability.fold_with(folder),
981                 name: name.fold_with(folder),
982                 mode: mode.fold_with(folder),
983                 var: var.fold_with(folder),
984                 ty: ty.fold_with(folder),
985                 subpattern: subpattern.fold_with(folder),
986             },
987             PatternKind::Variant {
988                 adt_def,
989                 substs,
990                 variant_index,
991                 ref subpatterns,
992             } => PatternKind::Variant {
993                 adt_def: adt_def.fold_with(folder),
994                 substs: substs.fold_with(folder),
995                 variant_index: variant_index.fold_with(folder),
996                 subpatterns: subpatterns.fold_with(folder)
997             },
998             PatternKind::Leaf {
999                 ref subpatterns,
1000             } => PatternKind::Leaf {
1001                 subpatterns: subpatterns.fold_with(folder),
1002             },
1003             PatternKind::Deref {
1004                 ref subpattern,
1005             } => PatternKind::Deref {
1006                 subpattern: subpattern.fold_with(folder),
1007             },
1008             PatternKind::Constant {
1009                 value
1010             } => PatternKind::Constant {
1011                 value: value.fold_with(folder)
1012             },
1013             PatternKind::Range {
1014                 lo,
1015                 hi,
1016                 end,
1017             } => PatternKind::Range {
1018                 lo: lo.fold_with(folder),
1019                 hi: hi.fold_with(folder),
1020                 end,
1021             },
1022             PatternKind::Slice {
1023                 ref prefix,
1024                 ref slice,
1025                 ref suffix,
1026             } => PatternKind::Slice {
1027                 prefix: prefix.fold_with(folder),
1028                 slice: slice.fold_with(folder),
1029                 suffix: suffix.fold_with(folder)
1030             },
1031             PatternKind::Array {
1032                 ref prefix,
1033                 ref slice,
1034                 ref suffix
1035             } => PatternKind::Array {
1036                 prefix: prefix.fold_with(folder),
1037                 slice: slice.fold_with(folder),
1038                 suffix: suffix.fold_with(folder)
1039             },
1040         }
1041     }
1042 }
1043
1044 pub fn compare_const_vals<'a, 'tcx>(
1045     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1046     a: &'tcx ty::Const<'tcx>,
1047     b: &'tcx ty::Const<'tcx>,
1048     ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1049 ) -> Option<Ordering> {
1050     trace!("compare_const_vals: {:?}, {:?}", a, b);
1051
1052     let from_bool = |v: bool| {
1053         if v {
1054             Some(Ordering::Equal)
1055         } else {
1056             None
1057         }
1058     };
1059
1060     let fallback = || from_bool(a == b);
1061
1062     // Use the fallback if any type differs
1063     if a.ty != b.ty || a.ty != ty.value {
1064         return fallback();
1065     }
1066
1067     // FIXME: This should use assert_bits(ty) instead of use_bits
1068     // but triggers possibly bugs due to mismatching of arrays and slices
1069     if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1070         use ::rustc_apfloat::Float;
1071         return match ty.value.sty {
1072             ty::TyFloat(ast::FloatTy::F32) => {
1073                 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1074                 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1075                 l.partial_cmp(&r)
1076             },
1077             ty::TyFloat(ast::FloatTy::F64) => {
1078                 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1079                 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1080                 l.partial_cmp(&r)
1081             },
1082             ty::TyInt(_) => {
1083                 let layout = tcx.layout_of(ty).ok()?;
1084                 let a = interpret::sign_extend(a, layout);
1085                 let b = interpret::sign_extend(b, layout);
1086                 Some((a as i128).cmp(&(b as i128)))
1087             },
1088             _ => Some(a.cmp(&b)),
1089         }
1090     }
1091
1092     if let ty::TyRef(_, rty, _) = ty.value.sty {
1093         if let ty::TyStr = rty.sty {
1094             match (a.val, b.val) {
1095                 (
1096                     ConstValue::ScalarPair(
1097                         Scalar::Ptr(ptr_a),
1098                         len_a,
1099                     ),
1100                     ConstValue::ScalarPair(
1101                         Scalar::Ptr(ptr_b),
1102                         len_b,
1103                     ),
1104                 ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1105                     let len_a = len_a.unwrap_or_err().ok();
1106                     let len_b = len_b.unwrap_or_err().ok();
1107                     if len_a.is_none() || len_b.is_none() {
1108                         tcx.sess.struct_err("str slice len is undef").delay_as_bug();
1109                     }
1110                     let len_a = len_a?;
1111                     let len_b = len_b?;
1112                     if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
1113                         if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
1114                             if len_a == len_b {
1115                                 let map = tcx.alloc_map.lock();
1116                                 let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1117                                 let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1118                                 if alloc_a.bytes.len() as u128 == len_a {
1119                                     return from_bool(alloc_a == alloc_b);
1120                                 }
1121                             }
1122                         }
1123                     }
1124                 }
1125                 _ => (),
1126             }
1127         }
1128     }
1129
1130     fallback()
1131 }
1132
1133 #[derive(PartialEq)]
1134 enum LitToConstError {
1135     UnparseableFloat,
1136     Propagated,
1137 }
1138
1139 // FIXME: Combine with rustc_mir::hair::cx::const_eval_literal
1140 fn lit_to_const<'a, 'tcx>(lit: &'tcx ast::LitKind,
1141                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
1142                           ty: Ty<'tcx>,
1143                           neg: bool)
1144                           -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
1145     use syntax::ast::*;
1146
1147     use rustc::mir::interpret::*;
1148     let lit = match *lit {
1149         LitKind::Str(ref s, _) => {
1150             let s = s.as_str();
1151             let id = tcx.allocate_bytes(s.as_bytes());
1152             let value = Scalar::Ptr(id.into()).to_value_with_len(s.len() as u64, tcx);
1153             ConstValue::from_byval_value(value).unwrap()
1154         },
1155         LitKind::ByteStr(ref data) => {
1156             let id = tcx.allocate_bytes(data);
1157             ConstValue::Scalar(Scalar::Ptr(id.into()))
1158         },
1159         LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
1160             bits: n as u128,
1161             size: 1,
1162         }),
1163         LitKind::Int(n, _) => {
1164             enum Int {
1165                 Signed(IntTy),
1166                 Unsigned(UintTy),
1167             }
1168             let ity = match ty.sty {
1169                 ty::TyInt(IntTy::Isize) => Int::Signed(tcx.sess.target.isize_ty),
1170                 ty::TyInt(other) => Int::Signed(other),
1171                 ty::TyUint(UintTy::Usize) => Int::Unsigned(tcx.sess.target.usize_ty),
1172                 ty::TyUint(other) => Int::Unsigned(other),
1173                 ty::TyError => { // Avoid ICE (#51963)
1174                     return Err(LitToConstError::Propagated);
1175                 }
1176                 _ => bug!("literal integer type with bad type ({:?})", ty.sty),
1177             };
1178             // This converts from LitKind::Int (which is sign extended) to
1179             // Scalar::Bytes (which is zero extended)
1180             let n = match ity {
1181                 // FIXME(oli-obk): are these casts correct?
1182                 Int::Signed(IntTy::I8) if neg =>
1183                     (n as i8).overflowing_neg().0 as u8 as u128,
1184                 Int::Signed(IntTy::I16) if neg =>
1185                     (n as i16).overflowing_neg().0 as u16 as u128,
1186                 Int::Signed(IntTy::I32) if neg =>
1187                     (n as i32).overflowing_neg().0 as u32 as u128,
1188                 Int::Signed(IntTy::I64) if neg =>
1189                     (n as i64).overflowing_neg().0 as u64 as u128,
1190                 Int::Signed(IntTy::I128) if neg =>
1191                     (n as i128).overflowing_neg().0 as u128,
1192                 Int::Signed(IntTy::I8) | Int::Unsigned(UintTy::U8) => n as u8 as u128,
1193                 Int::Signed(IntTy::I16) | Int::Unsigned(UintTy::U16) => n as u16 as u128,
1194                 Int::Signed(IntTy::I32) | Int::Unsigned(UintTy::U32) => n as u32 as u128,
1195                 Int::Signed(IntTy::I64) | Int::Unsigned(UintTy::U64) => n as u64 as u128,
1196                 Int::Signed(IntTy::I128)| Int::Unsigned(UintTy::U128) => n,
1197                 _ => bug!(),
1198             };
1199             let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size.bytes() as u8;
1200             ConstValue::Scalar(Scalar::Bits {
1201                 bits: n,
1202                 size,
1203             })
1204         },
1205         LitKind::Float(n, fty) => {
1206             parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1207         }
1208         LitKind::FloatUnsuffixed(n) => {
1209             let fty = match ty.sty {
1210                 ty::TyFloat(fty) => fty,
1211                 _ => bug!()
1212             };
1213             parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1214         }
1215         LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
1216         LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
1217     };
1218     Ok(ty::Const::from_const_value(tcx, lit, ty))
1219 }
1220
1221 pub fn parse_float<'tcx>(
1222     num: Symbol,
1223     fty: ast::FloatTy,
1224     neg: bool,
1225 ) -> Result<ConstValue<'tcx>, ()> {
1226     let num = num.as_str();
1227     use rustc_apfloat::ieee::{Single, Double};
1228     use rustc_apfloat::Float;
1229     let (bits, size) = match fty {
1230         ast::FloatTy::F32 => {
1231             num.parse::<f32>().map_err(|_| ())?;
1232             let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1233                 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1234             });
1235             if neg {
1236                 f = -f;
1237             }
1238             (f.to_bits(), 4)
1239         }
1240         ast::FloatTy::F64 => {
1241             num.parse::<f64>().map_err(|_| ())?;
1242             let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1243                 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1244             });
1245             if neg {
1246                 f = -f;
1247             }
1248             (f.to_bits(), 8)
1249         }
1250     };
1251
1252     Ok(ConstValue::Scalar(Scalar::Bits { bits, size }))
1253 }