2 use rustc::ty::{self, Ty, TyCtxt, ParamEnv, layout::Size};
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::from_uint(result, width)))
29 use rustc::mir::interpret::*;
30 let lit = match *lit {
31 LitKind::Str(ref s, _) => {
33 let allocation = Allocation::from_byte_aligned_bytes(s.as_bytes(), ());
34 let allocation = tcx.intern_const_alloc(allocation);
35 ConstValue::Slice { data: allocation, start: 0, end: s.len() }
37 LitKind::Err(ref s) => {
39 let allocation = Allocation::from_byte_aligned_bytes(s.as_bytes(), ());
40 let allocation = tcx.intern_const_alloc(allocation);
41 return Ok(tcx.mk_const(ty::Const {
42 val: ConstValue::Slice{ data: allocation, start: 0, end: s.len() },
46 LitKind::ByteStr(ref data) => {
47 let id = tcx.allocate_bytes(data);
48 ConstValue::Scalar(Scalar::Ptr(id.into()))
50 LitKind::Byte(n) => ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))),
51 LitKind::Int(n, _) if neg => {
53 let n = n.overflowing_neg().0;
56 LitKind::Int(n, _) => trunc(n)?,
57 LitKind::Float(n, fty) => {
58 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
60 LitKind::FloatUnsuffixed(n) => {
61 let fty = match ty.sty {
62 ty::Float(fty) => fty,
65 parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
67 LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
68 LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
70 Ok(tcx.mk_const(ty::Const { val: lit, ty }))
77 ) -> Result<ConstValue<'tcx>, ()> {
78 let num = num.as_str();
79 use rustc_apfloat::ieee::{Single, Double};
80 use rustc_apfloat::Float;
81 let (data, size) = match fty {
82 ast::FloatTy::F32 => {
83 num.parse::<f32>().map_err(|_| ())?;
84 let mut f = num.parse::<Single>().unwrap_or_else(|e| {
85 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
92 ast::FloatTy::F64 => {
93 num.parse::<f64>().map_err(|_| ())?;
94 let mut f = num.parse::<Double>().unwrap_or_else(|e| {
95 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
104 Ok(ConstValue::Scalar(Scalar::from_uint(data, Size::from_bytes(size))))