Skip to main content

xur_runtime/
value.rs

1//! Runtime values.
2//!
3//! Xur is dynamically checked, so every value carries what it is. Lists and
4//! native objects are shared and mutable, like Python's objects; everything
5//! else is immutable. Cloning a value is always cheap.
6//!
7//! Values are `Send + Sync` so threads can share them: shared mutable values
8//! are behind a [`Mutex`].
9
10use crate::RuntimeError;
11use std::any::Any;
12use std::fmt;
13use std::hash::{Hash, Hasher};
14use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
15
16use dashmap::DashMap;
17
18use xur_resolve::{DefId, NativeFnId, NativeTypeId, RtType};
19use xur_span::Symbol;
20
21/// Locks `mutex`. A panic while it was held doesn't stop the program from
22/// using the value, as Xur values have no invariants a panic could break.
23pub fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
24    mutex.lock().unwrap_or_else(PoisonError::into_inner)
25}
26
27/// Locks two shared values for reading without cloning. When they are the same
28/// value (aliased `Arc` — e.g. `xs.zip(xs)`), locks it once and hands the single
29/// guard to both sides; otherwise locks each. This avoids the deadlock a plain
30/// double `lock` of the same non-reentrant `Mutex` would hit.
31pub fn with_pair<T: ?Sized, R>(
32    a: &Arc<Mutex<T>>,
33    b: &Arc<Mutex<T>>,
34    f: impl FnOnce(&T, &T) -> R,
35) -> R {
36    if Arc::ptr_eq(a, b) {
37        let g = lock(a);
38        f(&g, &g)
39    } else {
40        let ga = lock(a);
41        let gb = lock(b);
42        f(&ga, &gb)
43    }
44}
45
46/// An integer value that preserves its original width.
47#[derive(Debug, Clone, Copy)]
48pub enum IntValue {
49    I8(i8),
50    I16(i16),
51    I32(i32),
52    I64(i64),
53    U8(u8),
54    U16(u16),
55    U32(u32),
56    U64(u64),
57}
58
59impl IntValue {
60    pub fn to_i128(self) -> i128 {
61        match self {
62            Self::I8(v) => v as i128,
63            Self::I16(v) => v as i128,
64            Self::I32(v) => v as i128,
65            Self::I64(v) => v as i128,
66            Self::U8(v) => v as i128,
67            Self::U16(v) => v as i128,
68            Self::U32(v) => v as i128,
69            Self::U64(v) => v as i128,
70        }
71    }
72
73    pub fn to_i64(self) -> Option<i64> {
74        i64::try_from(self.to_i128()).ok()
75    }
76
77    pub fn to_u64(self) -> Option<u64> {
78        u64::try_from(self.to_i128()).ok()
79    }
80
81    pub fn to_u32(self) -> Option<u32> {
82        u32::try_from(self.to_i128()).ok()
83    }
84
85    pub fn to_usize(self) -> Option<usize> {
86        usize::try_from(self.to_i128()).ok()
87    }
88
89    pub fn as_f64(self) -> f64 {
90        self.to_i128() as f64
91    }
92
93    pub fn is_signed(self) -> bool {
94        matches!(
95            self,
96            Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_)
97        )
98    }
99
100    pub fn is_zero(self) -> bool {
101        self.to_i128() == 0
102    }
103
104    pub fn width(self) -> u8 {
105        match self {
106            Self::I8(_) | Self::U8(_) => 1,
107            Self::I16(_) | Self::U16(_) => 2,
108            Self::I32(_) | Self::U32(_) => 4,
109            Self::I64(_) | Self::U64(_) => 8,
110        }
111    }
112
113    /// The promoted `(signed, width)` of a binary op: signed if either operand
114    /// is, width the wider of the two. The single rule for arithmetic and
115    /// bitwise, so they agree.
116    pub fn promote_type(a: Self, b: Self) -> (bool, u8) {
117        (a.is_signed() || b.is_signed(), a.width().max(b.width()))
118    }
119
120    /// Wrap `value` into `(signed, width)` (two's-complement), as Rust's
121    /// release-mode / `wrapping_*` arithmetic does.
122    pub fn wrap(value: i128, signed: bool, width: u8) -> Self {
123        match (signed, width) {
124            (true, 1) => Self::I8(value as i8),
125            (true, 2) => Self::I16(value as i16),
126            (true, 4) => Self::I32(value as i32),
127            (true, _) => Self::I64(value as i64),
128            (false, 1) => Self::U8(value as u8),
129            (false, 2) => Self::U16(value as u16),
130            (false, 4) => Self::U32(value as u32),
131            (false, _) => Self::U64(value as u64),
132        }
133    }
134
135    /// Negation, preserving width and wrapping on overflow. The result is signed
136    /// (negating a value yields a signed value).
137    pub fn wrapping_neg(self) -> Self {
138        Self::wrap(self.to_i128().wrapping_neg(), true, self.width())
139    }
140
141    /// This value's type, preserving width and signedness.
142    pub fn rt_type(self) -> RtType {
143        let (name, min, max) = match self {
144            Self::I8(_) => ("i8", i8::MIN as i128, i8::MAX as i128),
145            Self::I16(_) => ("i16", i16::MIN as i128, i16::MAX as i128),
146            Self::I32(_) => ("i32", i32::MIN as i128, i32::MAX as i128),
147            Self::I64(_) => ("i64", i64::MIN as i128, i64::MAX as i128),
148            Self::U8(_) => ("u8", 0, u8::MAX as i128),
149            Self::U16(_) => ("u16", 0, u16::MAX as i128),
150            Self::U32(_) => ("u32", 0, u32::MAX as i128),
151            Self::U64(_) => ("u64", 0, u64::MAX as i128),
152        };
153        RtType::Int { name, min, max }
154    }
155
156    pub fn bit_not(self) -> Self {
157        match self {
158            Self::I8(v) => Self::I8(!v),
159            Self::I16(v) => Self::I16(!v),
160            Self::I32(v) => Self::I32(!v),
161            Self::I64(v) => Self::I64(!v),
162            Self::U8(v) => Self::U8(!v),
163            Self::U16(v) => Self::U16(!v),
164            Self::U32(v) => Self::U32(!v),
165            Self::U64(v) => Self::U64(!v),
166        }
167    }
168}
169
170impl PartialEq for IntValue {
171    fn eq(&self, other: &Self) -> bool {
172        self.to_i128() == other.to_i128()
173    }
174}
175
176impl Eq for IntValue {}
177
178impl PartialOrd for IntValue {
179    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
180        Some(self.cmp(other))
181    }
182}
183
184impl Ord for IntValue {
185    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
186        self.to_i128().cmp(&other.to_i128())
187    }
188}
189
190impl Hash for IntValue {
191    fn hash<H: Hasher>(&self, state: &mut H) {
192        self.to_i128().hash(state);
193    }
194}
195
196impl fmt::Display for IntValue {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        match self {
199            Self::I8(v) => write!(f, "{v}"),
200            Self::I16(v) => write!(f, "{v}"),
201            Self::I32(v) => write!(f, "{v}"),
202            Self::I64(v) => write!(f, "{v}"),
203            Self::U8(v) => write!(f, "{v}"),
204            Self::U16(v) => write!(f, "{v}"),
205            Self::U32(v) => write!(f, "{v}"),
206            Self::U64(v) => write!(f, "{v}"),
207        }
208    }
209}
210
211impl From<i8> for IntValue {
212    fn from(v: i8) -> Self {
213        Self::I8(v)
214    }
215}
216impl From<i16> for IntValue {
217    fn from(v: i16) -> Self {
218        Self::I16(v)
219    }
220}
221impl From<i32> for IntValue {
222    fn from(v: i32) -> Self {
223        Self::I32(v)
224    }
225}
226impl From<i64> for IntValue {
227    fn from(v: i64) -> Self {
228        Self::I64(v)
229    }
230}
231impl From<u8> for IntValue {
232    fn from(v: u8) -> Self {
233        Self::U8(v)
234    }
235}
236impl From<u16> for IntValue {
237    fn from(v: u16) -> Self {
238        Self::U16(v)
239    }
240}
241impl From<u32> for IntValue {
242    fn from(v: u32) -> Self {
243        Self::U32(v)
244    }
245}
246impl From<u64> for IntValue {
247    fn from(v: u64) -> Self {
248        Self::U64(v)
249    }
250}
251impl From<usize> for IntValue {
252    fn from(v: usize) -> Self {
253        Self::U64(v as u64)
254    }
255}
256impl From<bool> for IntValue {
257    fn from(v: bool) -> Self {
258        Self::U8(v as u8)
259    }
260}
261
262/// A float value that preserves its original width.
263#[derive(Debug, Clone, Copy)]
264pub enum FloatValue {
265    F32(f32),
266    F64(f64),
267}
268
269impl FloatValue {
270    pub fn as_f64(self) -> f64 {
271        match self {
272            Self::F32(v) => v as f64,
273            Self::F64(v) => v,
274        }
275    }
276
277    pub fn as_f32(self) -> f32 {
278        match self {
279            Self::F32(v) => v,
280            Self::F64(v) => v as f32,
281        }
282    }
283
284    /// Negation, preserving width.
285    pub fn negate(self) -> Self {
286        match self {
287            Self::F32(v) => Self::F32(-v),
288            Self::F64(v) => Self::F64(-v),
289        }
290    }
291
292    pub fn width(self) -> u8 {
293        match self {
294            Self::F32(_) => 4,
295            Self::F64(_) => 8,
296        }
297    }
298
299    /// This value's type, preserving width.
300    pub fn rt_type(self) -> RtType {
301        RtType::Float {
302            name: match self {
303                Self::F32(_) => "f32",
304                Self::F64(_) => "f64",
305            },
306        }
307    }
308}
309
310impl PartialEq for FloatValue {
311    fn eq(&self, other: &Self) -> bool {
312        self.as_f64() == other.as_f64()
313    }
314}
315
316impl fmt::Display for FloatValue {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        match self {
319            Self::F32(v) => write!(f, "{v}"),
320            Self::F64(v) => write!(f, "{v}"),
321        }
322    }
323}
324
325impl From<f32> for FloatValue {
326    fn from(v: f32) -> Self {
327        Self::F32(v)
328    }
329}
330impl From<f64> for FloatValue {
331    fn from(v: f64) -> Self {
332        Self::F64(v)
333    }
334}
335
336#[derive(Debug, Clone)]
337pub enum Value {
338    /// `()`, the value of expressions that produce nothing.
339    Unit,
340    Bool(bool),
341    Int(IntValue),
342    Float(FloatValue),
343    Str(Arc<str>),
344    Tuple(Arc<[Value]>),
345    List(Arc<Mutex<Vec<Value>>>),
346    /// `#{k: v}`, shared and mutable like a list.
347    Map(Arc<DashMap<MapKey, Value>>),
348    /// A byte buffer, shared and mutable like a list (Python's `bytearray`).
349    Bytes(Arc<Mutex<Vec<u8>>>),
350    /// A raw pointer (address), for memory-level operations.
351    Ptr(u64),
352    /// An instance of a struct or enum variant defined in Xur.
353    Adt(Arc<Adt>),
354    /// A value of a registered Rust type, held as the Rust value itself.
355    Native(Arc<NativeObject>),
356    /// A value of a registered Rust enum type. Keeps the boxed Rust value
357    /// (like `Native`) while exposing the active variant and fields so the
358    /// VM can pattern-match on it.
359    NativeEnum(Arc<NativeEnum>),
360    /// A value of an unregistered Rust struct, converted to named fields.
361    Record(Arc<Record>),
362    /// A function defined in Xur, including those in `impl` blocks.
363    Fn(DefId),
364    /// The constructor of a tuple struct or tuple variant used as a
365    /// function, as in `Some(1)` or `list.map(Some)`.
366    Ctor(DefId),
367    /// A function implemented in Rust.
368    NativeFn(NativeFnId),
369    /// A closure: code owned by the engine running it, and what it captured.
370    Closure(Arc<Closure>),
371    /// An iterator, from iterating a list or range or from a native function.
372    Iterator(Arc<ValueIter>),
373    /// A module: modules are values.
374    Module(DefId),
375    /// `a..b`, `a..=b`, `a..`, `..b` over integers.
376    Range(Range),
377    /// A type used as a value: `u32`, `fn(u32) -> str`, etc.
378    Type(Box<RtType>),
379}
380
381/// An instance of a struct, or of an enum variant, defined in Xur.
382#[derive(Debug, Clone)]
383pub struct Adt {
384    /// The struct or variant.
385    pub ctor: DefId,
386    pub fields: Vec<Value>,
387}
388
389/// A closure value.
390#[derive(Debug)]
391pub struct Closure {
392    /// The closure's code, in whatever form the engine running it uses.
393    pub code: Arc<dyn Any + Send + Sync>,
394    /// The values of the variables it captured when it was created.
395    /// Wrapped in a Mutex so repeated calls can write back mutations.
396    pub captures: Mutex<Vec<Value>>,
397    /// The type arguments in effect where it was created.
398    pub type_args: Vec<crate::TypeRef>,
399}
400
401/// A shared iterator over values.
402pub struct ValueIter(Mutex<Box<dyn Iterator<Item = Value> + Send>>);
403
404impl ValueIter {
405    pub fn new(iter: impl Iterator<Item = Value> + Send + 'static) -> Self {
406        Self(Mutex::new(Box::new(iter)))
407    }
408
409    #[allow(clippy::should_implement_trait)] // it is shared, so `&self`
410    pub fn next(&self) -> Option<Value> {
411        lock(&self.0).next()
412    }
413}
414
415impl fmt::Debug for ValueIter {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        f.write_str("ValueIter")
418    }
419}
420
421/// A value of a registered Rust type. Methods registered as taking
422/// `&mut self` change it in place, and every Xur value referring to it sees
423/// the change.
424pub struct NativeObject {
425    pub ty: NativeTypeId,
426    value: Mutex<Box<dyn Any + Send>>,
427    /// Memory the Rust value borrows, kept alive for as long as the object:
428    /// the file bytes behind a parsed `PEFile<'static>`, for instance. The
429    /// value's `'static` references stay valid because this never moves or
430    /// drops while the value does.
431    _keep_alive: Option<Arc<dyn Any + Send + Sync>>,
432    /// Concrete type arguments for generic native types, e.g.
433    /// `[BuiltinType::Bool]` for a `Cell<bool>`.
434    type_args: Vec<BuiltinType>,
435}
436
437impl NativeObject {
438    pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
439        Self {
440            ty,
441            value: Mutex::new(value),
442            _keep_alive: None,
443            type_args: Vec::new(),
444        }
445    }
446
447    /// A native object with concrete type arguments for a generic type.
448    pub fn with_type_args(
449        ty: NativeTypeId,
450        value: Box<dyn Any + Send>,
451        type_args: Vec<BuiltinType>,
452    ) -> Self {
453        Self {
454            ty,
455            value: Mutex::new(value),
456            _keep_alive: None,
457            type_args,
458        }
459    }
460
461    /// A native object whose value borrows `keep_alive`, which is held as
462    /// long as the object so those borrows stay valid.
463    pub fn borrowing(
464        ty: NativeTypeId,
465        value: Box<dyn Any + Send>,
466        keep_alive: Arc<dyn Any + Send + Sync>,
467    ) -> Self {
468        Self {
469            ty,
470            value: Mutex::new(value),
471            _keep_alive: Some(keep_alive),
472            type_args: Vec::new(),
473        }
474    }
475
476    /// Calls `f` with the Rust value, if it is a `T`.
477    pub fn with<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
478        lock(&self.value).downcast_ref().map(f)
479    }
480
481    /// Calls `f` with the Rust value mutably, if it is a `T`.
482    pub fn with_mut<T: 'static, R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
483        lock(&self.value).downcast_mut().map(f)
484    }
485
486    /// The concrete type arguments of this object, e.g. `[Bool]` for
487    /// `Cell<bool>`. Empty for non-generic types.
488    pub fn type_args(&self) -> &[BuiltinType] {
489        &self.type_args
490    }
491
492    /// The memory this object keeps alive for its value's borrows, to share
493    /// with a part of it parsed from the same bytes.
494    pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
495        self._keep_alive.clone()
496    }
497
498    /// Calls `f` with the Rust value, type-erased.
499    pub fn with_any<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
500        f(lock(&self.value).as_ref())
501    }
502}
503
504impl fmt::Debug for NativeObject {
505    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506        f.debug_tuple("NativeObject").field(&self.ty).finish()
507    }
508}
509
510/// A value of a registered Rust enum type. Keeps the boxed Rust value for
511/// method dispatch and `from_value`, while exposing the active variant and
512/// its fields so the VM can pattern-match on it.
513pub struct NativeEnum {
514    pub object: Arc<NativeObject>,
515    pub variant: Symbol,
516    pub fields: Vec<(Symbol, Value)>,
517}
518
519impl NativeEnum {
520    pub fn field(&self, name: Symbol) -> Option<&Value> {
521        self.fields
522            .iter()
523            .find(|(field, _)| *field == name)
524            .map(|(_, value)| value)
525    }
526}
527
528impl fmt::Debug for NativeEnum {
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        f.debug_struct("NativeEnum")
531            .field("ty", &self.object.ty)
532            .field("variant", &self.variant)
533            .finish()
534    }
535}
536
537impl PartialEq for NativeEnum {
538    fn eq(&self, other: &Self) -> bool {
539        self.object.ty == other.object.ty
540            && self.variant == other.variant
541            && self.fields == other.fields
542    }
543}
544
545/// Named fields: a value of a Rust struct or enum converted to Xur, or a
546/// record read with a layout.
547#[derive(Debug, Clone, PartialEq)]
548pub struct Record {
549    /// The type registered for the Rust type's shape, if any, which names
550    /// it and is what written types check against.
551    pub ty: Option<NativeTypeId>,
552    /// For a value of a Rust enum, its variant, e.g. `Amd64`.
553    pub variant: Option<Symbol>,
554    pub fields: Vec<(Symbol, Value)>,
555}
556
557impl Record {
558    /// A record of no particular type.
559    pub fn new(fields: Vec<(Symbol, Value)>) -> Self {
560        Self {
561            ty: None,
562            variant: None,
563            fields,
564        }
565    }
566
567    pub fn field(&self, name: Symbol) -> Option<&Value> {
568        self.fields
569            .iter()
570            .find(|(field, _)| *field == name)
571            .map(|(_, value)| value)
572    }
573}
574
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
576pub struct Range {
577    pub start: Option<i64>,
578    pub end: Option<i64>,
579    /// Whether `end` is included, as in `a..=b`.
580    pub inclusive: bool,
581}
582
583impl Value {
584    /// Convenience: `Value::int(42)` creates `Value::Int(IntValue::I64(42))`.
585    pub fn int(v: i64) -> Self {
586        Self::Int(IntValue::I64(v))
587    }
588
589    pub fn float(v: f64) -> Self {
590        Self::Float(FloatValue::F64(v))
591    }
592
593    pub fn str(s: &str) -> Self {
594        Self::Str(s.into())
595    }
596
597    pub fn list(items: Vec<Value>) -> Self {
598        Self::List(Arc::new(Mutex::new(items)))
599    }
600
601    /// A map of `entries`, or an error if a key can't be a map key.
602    pub fn map(entries: Vec<(Value, Value)>) -> Result<Self, RuntimeError> {
603        let map = DashMap::new();
604        for (k, v) in entries {
605            map.insert(MapKey::new(k)?, v);
606        }
607        Ok(Self::Map(Arc::new(map)))
608    }
609
610    pub fn bytes(bytes: Vec<u8>) -> Self {
611        Self::Bytes(Arc::new(Mutex::new(bytes)))
612    }
613
614    pub fn tuple(items: Vec<Value>) -> Self {
615        if items.is_empty() {
616            Self::Unit
617        } else {
618            Self::Tuple(items.into())
619        }
620    }
621
622    pub fn adt(ctor: DefId, fields: Vec<Value>) -> Self {
623        Self::Adt(Arc::new(Adt { ctor, fields }))
624    }
625
626    /// How the kind of value is named in error messages.
627    pub fn kind(&self) -> &'static str {
628        match self {
629            Self::Unit => "unit",
630            Self::Bool(_) => "bool",
631            Self::Int(_) => "integer",
632            Self::Float(_) => "float",
633            Self::Str(_) => "string",
634            Self::Tuple(_) => "tuple",
635            Self::List(_) => "list",
636            Self::Map(_) => "map",
637            Self::Bytes(_) => "bytes",
638            Self::Ptr(_) => "pointer",
639            Self::Adt(_) => "struct or enum",
640            Self::Native(_) => "native object",
641            Self::NativeEnum(_) => "native enum",
642            Self::Record(_) => "record",
643            Self::Fn(_) | Self::NativeFn(_) => "function",
644            Self::Closure(_) => "closure",
645            Self::Iterator(_) => "iterator",
646            Self::Ctor(_) => "constructor",
647            Self::Module(_) => "module",
648            Self::Range(_) => "range",
649            Self::Type(_) => "type",
650        }
651    }
652}
653
654/// The kinds of built-in value that have methods, like `list.push(x)`.
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
656pub enum BuiltinType {
657    Bool,
658    Int,
659    Float,
660    Str,
661    Tuple,
662    List,
663    Map,
664    Bytes,
665    Ptr,
666    Range,
667    Record,
668    /// Every struct and enum variant defined in Xur, for methods they all
669    /// have, like `to_bytes`. Their own `impl` functions come first.
670    Struct,
671}
672
673impl fmt::Display for BuiltinType {
674    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675        f.write_str(match self {
676            Self::Bool => "bool",
677            Self::Int => "int",
678            Self::Float => "float",
679            Self::Str => "str",
680            Self::Tuple => "tuple",
681            Self::List => "list",
682            Self::Map => "map",
683            Self::Bytes => "bytes",
684            Self::Ptr => "ptr",
685            Self::Range => "range",
686            Self::Record => "record",
687            Self::Struct => "struct",
688        })
689    }
690}
691
692impl Value {
693    /// The built-in type whose methods `value.method()` looks up.
694    pub fn builtin_type(&self) -> Option<BuiltinType> {
695        Some(match self {
696            Self::Bool(_) => BuiltinType::Bool,
697            Self::Int(_) => BuiltinType::Int,
698            Self::Float(_) => BuiltinType::Float,
699            Self::Str(_) => BuiltinType::Str,
700            Self::Tuple(_) => BuiltinType::Tuple,
701            Self::List(_) => BuiltinType::List,
702            Self::Map(_) => BuiltinType::Map,
703            Self::Bytes(_) => BuiltinType::Bytes,
704            Self::Ptr(_) => BuiltinType::Ptr,
705            Self::Range(_) => BuiltinType::Range,
706            Self::Record(_) => BuiltinType::Record,
707            Self::Adt(_) => BuiltinType::Struct,
708            _ => return None,
709        })
710    }
711}
712
713/// Structural equality, as `==` sees it. Values of different kinds are
714/// never equal; in particular `1 == 1.0` is false.
715impl PartialEq for Value {
716    fn eq(&self, other: &Self) -> bool {
717        match (self, other) {
718            (Self::Unit, Self::Unit) => true,
719            (Self::Bool(a), Self::Bool(b)) => a == b,
720            (Self::Int(a), Self::Int(b)) => a == b,
721            (Self::Float(a), Self::Float(b)) => a == b,
722            (Self::Str(a), Self::Str(b)) => a == b,
723            (Self::Tuple(a), Self::Tuple(b)) => a == b,
724            (Self::List(a), Self::List(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
725            (Self::Map(a), Self::Map(b)) => {
726                Arc::ptr_eq(a, b)
727                    || (a.len() == b.len()
728                        && a.iter().all(|entry| {
729                            b.get(entry.key())
730                                .is_some_and(|v| *v.value() == *entry.value())
731                        }))
732            }
733            (Self::Bytes(a), Self::Bytes(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
734            (Self::Ptr(a), Self::Ptr(b)) => a == b,
735            (Self::Adt(a), Self::Adt(b)) => a.ctor == b.ctor && a.fields == b.fields,
736            // Native objects are compared by identity here; the interpreter
737            // compares their Rust values when the type supports it.
738            (Self::Native(a), Self::Native(b)) => Arc::ptr_eq(a, b),
739            (Self::NativeEnum(a), Self::NativeEnum(b)) => a == b,
740            (Self::Record(a), Self::Record(b)) => a == b,
741            (Self::Fn(a), Self::Fn(b)) | (Self::Ctor(a), Self::Ctor(b)) => a == b,
742            (Self::Module(a), Self::Module(b)) => a == b,
743            (Self::NativeFn(a), Self::NativeFn(b)) => a == b,
744            (Self::Range(a), Self::Range(b)) => a == b,
745            (Self::Type(a), Self::Type(b)) => a == b,
746            (Self::Closure(a), Self::Closure(b)) => Arc::ptr_eq(a, b),
747            (Self::Iterator(a), Self::Iterator(b)) => Arc::ptr_eq(a, b),
748            _ => false,
749        }
750    }
751}
752
753/// A value used as a map key: a str, int, bool, `()` or a unit enum variant.
754/// Build one with [`MapKey::new`], which refuses anything else.
755#[derive(Debug, Clone)]
756pub struct MapKey(pub Value);
757
758impl MapKey {
759    /// `value` as a key, or an error for a value that can't be one (a float,
760    /// list, map, ...).
761    pub fn new(value: Value) -> Result<Self, RuntimeError> {
762        if Self::hashable(&value) {
763            Ok(Self(value))
764        } else {
765            Err(RuntimeError::new(format!(
766                "a {} can't be a map key (use a str, int, bool or unit enum variant)",
767                value.kind()
768            )))
769        }
770    }
771
772    fn hashable(value: &Value) -> bool {
773        match value {
774            Value::Unit | Value::Bool(_) | Value::Int(_) | Value::Str(_) => true,
775            Value::Adt(adt) => adt.fields.is_empty(),
776            _ => false,
777        }
778    }
779}
780
781impl PartialEq for MapKey {
782    fn eq(&self, other: &Self) -> bool {
783        self.0 == other.0
784    }
785}
786
787impl Eq for MapKey {}
788
789impl Hash for MapKey {
790    fn hash<H: Hasher>(&self, state: &mut H) {
791        std::mem::discriminant(&self.0).hash(state);
792        match &self.0 {
793            Value::Unit => {}
794            Value::Bool(b) => b.hash(state),
795            Value::Int(i) => i.hash(state),
796            Value::Str(s) => s.hash(state),
797            Value::Adt(adt) if adt.fields.is_empty() => adt.ctor.hash(state),
798            // MapKey::new refuses these; equal values still hash alike.
799            _ => {}
800        }
801    }
802}
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807
808    #[test]
809    fn only_hashable_values_are_map_keys() {
810        assert!(MapKey::new(Value::int(1)).is_ok());
811        assert!(MapKey::new(Value::str("a")).is_ok());
812        assert!(MapKey::new(Value::float(1.5)).is_err());
813        assert!(MapKey::new(Value::list(vec![])).is_err());
814        assert!(Value::map(vec![(Value::float(1.0), Value::Unit)]).is_err());
815    }
816
817    #[test]
818    fn values_can_be_shared_between_threads() {
819        fn assert_send_sync<T: Send + Sync>() {}
820        assert_send_sync::<Value>();
821    }
822
823    #[test]
824    fn equality_is_structural_and_kind_strict() {
825        assert_eq!(
826            Value::list(vec![Value::int(1)]),
827            Value::list(vec![Value::int(1)])
828        );
829        assert_ne!(Value::int(1), Value::float(1.0));
830        assert_eq!(Value::str("a"), Value::str("a"));
831        assert_eq!(Value::tuple(vec![]), Value::Unit);
832    }
833
834    #[test]
835    fn int_value_cross_width_equality() {
836        assert_eq!(IntValue::I64(42), IntValue::U8(42));
837        assert_eq!(IntValue::U32(0), IntValue::I8(0));
838        assert_ne!(IntValue::I64(-1), IntValue::U64(u64::MAX));
839    }
840
841    #[test]
842    fn int_value_ordering() {
843        assert!(IntValue::I64(-1) < IntValue::U8(0));
844        assert!(IntValue::U64(u64::MAX) > IntValue::I64(i64::MAX));
845    }
846
847    #[test]
848    fn int_value_conversions() {
849        assert_eq!(IntValue::U64(u64::MAX).to_i64(), None);
850        assert_eq!(IntValue::U64(42).to_i64(), Some(42));
851        assert_eq!(IntValue::I64(-1).to_u64(), None);
852        assert_eq!(IntValue::U8(255).to_u64(), Some(255));
853    }
854
855    #[test]
856    fn float_value_cross_width_equality() {
857        assert_eq!(FloatValue::F32(1.0), FloatValue::F64(1.0));
858    }
859}