2 use rustc::ty::{self, Ty, TyCtxt, ParamEnv};
3 use syntax_pos::symbol::Symbol;
4 use rustc::mir::interpret::{ConstValue, Scalar};
7 crate enum LitToConstError {
12 crate fn lit_to_const<'a, 'gcx, 'tcx>(
13 lit: &'tcx ast::LitKind,
14 tcx: TyCtxt<'a, 'gcx, 'tcx>,
17 ) -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
21 let param_ty = ParamEnv::reveal_all().and(tcx.lift_to_global(&ty).unwrap());
22 let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
23 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
24 let result = truncate(n, width);
25 trace!("trunc result: {}", result);
26 Ok(ConstValue::Scalar(Scalar::Bits {
28 size: width.bytes() as u8,
32 use rustc::mir::interpret::*;
33 let lit = match *lit {
34 LitKind::Str(ref s, _) => {
36 let allocation = Allocation::from_byte_aligned_bytes(s.as_bytes(), ());
37 let allocation = tcx.intern_const_alloc(allocation);
38 ConstValue::Slice { data: allocation, start: 0, end: s.len() }
40 LitKind::Err(ref s) => {
42 let allocation = Allocation::from_byte_aligned_bytes(s.as_bytes(), ());
43 let allocation = tcx.intern_const_alloc(allocation);
44 return Ok(tcx.mk_const(ty::Const {
45 val: ConstValue::Slice{ data: allocation, start: 0, end: s.len() },
49 LitKind::ByteStr(ref data) => {
50 let id = tcx.allocate_bytes(data);
51 ConstValue::Scalar(Scalar::Ptr(id.into()))
53 LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
57 LitKind::Int(n, _) if neg => {
59 let n = n.overflowing_neg().0;
62 LitKind::Int(n, _) => trunc(n)?,
63 LitKind::Float(n, fty) => {
64 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
66 LitKind::FloatUnsuffixed(n) => {
67 let fty = match ty.sty {
68 ty::Float(fty) => fty,
71 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
73 LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
74 LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
76 Ok(tcx.mk_const(ty::Const { val: lit, ty }))
83 ) -> Result<ConstValue<'tcx>, ()> {
84 let num = num.as_str();
85 use rustc_apfloat::ieee::{Single, Double};
86 use rustc_apfloat::Float;
87 let (bits, size) = match fty {
88 ast::FloatTy::F32 => {
89 num.parse::<f32>().map_err(|_| ())?;
90 let mut f = num.parse::<Single>().unwrap_or_else(|e| {
91 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
98 ast::FloatTy::F64 => {
99 num.parse::<f64>().map_err(|_| ())?;
100 let mut f = num.parse::<Double>().unwrap_or_else(|e| {
101 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
110 Ok(ConstValue::Scalar(Scalar::Bits { bits, size }))