1use core::hash::Hash;
3use derive_generic_visitor::{Drive, DriveMut, DriveTwo};
4use enum_as_inner::EnumAsInner;
5use serde::{Deserialize, Serialize};
6use serde_state::{DeserializeState, SerializeState};
7use std::vec::Vec;
8
9use crate::ast::*;
10
11#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
13#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
14#[serde_state(state_implements = DedupSerializerState)] pub struct ConstantExpr(pub HashConsed<WithCachedTypeInfo<(ConstantExprKind, Ty)>>);
16
17#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
18#[derive(EnumAsInner)]
19#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
20#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("C"))]
21pub enum ConstantExprKind {
22 Bool(bool),
24 #[serde_state(stateless)]
26 Integer(IntegerValue),
27 Char(char),
29 #[serde_state(stateless)]
31 Float(FloatValue),
32 Adt(Option<VariantId>, IndexVec<FieldId, ConstantExpr>),
36 Array(Vec<ConstantExpr>),
40 Ref(GlobalPlace, Option<UnsizingMetadata>),
44 Ptr(RefKind, GlobalPlace, Option<UnsizingMetadata>),
48 Str(String),
50 ByteStr(Vec<u8>),
52 FnDef(FnPtr),
54 FnPtr(FnPtr),
58 Cast(ConstantExpr, CastKind),
60 PtrNoProvenance(#[serde(with = "scalar_value_ser_de")] u128),
64 ExternSymbol(String),
67 TypeId(Ty),
69 RawMemory(Vec<Byte>),
72
73 Var(ConstGenericDbVar),
75 Global(GlobalDeclRef),
79 Call(FnPtr, Vec<ConstantExpr>),
81 TraitConst(TraitRef, AssocConstId),
90 VTableRef(PolyTraitRef),
95 Discriminant(TypeDeclRef, VariantId),
97 Repeat {
99 value: ConstantExpr,
100 count: ConstantExpr,
101 value_is_sized: Option<TraitRef>,
103 },
104 SizeOf(Ty),
106 AlignOf(Ty),
108 OffsetOf(TypeDeclRef, Option<VariantId>, FieldId),
110
111 Opaque(String),
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
118#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
119#[serde_state(state_implements = DedupSerializerState)] pub struct GlobalPlace {
121 #[cfg_attr(feature = "charon_on_charon", charon::rename("global_place_kind"))]
122 pub kind: GlobalPlaceKind,
123 #[cfg_attr(feature = "charon_on_charon", charon::rename("global_place_ty"))]
125 pub ty: Ty,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
129#[derive(EnumAsInner)]
130#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
131#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("GlobalPlace"))]
132pub enum GlobalPlaceKind {
133 Global(GlobalProvenance),
135 Value(ConstantExpr),
139 Projection(Box<GlobalPlace>, ConstProjectionElem),
141}
142
143impl GlobalPlace {
144 pub fn new_global(global: GlobalDeclRef, ty: Ty) -> Self {
145 GlobalPlace {
146 kind: GlobalPlaceKind::Global(GlobalProvenance::Global(global)),
147 ty,
148 }
149 }
150
151 pub fn new_value(value: ConstantExpr) -> Self {
152 GlobalPlace {
153 ty: value.ty().clone(),
154 kind: GlobalPlaceKind::Value(value),
155 }
156 }
157
158 pub fn project(self, elem: ConstProjectionElem, ty: Ty) -> Self {
159 GlobalPlace {
160 kind: GlobalPlaceKind::Projection(Box::new(self), elem),
161 ty,
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
169#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
170#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("CProj"))]
171pub enum ConstProjectionElem {
172 Field(Option<VariantId>, FieldId),
174 #[serde_state(stateless)]
176 Index(IntegerValue),
177 #[serde_state(stateless)]
179 Subslice {
180 from: IntegerValue,
181 to: IntegerValue,
182 },
183 Offset {
187 count: IntegerValue,
188 ty: Option<Ty>,
189 in_bounds: bool,
190 pointee_is_sized: Option<TraitRef>,
191 },
192}
193
194#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
196#[derive(EnumAsInner)]
197#[derive(
198 Serialize,
199 Deserialize,
200 SerializeState,
201 DeserializeState,
202 Drive,
203 DriveMut,
204 DriveTwo
205)]
206#[cfg_attr(feature = "charon_on_charon", charon::variants_suffix("Integer"))]
207#[serde_state(stateless)]
208pub enum IntegerValue {
209 Unsigned(UIntTy, #[serde(with = "scalar_value_ser_de")] u128),
210 Signed(IntTy, #[serde(with = "scalar_value_ser_de")] i128),
211}
212
213#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
217#[derive(Serialize, Deserialize, Drive, DriveMut, DriveTwo)]
218pub struct FloatValue {
219 #[cfg_attr(feature = "charon_on_charon", charon::rename("float_value"))]
220 pub value: String,
221 #[cfg_attr(feature = "charon_on_charon", charon::rename("float_bits"))]
222 #[serde(with = "scalar_value_ser_de")]
223 pub bits: u128,
224 #[cfg_attr(feature = "charon_on_charon", charon::rename("float_ty"))]
225 pub ty: FloatTy,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
232#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
233#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Prov"))]
234pub enum GlobalProvenance {
235 Global(GlobalDeclRef),
236 Function(FnPtr, Ty),
238 TypeId(Ty),
242}
243
244#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
247#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
248pub enum Byte {
249 Uninit,
251 Value(u8),
253 Provenance(GlobalProvenance, IntegerValue, u8),
257}
258
259macro_rules! static_constant {
260 ($e:expr) => {{
261 use std::sync::LazyLock;
262 static CONSTANT: LazyLock<ConstantExpr> = LazyLock::new(|| $e);
263 CONSTANT.clone()
264 }};
265}
266
267impl ConstantExpr {
268 pub fn new(kind: ConstantExprKind, ty: Ty) -> Self {
269 Self(HashConsed::new(WithCachedTypeInfo::new((kind, ty))))
270 }
271
272 pub fn kind(&self) -> &ConstantExprKind {
273 &self.0.inner().0
274 }
275
276 pub fn ty(&self) -> &Ty {
277 &self.0.inner().1
278 }
279
280 pub fn with_contents_mut<R>(
281 &mut self,
282 f: impl FnOnce(&mut ConstantExprKind, &mut Ty) -> R,
283 ) -> R {
284 self.0
285 .with_inner_mut(|contents| contents.with_value_mut(|(kind, ty)| f(kind, ty)))
286 }
287
288 pub fn mk_unit() -> Self {
289 static_constant!(ConstantExpr::new(
290 ConstantExprKind::Adt(None, IndexVec::new()),
291 Ty::mk_unit(),
292 ))
293 }
294
295 pub fn mk_usize(value: u128) -> Self {
296 if value == 0 {
297 static_constant!(IntegerValue::mk_usize(0).to_constant())
298 } else {
299 IntegerValue::mk_usize(value).to_constant()
300 }
301 }
302
303 pub fn mk_bool(value: bool) -> Self {
304 match value {
305 true => static_constant!(ConstantExpr::new(
306 ConstantExprKind::Bool(true),
307 Ty::mk_bool()
308 )),
309 false => static_constant!(ConstantExpr::new(
310 ConstantExprKind::Bool(false),
311 Ty::mk_bool()
312 )),
313 }
314 }
315
316 pub fn as_usize_literal(&self) -> Option<u128> {
317 match self.kind() {
318 ConstantExprKind::Integer(IntegerValue::Unsigned(UIntTy::Usize, value)) => Some(*value),
319 _ => None,
320 }
321 }
322}
323
324impl ConstantExprKind {
325 pub fn from_bits(scalar_ty: &ScalarTy, bits: u128) -> Option<Self> {
326 match *scalar_ty {
327 ScalarTy::Integer(int_ty) => Some(Self::Integer(IntegerValue::from_bits(int_ty, bits))),
328 ScalarTy::Bool => match bits {
329 0 => Some(Self::Bool(false)),
330 1 => Some(Self::Bool(true)),
331 _ => None,
332 },
333 ScalarTy::Char => {
334 let bytes: [u8; 4] = bits.to_le_bytes()[0..4].try_into().unwrap();
335 Some(Self::Char(
336 std::char::from_u32(u32::from_le_bytes(bytes)).unwrap(),
337 ))
338 }
339 ScalarTy::Float(_) => None,
340 }
341 }
342}
343
344impl std::ops::Deref for ConstantExpr {
345 type Target = WithCachedTypeInfo<(ConstantExprKind, Ty)>;
346 fn deref(&self) -> &Self::Target {
347 &self.0
348 }
349}
350
351impl IntegerValue {
352 fn ptr_size_max(ptr_size: ByteCount, signed: bool) -> u128 {
353 match ptr_size {
354 2 => {
355 if signed {
356 i16::MAX as u128
357 } else {
358 u16::MAX as u128
359 }
360 }
361 4 => {
362 if signed {
363 i32::MAX as u128
364 } else {
365 u32::MAX as u128
366 }
367 }
368 8 => {
369 if signed {
370 i64::MAX as u128
371 } else {
372 u64::MAX as u128
373 }
374 }
375 _ => panic!("`ptr_size_max`: unsupported ptr size {ptr_size}"),
376 }
377 }
378
379 fn ptr_size_min(ptr_size: ByteCount, signed: bool) -> i128 {
380 match ptr_size {
381 2 => {
382 if signed {
383 i16::MIN as i128
384 } else {
385 u16::MIN as i128
386 }
387 }
388 4 => {
389 if signed {
390 i32::MIN as i128
391 } else {
392 u32::MIN as i128
393 }
394 }
395 8 => {
396 if signed {
397 i64::MIN as i128
398 } else {
399 u64::MIN as i128
400 }
401 }
402 _ => panic!("`ptr_size_min`: unsupported ptr size {ptr_size}"),
403 }
404 }
405
406 pub fn ty(&self) -> IntegerTy {
407 match self {
408 IntegerValue::Signed(ty, _) => IntegerTy::Signed(*ty),
409 IntegerValue::Unsigned(ty, _) => IntegerTy::Unsigned(*ty),
410 }
411 }
412
413 pub fn is_int(&self) -> bool {
414 matches!(self, IntegerValue::Signed(_, _))
415 }
416
417 pub fn is_uint(&self) -> bool {
418 matches!(self, IntegerValue::Unsigned(_, _))
419 }
420
421 pub fn as_uint(&self) -> Option<u128> {
425 match self {
426 IntegerValue::Unsigned(_, v) => Some(*v),
427 _ => None,
428 }
429 }
430
431 pub fn uint_is_in_bounds(ptr_size: ByteCount, ty: UIntTy, v: u128) -> bool {
432 match ty {
433 UIntTy::Usize => v <= Self::ptr_size_max(ptr_size, false),
434 UIntTy::U8 => v <= (u8::MAX as u128),
435 UIntTy::U16 => v <= (u16::MAX as u128),
436 UIntTy::U32 => v <= (u32::MAX as u128),
437 UIntTy::U64 => v <= (u64::MAX as u128),
438 UIntTy::U128 => true,
439 }
440 }
441
442 pub fn from_unchecked_uint(ty: UIntTy, v: u128) -> IntegerValue {
443 IntegerValue::Unsigned(ty, v)
444 }
445
446 pub fn from_uint(ptr_size: ByteCount, ty: UIntTy, v: u128) -> Option<Self> {
447 if !IntegerValue::uint_is_in_bounds(ptr_size, ty, v) {
448 None
449 } else {
450 Some(IntegerValue::from_unchecked_uint(ty, v))
451 }
452 }
453
454 pub fn mk_usize(value: u128) -> Self {
455 IntegerValue::Unsigned(UIntTy::Usize, value)
456 }
457
458 pub fn as_int(&self) -> Option<i128> {
462 match self {
463 IntegerValue::Signed(_, v) => Some(*v),
464 _ => None,
465 }
466 }
467
468 pub fn int_is_in_bounds(ptr_size: ByteCount, ty: IntTy, v: i128) -> bool {
469 match ty {
470 IntTy::Isize => {
471 v >= Self::ptr_size_min(ptr_size, true)
472 && v <= Self::ptr_size_max(ptr_size, true) as i128
473 }
474 IntTy::I8 => v >= (i8::MIN as i128) && v <= (i8::MAX as i128),
475 IntTy::I16 => v >= (i16::MIN as i128) && v <= (i16::MAX as i128),
476 IntTy::I32 => v >= (i32::MIN as i128) && v <= (i32::MAX as i128),
477 IntTy::I64 => v >= (i64::MIN as i128) && v <= (i64::MAX as i128),
478 IntTy::I128 => true,
479 }
480 }
481
482 pub fn from_unchecked_int(ty: IntTy, v: i128) -> IntegerValue {
483 IntegerValue::Signed(ty, v)
484 }
485
486 pub fn to_bits(&self) -> u128 {
488 match *self {
489 IntegerValue::Unsigned(_, v) => v,
490 IntegerValue::Signed(_, v) => u128::from_le_bytes(v.to_le_bytes()),
491 }
492 }
493
494 pub fn from_le_bytes(ty: IntegerTy, bytes: [u8; 16]) -> Self {
499 macro_rules! from_le_bytes {
500 ($m:ident, $b:ident, [$(($i_ty: ty, $i:ident, $s:ident, $n_ty:ty, $t:ty)),*]) => {
501 match $m {
502 $(
503 IntegerTy::$s(<$i_ty>::$i) => {
504 let n = size_of::<$n_ty>();
505 let b: [u8; _] = $b[0..n].try_into().unwrap();
506 IntegerValue::$s(<$i_ty>::$i, <$n_ty>::from_le_bytes(b) as $t)
507 }
508 )*
509 }
510 }
511 }
512
513 from_le_bytes!(
514 ty,
515 bytes,
516 [
517 (IntTy, Isize, Signed, isize, i128),
518 (IntTy, I8, Signed, i8, i128),
519 (IntTy, I16, Signed, i16, i128),
520 (IntTy, I32, Signed, i32, i128),
521 (IntTy, I64, Signed, i64, i128),
522 (IntTy, I128, Signed, i128, i128),
523 (UIntTy, Usize, Unsigned, usize, u128),
524 (UIntTy, U8, Unsigned, u8, u128),
525 (UIntTy, U16, Unsigned, u16, u128),
526 (UIntTy, U32, Unsigned, u32, u128),
527 (UIntTy, U64, Unsigned, u64, u128),
528 (UIntTy, U128, Unsigned, u128, u128)
529 ]
530 )
531 }
532
533 pub fn from_bits(ty: IntegerTy, bits: u128) -> Self {
534 let bytes = bits.to_le_bytes();
535 Self::from_le_bytes(ty, bytes)
536 }
537
538 pub fn from_int(ptr_size: ByteCount, ty: IntTy, v: i128) -> Option<IntegerValue> {
542 if !IntegerValue::int_is_in_bounds(ptr_size, ty, v) {
543 None
544 } else {
545 Some(IntegerValue::from_unchecked_int(ty, v))
546 }
547 }
548
549 pub fn add(self, n: u128) -> Option<Self> {
551 Some(match self {
552 IntegerValue::Unsigned(ty, v) => IntegerValue::Unsigned(ty, v.checked_add(n)?),
553 IntegerValue::Signed(ty, v) => {
554 IntegerValue::Signed(ty, v.checked_add(n.try_into().unwrap())?)
555 }
556 })
557 }
558
559 pub fn to_constant(self) -> ConstantExpr {
560 let scalar_ty = ScalarTy::Integer(self.ty());
561 ConstantExpr::new(
562 ConstantExprKind::Integer(self),
563 TyKind::Scalar(scalar_ty).into_ty(),
564 )
565 }
566}
567
568pub(crate) mod scalar_value_ser_de {
570 use std::{marker::PhantomData, str::FromStr};
571
572 use serde::de::{Deserializer, Error};
573
574 pub fn serialize<S, V>(val: &V, serializer: S) -> Result<S::Ok, S::Error>
575 where
576 S: serde::ser::Serializer,
577 V: ToString,
578 {
579 serializer.serialize_str(&val.to_string())
580 }
581
582 pub fn serialize_state<S, State: ?Sized, V>(
585 val: &V,
586 _state: &State,
587 serializer: S,
588 ) -> Result<S::Ok, S::Error>
589 where
590 S: serde::ser::Serializer,
591 V: ToString,
592 {
593 serialize(val, serializer)
594 }
595
596 pub fn deserialize<'de, D, V>(deserializer: D) -> Result<V, D::Error>
597 where
598 D: Deserializer<'de>,
599 V: FromStr,
600 {
601 struct Visitor<V> {
602 _val: PhantomData<V>,
603 }
604 impl<'de, V> serde::de::Visitor<'de> for Visitor<V>
605 where
606 V: FromStr,
607 {
608 type Value = V;
609 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
610 write!(f, "IntegerValue value")
611 }
612 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
613 where
614 E: Error,
615 {
616 v.parse()
617 .map_err(|_| E::custom("Could not parse 128 bit integer!"))
618 }
619 }
620 deserializer.deserialize_str(Visitor { _val: PhantomData })
621 }
622
623 pub fn deserialize_state<'de, D, State: ?Sized, V>(
626 _state: &State,
627 deserializer: D,
628 ) -> Result<V, D::Error>
629 where
630 D: Deserializer<'de>,
631 V: FromStr,
632 {
633 deserialize(deserializer)
634 }
635}
636
637#[cfg(test)]
638mod test {
639 use super::*;
640
641 #[test]
642 fn test_big_endian_scalars() {
643 let u128 = 0x12345678901234567890123456789012u128;
644 let le_bytes = u128.to_le_bytes();
645
646 let le_scalar = IntegerValue::from_le_bytes(IntegerTy::Unsigned(UIntTy::U128), le_bytes);
647 assert_eq!(le_scalar, IntegerValue::Unsigned(UIntTy::U128, u128));
648
649 let i64 = 0x1234567890123456i64;
650 let le_bytes = (i64 as i128).to_le_bytes();
651 let le_scalar = IntegerValue::from_le_bytes(IntegerTy::Signed(IntTy::I64), le_bytes);
652 assert_eq!(le_scalar, IntegerValue::Signed(IntTy::I64, i64 as i128));
653 }
654}