]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/constant.rs
Rollup merge of #101424 - compiler-errors:operator-err-sugg, r=TaKO8Ki
[rust.git] / compiler / rustc_mir_build / src / thir / constant.rs
1 use rustc_ast as ast;
2 use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
3 use rustc_middle::ty::{self, ParamEnv, ScalarInt, TyCtxt};
4
5 pub(crate) fn lit_to_const<'tcx>(
6     tcx: TyCtxt<'tcx>,
7     lit_input: LitToConstInput<'tcx>,
8 ) -> Result<ty::Const<'tcx>, LitToConstError> {
9     let LitToConstInput { lit, ty, neg } = lit_input;
10
11     let trunc = |n| {
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);
17
18         Ok(ScalarInt::try_from_uint(result, width)
19             .unwrap_or_else(|| bug!("expected to create ScalarInt from uint {:?}", result)))
20     };
21
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)
26         }
27         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
28             if matches!(inner_ty.kind(), ty::Slice(_)) =>
29         {
30             let bytes = data as &[u8];
31             ty::ValTree::from_raw_bytes(tcx, bytes)
32         }
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)
36         }
37         (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
38             ty::ValTree::from_scalar_int((*n).into())
39         }
40         (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
41             let scalar_int =
42                 trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?;
43             ty::ValTree::from_scalar_int(scalar_int)
44         }
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),
49     };
50
51     Ok(ty::Const::from_value(tcx, valtree, ty))
52 }