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