]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/constant.rs
Rollup merge of #86424 - calebcartwright:rustfmt-mod-resolution, r=Mark-Simulacrum
[rust.git] / compiler / rustc_mir_build / src / thir / constant.rs
1 use rustc_apfloat::Float;
2 use rustc_ast as ast;
3 use rustc_middle::mir::interpret::{
4     Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
5 };
6 use rustc_middle::ty::{self, ParamEnv, TyCtxt};
7 use rustc_span::symbol::Symbol;
8 use rustc_target::abi::Size;
9
10 crate fn lit_to_const<'tcx>(
11     tcx: TyCtxt<'tcx>,
12     lit_input: LitToConstInput<'tcx>,
13 ) -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
14     let LitToConstInput { lit, ty, neg } = lit_input;
15
16     let trunc = |n| {
17         let param_ty = ParamEnv::reveal_all().and(ty);
18         let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
19         trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
20         let result = width.truncate(n);
21         trace!("trunc result: {}", result);
22         Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
23     };
24
25     let lit = match (lit, &ty.kind()) {
26         (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
27             let s = s.as_str();
28             let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
29             let allocation = tcx.intern_const_alloc(allocation);
30             ConstValue::Slice { data: allocation, start: 0, end: s.len() }
31         }
32         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
33             if matches!(inner_ty.kind(), ty::Slice(_)) =>
34         {
35             let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
36             let allocation = tcx.intern_const_alloc(allocation);
37             ConstValue::Slice { data: allocation, start: 0, end: data.len() }
38         }
39         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
40             let id = tcx.allocate_bytes(data);
41             ConstValue::Scalar(Scalar::Ptr(id.into()))
42         }
43         (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
44             ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
45         }
46         (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
47             trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
48         }
49         (ast::LitKind::Float(n, _), ty::Float(fty)) => {
50             parse_float(*n, *fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
51         }
52         (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
53         (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
54         (ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
55         _ => return Err(LitToConstError::TypeError),
56     };
57     Ok(ty::Const::from_value(tcx, lit, ty))
58 }
59
60 fn parse_float<'tcx>(num: Symbol, fty: ty::FloatTy, neg: bool) -> Result<ConstValue<'tcx>, ()> {
61     let num = num.as_str();
62     use rustc_apfloat::ieee::{Double, Single};
63     let scalar = match fty {
64         ty::FloatTy::F32 => {
65             let rust_f = num.parse::<f32>().map_err(|_| ())?;
66             let mut f = num.parse::<Single>().unwrap_or_else(|e| {
67                 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
68             });
69             assert!(
70                 u128::from(rust_f.to_bits()) == f.to_bits(),
71                 "apfloat::ieee::Single gave different result for `{}`: \
72                  {}({:#x}) vs Rust's {}({:#x})",
73                 rust_f,
74                 f,
75                 f.to_bits(),
76                 Single::from_bits(rust_f.to_bits().into()),
77                 rust_f.to_bits()
78             );
79             if neg {
80                 f = -f;
81             }
82             Scalar::from_f32(f)
83         }
84         ty::FloatTy::F64 => {
85             let rust_f = num.parse::<f64>().map_err(|_| ())?;
86             let mut f = num.parse::<Double>().unwrap_or_else(|e| {
87                 panic!("apfloat::ieee::Double failed to parse `{}`: {:?}", num, e)
88             });
89             assert!(
90                 u128::from(rust_f.to_bits()) == f.to_bits(),
91                 "apfloat::ieee::Double gave different result for `{}`: \
92                  {}({:#x}) vs Rust's {}({:#x})",
93                 rust_f,
94                 f,
95                 f.to_bits(),
96                 Double::from_bits(rust_f.to_bits().into()),
97                 rust_f.to_bits()
98             );
99             if neg {
100                 f = -f;
101             }
102             Scalar::from_f64(f)
103         }
104     };
105
106     Ok(ConstValue::Scalar(scalar))
107 }