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