2 use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
3 use rustc_middle::ty::{self, ParamEnv, ScalarInt, TyCtxt};
5 pub(crate) fn lit_to_const<'tcx>(
7 lit_input: LitToConstInput<'tcx>,
8 ) -> Result<ty::Const<'tcx>, LitToConstError> {
9 let LitToConstInput { lit, ty, neg } = lit_input;
12 let param_ty = ParamEnv::reveal_all().and(ty);
13 let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
14 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
15 let result = width.truncate(n);
16 trace!("trunc result: {}", result);
18 Ok(ScalarInt::try_from_uint(result, width)
19 .unwrap_or_else(|| bug!("expected to create ScalarInt from uint {:?}", result)))
22 let valtree = match (lit, &ty.kind()) {
23 (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
24 let str_bytes = s.as_str().as_bytes();
25 ty::ValTree::from_raw_bytes(tcx, str_bytes)
27 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
28 if matches!(inner_ty.kind(), ty::Slice(_)) =>
30 let bytes = data as &[u8];
31 ty::ValTree::from_raw_bytes(tcx, bytes)
33 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
34 let bytes = data as &[u8];
35 ty::ValTree::from_raw_bytes(tcx, bytes)
37 (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
38 ty::ValTree::from_scalar_int((*n).into())
40 (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
42 trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?;
43 ty::ValTree::from_scalar_int(scalar_int)
45 (ast::LitKind::Bool(b), ty::Bool) => ty::ValTree::from_scalar_int((*b).into()),
46 (ast::LitKind::Char(c), ty::Char) => ty::ValTree::from_scalar_int((*c).into()),
47 (ast::LitKind::Err, _) => return Err(LitToConstError::Reported),
48 _ => return Err(LitToConstError::TypeError),
51 Ok(ty::Const::from_value(tcx, valtree, ty))