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. Boxed so the (rarely used,
376    /// ~40-byte) range doesn't bloat every `Value` — keeping `Value` small
377    /// makes the hot register load/store copies cheaper.
378    Range(Box<Range>),
379    /// A type used as a value: `u32`, `fn(u32) -> str`, etc.
380    Type(Box<RtType>),
381}
382
383/// An instance of a struct, or of an enum variant, defined in Xur.
384#[derive(Debug, Clone)]
385pub struct Adt {
386    /// The struct or variant.
387    pub ctor: DefId,
388    pub fields: Vec<Value>,
389}
390
391/// A closure value.
392#[derive(Debug)]
393pub struct Closure {
394    /// The closure's code, in whatever form the engine running it uses.
395    pub code: Arc<dyn Any + Send + Sync>,
396    /// The values of the variables it captured when it was created.
397    /// Wrapped in a Mutex so repeated calls can write back mutations.
398    pub captures: Mutex<Vec<Value>>,
399    /// The type arguments in effect where it was created.
400    pub type_args: Vec<crate::TypeRef>,
401}
402
403/// A shared iterator over values.
404pub struct ValueIter(Mutex<Box<dyn Iterator<Item = Value> + Send>>);
405
406impl ValueIter {
407    pub fn new(iter: impl Iterator<Item = Value> + Send + 'static) -> Self {
408        Self(Mutex::new(Box::new(iter)))
409    }
410
411    #[allow(clippy::should_implement_trait)] // it is shared, so `&self`
412    pub fn next(&self) -> Option<Value> {
413        lock(&self.0).next()
414    }
415}
416
417impl fmt::Debug for ValueIter {
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419        f.write_str("ValueIter")
420    }
421}
422
423/// A value of a registered Rust type. Methods registered as taking
424/// `&mut self` change it in place, and every Xur value referring to it sees
425/// the change.
426pub struct NativeObject {
427    pub ty: NativeTypeId,
428    value: Mutex<Box<dyn Any + Send>>,
429    /// Memory the Rust value borrows, kept alive for as long as the object:
430    /// the file bytes behind a parsed `PEFile<'static>`, for instance. The
431    /// value's `'static` references stay valid because this never moves or
432    /// drops while the value does.
433    _keep_alive: Option<Arc<dyn Any + Send + Sync>>,
434    /// Concrete type arguments for generic native types, e.g.
435    /// `[BuiltinType::Bool]` for a `Cell<bool>`.
436    type_args: Vec<BuiltinType>,
437}
438
439impl NativeObject {
440    pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
441        Self {
442            ty,
443            value: Mutex::new(value),
444            _keep_alive: None,
445            type_args: Vec::new(),
446        }
447    }
448
449    /// A native object with concrete type arguments for a generic type.
450    pub fn with_type_args(
451        ty: NativeTypeId,
452        value: Box<dyn Any + Send>,
453        type_args: Vec<BuiltinType>,
454    ) -> Self {
455        Self {
456            ty,
457            value: Mutex::new(value),
458            _keep_alive: None,
459            type_args,
460        }
461    }
462
463    /// A native object whose value borrows `keep_alive`, which is held as
464    /// long as the object so those borrows stay valid.
465    pub fn borrowing(
466        ty: NativeTypeId,
467        value: Box<dyn Any + Send>,
468        keep_alive: Arc<dyn Any + Send + Sync>,
469    ) -> Self {
470        Self {
471            ty,
472            value: Mutex::new(value),
473            _keep_alive: Some(keep_alive),
474            type_args: Vec::new(),
475        }
476    }
477
478    /// Calls `f` with the Rust value, if it is a `T`.
479    pub fn with<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
480        lock(&self.value).downcast_ref().map(f)
481    }
482
483    /// Calls `f` with the Rust value mutably, if it is a `T`.
484    pub fn with_mut<T: 'static, R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
485        lock(&self.value).downcast_mut().map(f)
486    }
487
488    /// The concrete type arguments of this object, e.g. `[Bool]` for
489    /// `Cell<bool>`. Empty for non-generic types.
490    pub fn type_args(&self) -> &[BuiltinType] {
491        &self.type_args
492    }
493
494    /// The memory this object keeps alive for its value's borrows, to share
495    /// with a part of it parsed from the same bytes.
496    pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
497        self._keep_alive.clone()
498    }
499
500    /// Calls `f` with the Rust value, type-erased.
501    pub fn with_any<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
502        f(lock(&self.value).as_ref())
503    }
504}
505
506impl fmt::Debug for NativeObject {
507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508        f.debug_tuple("NativeObject").field(&self.ty).finish()
509    }
510}
511
512/// A value of a registered Rust enum type. Keeps the boxed Rust value for
513/// method dispatch and `from_value`, while exposing the active variant and
514/// its fields so the VM can pattern-match on it.
515pub struct NativeEnum {
516    pub object: Arc<NativeObject>,
517    pub variant: Symbol,
518    pub fields: Vec<(Symbol, Value)>,
519}
520
521impl NativeEnum {
522    pub fn field(&self, name: Symbol) -> Option<&Value> {
523        self.fields
524            .iter()
525            .find(|(field, _)| *field == name)
526            .map(|(_, value)| value)
527    }
528}
529
530impl fmt::Debug for NativeEnum {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        f.debug_struct("NativeEnum")
533            .field("ty", &self.object.ty)
534            .field("variant", &self.variant)
535            .finish()
536    }
537}
538
539impl PartialEq for NativeEnum {
540    fn eq(&self, other: &Self) -> bool {
541        self.object.ty == other.object.ty
542            && self.variant == other.variant
543            && self.fields == other.fields
544    }
545}
546
547/// Named fields: a value of a Rust struct or enum converted to Xur, or a
548/// record read with a layout.
549#[derive(Debug, Clone, PartialEq)]
550pub struct Record {
551    /// The type registered for the Rust type's shape, if any, which names
552    /// it and is what written types check against.
553    pub ty: Option<NativeTypeId>,
554    /// For a value of a Rust enum, its variant, e.g. `Amd64`.
555    pub variant: Option<Symbol>,
556    pub fields: Vec<(Symbol, Value)>,
557}
558
559impl Record {
560    /// A record of no particular type.
561    pub fn new(fields: Vec<(Symbol, Value)>) -> Self {
562        Self {
563            ty: None,
564            variant: None,
565            fields,
566        }
567    }
568
569    pub fn field(&self, name: Symbol) -> Option<&Value> {
570        self.fields
571            .iter()
572            .find(|(field, _)| *field == name)
573            .map(|(_, value)| value)
574    }
575}
576
577#[derive(Debug, Clone, Copy, PartialEq, Eq)]
578pub struct Range {
579    pub start: Option<i64>,
580    pub end: Option<i64>,
581    /// Whether `end` is included, as in `a..=b`.
582    pub inclusive: bool,
583}
584
585impl Value {
586    /// Convenience: `Value::int(42)` creates `Value::Int(IntValue::I64(42))`.
587    pub fn int(v: i64) -> Self {
588        Self::Int(IntValue::I64(v))
589    }
590
591    pub fn float(v: f64) -> Self {
592        Self::Float(FloatValue::F64(v))
593    }
594
595    pub fn str(s: &str) -> Self {
596        Self::Str(s.into())
597    }
598
599    pub fn list(items: Vec<Value>) -> Self {
600        Self::List(Arc::new(Mutex::new(items)))
601    }
602
603    /// A map of `entries`, or an error if a key can't be a map key.
604    pub fn map(entries: Vec<(Value, Value)>) -> Result<Self, RuntimeError> {
605        let map = DashMap::new();
606        for (k, v) in entries {
607            map.insert(MapKey::new(k)?, v);
608        }
609        Ok(Self::Map(Arc::new(map)))
610    }
611
612    pub fn bytes(bytes: Vec<u8>) -> Self {
613        Self::Bytes(Arc::new(Mutex::new(bytes)))
614    }
615
616    pub fn tuple(items: Vec<Value>) -> Self {
617        if items.is_empty() {
618            Self::Unit
619        } else {
620            Self::Tuple(items.into())
621        }
622    }
623
624    pub fn adt(ctor: DefId, fields: Vec<Value>) -> Self {
625        Self::Adt(Arc::new(Adt { ctor, fields }))
626    }
627
628    /// How the kind of value is named in error messages.
629    pub fn kind(&self) -> &'static str {
630        match self {
631            Self::Unit => "unit",
632            Self::Bool(_) => "bool",
633            Self::Int(_) => "integer",
634            Self::Float(_) => "float",
635            Self::Str(_) => "string",
636            Self::Tuple(_) => "tuple",
637            Self::List(_) => "list",
638            Self::Map(_) => "map",
639            Self::Bytes(_) => "bytes",
640            Self::Ptr(_) => "pointer",
641            Self::Adt(_) => "struct or enum",
642            Self::Native(_) => "native object",
643            Self::NativeEnum(_) => "native enum",
644            Self::Record(_) => "record",
645            Self::Fn(_) | Self::NativeFn(_) => "function",
646            Self::Closure(_) => "closure",
647            Self::Iterator(_) => "iterator",
648            Self::Ctor(_) => "constructor",
649            Self::Module(_) => "module",
650            Self::Range(_) => "range",
651            Self::Type(_) => "type",
652        }
653    }
654}
655
656/// The kinds of built-in value that have methods, like `list.push(x)`.
657#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
658pub enum BuiltinType {
659    Bool,
660    Int,
661    Float,
662    Str,
663    Tuple,
664    List,
665    Map,
666    Bytes,
667    Ptr,
668    Range,
669    Record,
670    /// Every struct and enum variant defined in Xur, for methods they all
671    /// have, like `to_bytes`. Their own `impl` functions come first.
672    Struct,
673}
674
675impl fmt::Display for BuiltinType {
676    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677        f.write_str(match self {
678            Self::Bool => "bool",
679            Self::Int => "int",
680            Self::Float => "float",
681            Self::Str => "str",
682            Self::Tuple => "tuple",
683            Self::List => "list",
684            Self::Map => "map",
685            Self::Bytes => "bytes",
686            Self::Ptr => "ptr",
687            Self::Range => "range",
688            Self::Record => "record",
689            Self::Struct => "struct",
690        })
691    }
692}
693
694impl Value {
695    /// The built-in type whose methods `value.method()` looks up.
696    pub fn builtin_type(&self) -> Option<BuiltinType> {
697        Some(match self {
698            Self::Bool(_) => BuiltinType::Bool,
699            Self::Int(_) => BuiltinType::Int,
700            Self::Float(_) => BuiltinType::Float,
701            Self::Str(_) => BuiltinType::Str,
702            Self::Tuple(_) => BuiltinType::Tuple,
703            Self::List(_) => BuiltinType::List,
704            Self::Map(_) => BuiltinType::Map,
705            Self::Bytes(_) => BuiltinType::Bytes,
706            Self::Ptr(_) => BuiltinType::Ptr,
707            Self::Range(_) => BuiltinType::Range,
708            Self::Record(_) => BuiltinType::Record,
709            Self::Adt(_) => BuiltinType::Struct,
710            _ => return None,
711        })
712    }
713}
714
715/// Structural equality, as `==` sees it. Values of different kinds are
716/// never equal; in particular `1 == 1.0` is false.
717impl PartialEq for Value {
718    fn eq(&self, other: &Self) -> bool {
719        match (self, other) {
720            (Self::Unit, Self::Unit) => true,
721            (Self::Bool(a), Self::Bool(b)) => a == b,
722            (Self::Int(a), Self::Int(b)) => a == b,
723            (Self::Float(a), Self::Float(b)) => a == b,
724            (Self::Str(a), Self::Str(b)) => a == b,
725            (Self::Tuple(a), Self::Tuple(b)) => a == b,
726            (Self::List(a), Self::List(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
727            (Self::Map(a), Self::Map(b)) => {
728                Arc::ptr_eq(a, b)
729                    || (a.len() == b.len()
730                        && a.iter().all(|entry| {
731                            b.get(entry.key())
732                                .is_some_and(|v| *v.value() == *entry.value())
733                        }))
734            }
735            (Self::Bytes(a), Self::Bytes(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
736            (Self::Ptr(a), Self::Ptr(b)) => a == b,
737            (Self::Adt(a), Self::Adt(b)) => a.ctor == b.ctor && a.fields == b.fields,
738            // Native objects are compared by identity here; the interpreter
739            // compares their Rust values when the type supports it.
740            (Self::Native(a), Self::Native(b)) => Arc::ptr_eq(a, b),
741            (Self::NativeEnum(a), Self::NativeEnum(b)) => a == b,
742            (Self::Record(a), Self::Record(b)) => a == b,
743            (Self::Fn(a), Self::Fn(b)) | (Self::Ctor(a), Self::Ctor(b)) => a == b,
744            (Self::Module(a), Self::Module(b)) => a == b,
745            (Self::NativeFn(a), Self::NativeFn(b)) => a == b,
746            (Self::Range(a), Self::Range(b)) => a == b,
747            (Self::Type(a), Self::Type(b)) => a == b,
748            (Self::Closure(a), Self::Closure(b)) => Arc::ptr_eq(a, b),
749            (Self::Iterator(a), Self::Iterator(b)) => Arc::ptr_eq(a, b),
750            _ => false,
751        }
752    }
753}
754
755/// A value used as a map key: a str, int, bool, `()` or a unit enum variant.
756/// Build one with [`MapKey::new`], which refuses anything else.
757#[derive(Debug, Clone)]
758pub struct MapKey(pub Value);
759
760impl MapKey {
761    /// `value` as a key, or an error for a value that can't be one (a float,
762    /// list, map, ...).
763    pub fn new(value: Value) -> Result<Self, RuntimeError> {
764        if Self::hashable(&value) {
765            Ok(Self(value))
766        } else {
767            Err(RuntimeError::new(format!(
768                "a {} can't be a map key (use a str, int, bool or unit enum variant)",
769                value.kind()
770            )))
771        }
772    }
773
774    fn hashable(value: &Value) -> bool {
775        match value {
776            Value::Unit | Value::Bool(_) | Value::Int(_) | Value::Str(_) => true,
777            Value::Adt(adt) => adt.fields.is_empty(),
778            _ => false,
779        }
780    }
781}
782
783impl PartialEq for MapKey {
784    fn eq(&self, other: &Self) -> bool {
785        self.0 == other.0
786    }
787}
788
789impl Eq for MapKey {}
790
791impl Hash for MapKey {
792    fn hash<H: Hasher>(&self, state: &mut H) {
793        std::mem::discriminant(&self.0).hash(state);
794        match &self.0 {
795            Value::Unit => {}
796            Value::Bool(b) => b.hash(state),
797            Value::Int(i) => i.hash(state),
798            Value::Str(s) => s.hash(state),
799            Value::Adt(adt) if adt.fields.is_empty() => adt.ctor.hash(state),
800            // MapKey::new refuses these; equal values still hash alike.
801            _ => {}
802        }
803    }
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    #[test]
811    fn only_hashable_values_are_map_keys() {
812        assert!(MapKey::new(Value::int(1)).is_ok());
813        assert!(MapKey::new(Value::str("a")).is_ok());
814        assert!(MapKey::new(Value::float(1.5)).is_err());
815        assert!(MapKey::new(Value::list(vec![])).is_err());
816        assert!(Value::map(vec![(Value::float(1.0), Value::Unit)]).is_err());
817    }
818
819    #[test]
820    fn values_can_be_shared_between_threads() {
821        fn assert_send_sync<T: Send + Sync>() {}
822        assert_send_sync::<Value>();
823    }
824
825    #[test]
826    fn equality_is_structural_and_kind_strict() {
827        assert_eq!(
828            Value::list(vec![Value::int(1)]),
829            Value::list(vec![Value::int(1)])
830        );
831        assert_ne!(Value::int(1), Value::float(1.0));
832        assert_eq!(Value::str("a"), Value::str("a"));
833        assert_eq!(Value::tuple(vec![]), Value::Unit);
834    }
835
836    #[test]
837    fn int_value_cross_width_equality() {
838        assert_eq!(IntValue::I64(42), IntValue::U8(42));
839        assert_eq!(IntValue::U32(0), IntValue::I8(0));
840        assert_ne!(IntValue::I64(-1), IntValue::U64(u64::MAX));
841    }
842
843    #[test]
844    fn int_value_ordering() {
845        assert!(IntValue::I64(-1) < IntValue::U8(0));
846        assert!(IntValue::U64(u64::MAX) > IntValue::I64(i64::MAX));
847    }
848
849    #[test]
850    fn int_value_conversions() {
851        assert_eq!(IntValue::U64(u64::MAX).to_i64(), None);
852        assert_eq!(IntValue::U64(42).to_i64(), Some(42));
853        assert_eq!(IntValue::I64(-1).to_u64(), None);
854        assert_eq!(IntValue::U8(255).to_u64(), Some(255));
855    }
856
857    #[test]
858    fn float_value_cross_width_equality() {
859        assert_eq!(FloatValue::F32(1.0), FloatValue::F64(1.0));
860    }
861
862    #[test]
863    fn value_stays_small() {
864        // `Value` is copied on every register load/store in the VM, so it must
865        // stay compact. `Range` is boxed (rather than inlined) specifically to
866        // keep a rarely-used ~40-byte variant from bloating every `Value`.
867        assert!(
868            size_of::<Value>() <= 24,
869            "Value grew to {} bytes — did a large variant get inlined?",
870            size_of::<Value>()
871        );
872    }
873}