1use std::any::Any;
11use std::fmt;
12use std::hash::{Hash, Hasher};
13use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
14
15use dashmap::DashMap;
16
17use xur_resolve::{DefId, NativeFnId, NativeTypeId, RtType};
18use xur_span::Symbol;
19
20pub fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
23 mutex.lock().unwrap_or_else(PoisonError::into_inner)
24}
25
26pub fn with_pair<T: ?Sized, R>(
31 a: &Arc<Mutex<T>>,
32 b: &Arc<Mutex<T>>,
33 f: impl FnOnce(&T, &T) -> R,
34) -> R {
35 if Arc::ptr_eq(a, b) {
36 let g = lock(a);
37 f(&g, &g)
38 } else {
39 let ga = lock(a);
40 let gb = lock(b);
41 f(&ga, &gb)
42 }
43}
44
45#[derive(Debug, Clone, Copy)]
47pub enum IntValue {
48 I8(i8),
49 I16(i16),
50 I32(i32),
51 I64(i64),
52 U8(u8),
53 U16(u16),
54 U32(u32),
55 U64(u64),
56}
57
58impl IntValue {
59 pub fn to_i128(self) -> i128 {
60 match self {
61 Self::I8(v) => v as i128,
62 Self::I16(v) => v as i128,
63 Self::I32(v) => v as i128,
64 Self::I64(v) => v as i128,
65 Self::U8(v) => v as i128,
66 Self::U16(v) => v as i128,
67 Self::U32(v) => v as i128,
68 Self::U64(v) => v as i128,
69 }
70 }
71
72 pub fn to_i64(self) -> Option<i64> {
73 i64::try_from(self.to_i128()).ok()
74 }
75
76 pub fn to_u64(self) -> Option<u64> {
77 u64::try_from(self.to_i128()).ok()
78 }
79
80 pub fn to_u32(self) -> Option<u32> {
81 u32::try_from(self.to_i128()).ok()
82 }
83
84 pub fn to_usize(self) -> Option<usize> {
85 usize::try_from(self.to_i128()).ok()
86 }
87
88 pub fn as_f64(self) -> f64 {
89 self.to_i128() as f64
90 }
91
92 pub fn is_signed(self) -> bool {
93 matches!(
94 self,
95 Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_)
96 )
97 }
98
99 pub fn is_zero(self) -> bool {
100 self.to_i128() == 0
101 }
102
103 pub fn width(self) -> u8 {
104 match self {
105 Self::I8(_) | Self::U8(_) => 1,
106 Self::I16(_) | Self::U16(_) => 2,
107 Self::I32(_) | Self::U32(_) => 4,
108 Self::I64(_) | Self::U64(_) => 8,
109 }
110 }
111
112 pub fn promote_type(a: Self, b: Self) -> (bool, u8) {
116 (a.is_signed() || b.is_signed(), a.width().max(b.width()))
117 }
118
119 pub fn wrap(value: i128, signed: bool, width: u8) -> Self {
122 match (signed, width) {
123 (true, 1) => Self::I8(value as i8),
124 (true, 2) => Self::I16(value as i16),
125 (true, 4) => Self::I32(value as i32),
126 (true, _) => Self::I64(value as i64),
127 (false, 1) => Self::U8(value as u8),
128 (false, 2) => Self::U16(value as u16),
129 (false, 4) => Self::U32(value as u32),
130 (false, _) => Self::U64(value as u64),
131 }
132 }
133
134 pub fn wrapping_neg(self) -> Self {
137 Self::wrap(self.to_i128().wrapping_neg(), true, self.width())
138 }
139
140 pub fn rt_type(self) -> RtType {
142 let (name, min, max) = match self {
143 Self::I8(_) => ("i8", i8::MIN as i128, i8::MAX as i128),
144 Self::I16(_) => ("i16", i16::MIN as i128, i16::MAX as i128),
145 Self::I32(_) => ("i32", i32::MIN as i128, i32::MAX as i128),
146 Self::I64(_) => ("i64", i64::MIN as i128, i64::MAX as i128),
147 Self::U8(_) => ("u8", 0, u8::MAX as i128),
148 Self::U16(_) => ("u16", 0, u16::MAX as i128),
149 Self::U32(_) => ("u32", 0, u32::MAX as i128),
150 Self::U64(_) => ("u64", 0, u64::MAX as i128),
151 };
152 RtType::Int { name, min, max }
153 }
154
155 pub fn bit_not(self) -> Self {
156 match self {
157 Self::I8(v) => Self::I8(!v),
158 Self::I16(v) => Self::I16(!v),
159 Self::I32(v) => Self::I32(!v),
160 Self::I64(v) => Self::I64(!v),
161 Self::U8(v) => Self::U8(!v),
162 Self::U16(v) => Self::U16(!v),
163 Self::U32(v) => Self::U32(!v),
164 Self::U64(v) => Self::U64(!v),
165 }
166 }
167}
168
169impl PartialEq for IntValue {
170 fn eq(&self, other: &Self) -> bool {
171 self.to_i128() == other.to_i128()
172 }
173}
174
175impl Eq for IntValue {}
176
177impl PartialOrd for IntValue {
178 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
179 Some(self.cmp(other))
180 }
181}
182
183impl Ord for IntValue {
184 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
185 self.to_i128().cmp(&other.to_i128())
186 }
187}
188
189impl Hash for IntValue {
190 fn hash<H: Hasher>(&self, state: &mut H) {
191 self.to_i128().hash(state);
192 }
193}
194
195impl fmt::Display for IntValue {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 match self {
198 Self::I8(v) => write!(f, "{v}"),
199 Self::I16(v) => write!(f, "{v}"),
200 Self::I32(v) => write!(f, "{v}"),
201 Self::I64(v) => write!(f, "{v}"),
202 Self::U8(v) => write!(f, "{v}"),
203 Self::U16(v) => write!(f, "{v}"),
204 Self::U32(v) => write!(f, "{v}"),
205 Self::U64(v) => write!(f, "{v}"),
206 }
207 }
208}
209
210impl From<i8> for IntValue {
211 fn from(v: i8) -> Self {
212 Self::I8(v)
213 }
214}
215impl From<i16> for IntValue {
216 fn from(v: i16) -> Self {
217 Self::I16(v)
218 }
219}
220impl From<i32> for IntValue {
221 fn from(v: i32) -> Self {
222 Self::I32(v)
223 }
224}
225impl From<i64> for IntValue {
226 fn from(v: i64) -> Self {
227 Self::I64(v)
228 }
229}
230impl From<u8> for IntValue {
231 fn from(v: u8) -> Self {
232 Self::U8(v)
233 }
234}
235impl From<u16> for IntValue {
236 fn from(v: u16) -> Self {
237 Self::U16(v)
238 }
239}
240impl From<u32> for IntValue {
241 fn from(v: u32) -> Self {
242 Self::U32(v)
243 }
244}
245impl From<u64> for IntValue {
246 fn from(v: u64) -> Self {
247 Self::U64(v)
248 }
249}
250impl From<usize> for IntValue {
251 fn from(v: usize) -> Self {
252 Self::U64(v as u64)
253 }
254}
255impl From<bool> for IntValue {
256 fn from(v: bool) -> Self {
257 Self::U8(v as u8)
258 }
259}
260
261#[derive(Debug, Clone, Copy)]
263pub enum FloatValue {
264 F32(f32),
265 F64(f64),
266}
267
268impl FloatValue {
269 pub fn as_f64(self) -> f64 {
270 match self {
271 Self::F32(v) => v as f64,
272 Self::F64(v) => v,
273 }
274 }
275
276 pub fn as_f32(self) -> f32 {
277 match self {
278 Self::F32(v) => v,
279 Self::F64(v) => v as f32,
280 }
281 }
282
283 pub fn negate(self) -> Self {
285 match self {
286 Self::F32(v) => Self::F32(-v),
287 Self::F64(v) => Self::F64(-v),
288 }
289 }
290
291 pub fn width(self) -> u8 {
292 match self {
293 Self::F32(_) => 4,
294 Self::F64(_) => 8,
295 }
296 }
297
298 pub fn rt_type(self) -> RtType {
300 RtType::Float {
301 name: match self {
302 Self::F32(_) => "f32",
303 Self::F64(_) => "f64",
304 },
305 }
306 }
307}
308
309impl PartialEq for FloatValue {
310 fn eq(&self, other: &Self) -> bool {
311 self.as_f64() == other.as_f64()
312 }
313}
314
315impl fmt::Display for FloatValue {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 match self {
318 Self::F32(v) => write!(f, "{v}"),
319 Self::F64(v) => write!(f, "{v}"),
320 }
321 }
322}
323
324impl From<f32> for FloatValue {
325 fn from(v: f32) -> Self {
326 Self::F32(v)
327 }
328}
329impl From<f64> for FloatValue {
330 fn from(v: f64) -> Self {
331 Self::F64(v)
332 }
333}
334
335#[derive(Debug, Clone)]
336pub enum Value {
337 Unit,
339 Bool(bool),
340 Int(IntValue),
341 Float(FloatValue),
342 Str(Arc<str>),
343 Tuple(Arc<[Value]>),
344 List(Arc<Mutex<Vec<Value>>>),
345 Map(Arc<DashMap<MapKey, Value>>),
347 Bytes(Arc<Mutex<Vec<u8>>>),
349 Ptr(u64),
351 Adt(Arc<Adt>),
353 Native(Arc<NativeObject>),
355 NativeEnum(Arc<NativeEnum>),
359 Record(Arc<Record>),
361 Fn(DefId),
363 Ctor(DefId),
366 NativeFn(NativeFnId),
368 Closure(Arc<Closure>),
370 Iterator(Arc<ValueIter>),
372 Module(DefId),
374 Range(Range),
376 Type(Box<RtType>),
378}
379
380#[derive(Debug, Clone)]
382pub struct Adt {
383 pub ctor: DefId,
385 pub fields: Vec<Value>,
386}
387
388#[derive(Debug)]
390pub struct Closure {
391 pub code: Arc<dyn Any + Send + Sync>,
393 pub captures: Mutex<Vec<Value>>,
396 pub type_args: Vec<crate::TypeRef>,
398}
399
400pub struct ValueIter(Mutex<Box<dyn Iterator<Item = Value> + Send>>);
402
403impl ValueIter {
404 pub fn new(iter: impl Iterator<Item = Value> + Send + 'static) -> Self {
405 Self(Mutex::new(Box::new(iter)))
406 }
407
408 #[allow(clippy::should_implement_trait)] pub fn next(&self) -> Option<Value> {
410 lock(&self.0).next()
411 }
412}
413
414impl fmt::Debug for ValueIter {
415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416 f.write_str("ValueIter")
417 }
418}
419
420pub struct NativeObject {
424 pub ty: NativeTypeId,
425 value: Mutex<Box<dyn Any + Send>>,
426 _keep_alive: Option<Arc<dyn Any + Send + Sync>>,
431 type_args: Vec<BuiltinType>,
434}
435
436impl NativeObject {
437 pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
438 Self {
439 ty,
440 value: Mutex::new(value),
441 _keep_alive: None,
442 type_args: Vec::new(),
443 }
444 }
445
446 pub fn with_type_args(
448 ty: NativeTypeId,
449 value: Box<dyn Any + Send>,
450 type_args: Vec<BuiltinType>,
451 ) -> Self {
452 Self {
453 ty,
454 value: Mutex::new(value),
455 _keep_alive: None,
456 type_args,
457 }
458 }
459
460 pub fn borrowing(
463 ty: NativeTypeId,
464 value: Box<dyn Any + Send>,
465 keep_alive: Arc<dyn Any + Send + Sync>,
466 ) -> Self {
467 Self {
468 ty,
469 value: Mutex::new(value),
470 _keep_alive: Some(keep_alive),
471 type_args: Vec::new(),
472 }
473 }
474
475 pub fn with<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
477 lock(&self.value).downcast_ref().map(f)
478 }
479
480 pub fn with_mut<T: 'static, R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
482 lock(&self.value).downcast_mut().map(f)
483 }
484
485 pub fn type_args(&self) -> &[BuiltinType] {
488 &self.type_args
489 }
490
491 pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
494 self._keep_alive.clone()
495 }
496
497 pub fn with_any<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
499 f(lock(&self.value).as_ref())
500 }
501}
502
503impl fmt::Debug for NativeObject {
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 f.debug_tuple("NativeObject").field(&self.ty).finish()
506 }
507}
508
509pub struct NativeEnum {
513 pub object: Arc<NativeObject>,
514 pub variant: Symbol,
515 pub fields: Vec<(Symbol, Value)>,
516}
517
518impl NativeEnum {
519 pub fn field(&self, name: Symbol) -> Option<&Value> {
520 self.fields
521 .iter()
522 .find(|(field, _)| *field == name)
523 .map(|(_, value)| value)
524 }
525}
526
527impl fmt::Debug for NativeEnum {
528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529 f.debug_struct("NativeEnum")
530 .field("ty", &self.object.ty)
531 .field("variant", &self.variant)
532 .finish()
533 }
534}
535
536impl PartialEq for NativeEnum {
537 fn eq(&self, other: &Self) -> bool {
538 self.object.ty == other.object.ty
539 && self.variant == other.variant
540 && self.fields == other.fields
541 }
542}
543
544#[derive(Debug, Clone, PartialEq)]
547pub struct Record {
548 pub ty: Option<NativeTypeId>,
551 pub variant: Option<Symbol>,
553 pub fields: Vec<(Symbol, Value)>,
554}
555
556impl Record {
557 pub fn new(fields: Vec<(Symbol, Value)>) -> Self {
559 Self {
560 ty: None,
561 variant: None,
562 fields,
563 }
564 }
565
566 pub fn field(&self, name: Symbol) -> Option<&Value> {
567 self.fields
568 .iter()
569 .find(|(field, _)| *field == name)
570 .map(|(_, value)| value)
571 }
572}
573
574#[derive(Debug, Clone, Copy, PartialEq, Eq)]
575pub struct Range {
576 pub start: Option<i64>,
577 pub end: Option<i64>,
578 pub inclusive: bool,
580}
581
582impl Value {
583 pub fn int(v: i64) -> Self {
585 Self::Int(IntValue::I64(v))
586 }
587
588 pub fn float(v: f64) -> Self {
589 Self::Float(FloatValue::F64(v))
590 }
591
592 pub fn str(s: &str) -> Self {
593 Self::Str(s.into())
594 }
595
596 pub fn list(items: Vec<Value>) -> Self {
597 Self::List(Arc::new(Mutex::new(items)))
598 }
599
600 pub fn map(entries: Vec<(Value, Value)>) -> Self {
601 let map = DashMap::new();
602 for (k, v) in entries {
603 map.insert(MapKey(k), v);
604 }
605 Self::Map(Arc::new(map))
606 }
607
608 pub fn bytes(bytes: Vec<u8>) -> Self {
609 Self::Bytes(Arc::new(Mutex::new(bytes)))
610 }
611
612 pub fn tuple(items: Vec<Value>) -> Self {
613 if items.is_empty() {
614 Self::Unit
615 } else {
616 Self::Tuple(items.into())
617 }
618 }
619
620 pub fn adt(ctor: DefId, fields: Vec<Value>) -> Self {
621 Self::Adt(Arc::new(Adt { ctor, fields }))
622 }
623
624 pub fn kind(&self) -> &'static str {
626 match self {
627 Self::Unit => "unit",
628 Self::Bool(_) => "bool",
629 Self::Int(_) => "integer",
630 Self::Float(_) => "float",
631 Self::Str(_) => "string",
632 Self::Tuple(_) => "tuple",
633 Self::List(_) => "list",
634 Self::Map(_) => "map",
635 Self::Bytes(_) => "bytes",
636 Self::Ptr(_) => "pointer",
637 Self::Adt(_) => "struct or enum",
638 Self::Native(_) => "native object",
639 Self::NativeEnum(_) => "native enum",
640 Self::Record(_) => "record",
641 Self::Fn(_) | Self::NativeFn(_) => "function",
642 Self::Closure(_) => "closure",
643 Self::Iterator(_) => "iterator",
644 Self::Ctor(_) => "constructor",
645 Self::Module(_) => "module",
646 Self::Range(_) => "range",
647 Self::Type(_) => "type",
648 }
649 }
650}
651
652#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
654pub enum BuiltinType {
655 Bool,
656 Int,
657 Float,
658 Str,
659 Tuple,
660 List,
661 Map,
662 Bytes,
663 Ptr,
664 Range,
665 Record,
666 Struct,
669}
670
671impl fmt::Display for BuiltinType {
672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 f.write_str(match self {
674 Self::Bool => "bool",
675 Self::Int => "int",
676 Self::Float => "float",
677 Self::Str => "str",
678 Self::Tuple => "tuple",
679 Self::List => "list",
680 Self::Map => "map",
681 Self::Bytes => "bytes",
682 Self::Ptr => "ptr",
683 Self::Range => "range",
684 Self::Record => "record",
685 Self::Struct => "struct",
686 })
687 }
688}
689
690impl Value {
691 pub fn builtin_type(&self) -> Option<BuiltinType> {
693 Some(match self {
694 Self::Bool(_) => BuiltinType::Bool,
695 Self::Int(_) => BuiltinType::Int,
696 Self::Float(_) => BuiltinType::Float,
697 Self::Str(_) => BuiltinType::Str,
698 Self::Tuple(_) => BuiltinType::Tuple,
699 Self::List(_) => BuiltinType::List,
700 Self::Map(_) => BuiltinType::Map,
701 Self::Bytes(_) => BuiltinType::Bytes,
702 Self::Ptr(_) => BuiltinType::Ptr,
703 Self::Range(_) => BuiltinType::Range,
704 Self::Record(_) => BuiltinType::Record,
705 Self::Adt(_) => BuiltinType::Struct,
706 _ => return None,
707 })
708 }
709}
710
711impl PartialEq for Value {
714 fn eq(&self, other: &Self) -> bool {
715 match (self, other) {
716 (Self::Unit, Self::Unit) => true,
717 (Self::Bool(a), Self::Bool(b)) => a == b,
718 (Self::Int(a), Self::Int(b)) => a == b,
719 (Self::Float(a), Self::Float(b)) => a == b,
720 (Self::Str(a), Self::Str(b)) => a == b,
721 (Self::Tuple(a), Self::Tuple(b)) => a == b,
722 (Self::List(a), Self::List(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
723 (Self::Map(a), Self::Map(b)) => {
724 Arc::ptr_eq(a, b)
725 || (a.len() == b.len()
726 && a.iter().all(|entry| {
727 b.get(entry.key())
728 .is_some_and(|v| *v.value() == *entry.value())
729 }))
730 }
731 (Self::Bytes(a), Self::Bytes(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
732 (Self::Ptr(a), Self::Ptr(b)) => a == b,
733 (Self::Adt(a), Self::Adt(b)) => a.ctor == b.ctor && a.fields == b.fields,
734 (Self::Native(a), Self::Native(b)) => Arc::ptr_eq(a, b),
737 (Self::NativeEnum(a), Self::NativeEnum(b)) => a == b,
738 (Self::Record(a), Self::Record(b)) => a == b,
739 (Self::Fn(a), Self::Fn(b)) | (Self::Ctor(a), Self::Ctor(b)) => a == b,
740 (Self::Module(a), Self::Module(b)) => a == b,
741 (Self::NativeFn(a), Self::NativeFn(b)) => a == b,
742 (Self::Range(a), Self::Range(b)) => a == b,
743 (Self::Type(a), Self::Type(b)) => a == b,
744 (Self::Closure(a), Self::Closure(b)) => Arc::ptr_eq(a, b),
745 (Self::Iterator(a), Self::Iterator(b)) => Arc::ptr_eq(a, b),
746 _ => false,
747 }
748 }
749}
750
751#[derive(Debug, Clone)]
754pub struct MapKey(pub Value);
755
756impl PartialEq for MapKey {
757 fn eq(&self, other: &Self) -> bool {
758 self.0 == other.0
759 }
760}
761
762impl Eq for MapKey {}
763
764impl Hash for MapKey {
765 fn hash<H: Hasher>(&self, state: &mut H) {
766 std::mem::discriminant(&self.0).hash(state);
767 match &self.0 {
768 Value::Unit => {}
769 Value::Bool(b) => b.hash(state),
770 Value::Int(i) => i.hash(state),
771 Value::Str(s) => s.hash(state),
772 Value::Adt(adt) if adt.fields.is_empty() => adt.ctor.hash(state),
773 other => panic!("{} is not hashable", other.kind()),
774 }
775 }
776}
777
778#[cfg(test)]
779mod tests {
780 use super::*;
781
782 #[test]
783 fn values_can_be_shared_between_threads() {
784 fn assert_send_sync<T: Send + Sync>() {}
785 assert_send_sync::<Value>();
786 }
787
788 #[test]
789 fn equality_is_structural_and_kind_strict() {
790 assert_eq!(
791 Value::list(vec![Value::int(1)]),
792 Value::list(vec![Value::int(1)])
793 );
794 assert_ne!(Value::int(1), Value::float(1.0));
795 assert_eq!(Value::str("a"), Value::str("a"));
796 assert_eq!(Value::tuple(vec![]), Value::Unit);
797 }
798
799 #[test]
800 fn int_value_cross_width_equality() {
801 assert_eq!(IntValue::I64(42), IntValue::U8(42));
802 assert_eq!(IntValue::U32(0), IntValue::I8(0));
803 assert_ne!(IntValue::I64(-1), IntValue::U64(u64::MAX));
804 }
805
806 #[test]
807 fn int_value_ordering() {
808 assert!(IntValue::I64(-1) < IntValue::U8(0));
809 assert!(IntValue::U64(u64::MAX) > IntValue::I64(i64::MAX));
810 }
811
812 #[test]
813 fn int_value_conversions() {
814 assert_eq!(IntValue::U64(u64::MAX).to_i64(), None);
815 assert_eq!(IntValue::U64(42).to_i64(), Some(42));
816 assert_eq!(IntValue::I64(-1).to_u64(), None);
817 assert_eq!(IntValue::U8(255).to_u64(), Some(255));
818 }
819
820 #[test]
821 fn float_value_cross_width_equality() {
822 assert_eq!(FloatValue::F32(1.0), FloatValue::F64(1.0));
823 }
824}