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 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
20/// Locks `mutex`. A panic while it was held doesn't stop the program from
21/// using the value, as Xur values have no invariants a panic could break.
22pub fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
23    mutex.lock().unwrap_or_else(PoisonError::into_inner)
24}
25
26#[derive(Debug, Clone)]
27pub enum Value {
28    /// `()`, the value of expressions that produce nothing.
29    Unit,
30    Bool(bool),
31    Int(i64),
32    Float(f64),
33    Str(Arc<str>),
34    Tuple(Arc<[Value]>),
35    List(Arc<Mutex<Vec<Value>>>),
36    /// `#{k: v}`, shared and mutable like a list.
37    Map(Arc<DashMap<MapKey, Value>>),
38    /// A byte buffer, shared and mutable like a list (Python's `bytearray`).
39    Bytes(Arc<Mutex<Vec<u8>>>),
40    /// A raw pointer (address), for memory-level operations.
41    Ptr(u64),
42    /// An instance of a struct or enum variant defined in Xur.
43    Adt(Arc<Adt>),
44    /// A value of a registered Rust type, held as the Rust value itself.
45    Native(Arc<NativeObject>),
46    /// A value of an unregistered Rust struct, converted to named fields.
47    Record(Arc<Record>),
48    /// A function defined in Xur, including those in `impl` blocks.
49    Fn(DefId),
50    /// The constructor of a tuple struct or tuple variant used as a
51    /// function, as in `Some(1)` or `list.map(Some)`.
52    Ctor(DefId),
53    /// A function implemented in Rust.
54    NativeFn(NativeFnId),
55    /// A closure: code owned by the engine running it, and what it captured.
56    Closure(Arc<Closure>),
57    /// An iterator, from iterating a list or range or from a native function.
58    Iterator(Arc<ValueIter>),
59    /// A module: modules are values.
60    Module(DefId),
61    /// `a..b`, `a..=b`, `a..`, `..b` over integers.
62    Range(Range),
63    /// A type used as a value: `u32`, `fn(u32) -> str`, etc.
64    Type(Box<RtType>),
65}
66
67/// An instance of a struct, or of an enum variant, defined in Xur.
68#[derive(Debug, Clone)]
69pub struct Adt {
70    /// The struct or variant.
71    pub ctor: DefId,
72    pub fields: Vec<Value>,
73}
74
75/// A closure value.
76#[derive(Debug)]
77pub struct Closure {
78    /// The closure's code, in whatever form the engine running it uses.
79    pub code: Arc<dyn Any + Send + Sync>,
80    /// The values of the variables it captured when it was created.
81    /// Wrapped in a Mutex so repeated calls can write back mutations.
82    pub captures: Mutex<Vec<Value>>,
83    /// The type arguments in effect where it was created.
84    pub type_args: Vec<crate::TypeRef>,
85}
86
87/// A shared iterator over values.
88pub struct ValueIter(Mutex<Box<dyn Iterator<Item = Value> + Send>>);
89
90impl ValueIter {
91    pub fn new(iter: impl Iterator<Item = Value> + Send + 'static) -> Self {
92        Self(Mutex::new(Box::new(iter)))
93    }
94
95    #[allow(clippy::should_implement_trait)] // it is shared, so `&self`
96    pub fn next(&self) -> Option<Value> {
97        lock(&self.0).next()
98    }
99}
100
101impl fmt::Debug for ValueIter {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str("ValueIter")
104    }
105}
106
107/// A value of a registered Rust type. Methods registered as taking
108/// `&mut self` change it in place, and every Xur value referring to it sees
109/// the change.
110pub struct NativeObject {
111    pub ty: NativeTypeId,
112    value: Mutex<Box<dyn Any + Send>>,
113    /// Memory the Rust value borrows, kept alive for as long as the object:
114    /// the file bytes behind a parsed `PEFile<'static>`, for instance. The
115    /// value's `'static` references stay valid because this never moves or
116    /// drops while the value does.
117    _keep_alive: Option<Arc<dyn Any + Send + Sync>>,
118    /// Concrete type arguments for generic native types, e.g.
119    /// `[BuiltinType::Bool]` for a `Cell<bool>`.
120    type_args: Vec<BuiltinType>,
121}
122
123impl NativeObject {
124    pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
125        Self {
126            ty,
127            value: Mutex::new(value),
128            _keep_alive: None,
129            type_args: Vec::new(),
130        }
131    }
132
133    /// A native object with concrete type arguments for a generic type.
134    pub fn with_type_args(
135        ty: NativeTypeId,
136        value: Box<dyn Any + Send>,
137        type_args: Vec<BuiltinType>,
138    ) -> Self {
139        Self {
140            ty,
141            value: Mutex::new(value),
142            _keep_alive: None,
143            type_args,
144        }
145    }
146
147    /// A native object whose value borrows `keep_alive`, which is held as
148    /// long as the object so those borrows stay valid.
149    pub fn borrowing(
150        ty: NativeTypeId,
151        value: Box<dyn Any + Send>,
152        keep_alive: Arc<dyn Any + Send + Sync>,
153    ) -> Self {
154        Self {
155            ty,
156            value: Mutex::new(value),
157            _keep_alive: Some(keep_alive),
158            type_args: Vec::new(),
159        }
160    }
161
162    /// Calls `f` with the Rust value, if it is a `T`.
163    pub fn with<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
164        lock(&self.value).downcast_ref().map(f)
165    }
166
167    /// Calls `f` with the Rust value mutably, if it is a `T`.
168    pub fn with_mut<T: 'static, R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
169        lock(&self.value).downcast_mut().map(f)
170    }
171
172    /// The concrete type arguments of this object, e.g. `[Bool]` for
173    /// `Cell<bool>`. Empty for non-generic types.
174    pub fn type_args(&self) -> &[BuiltinType] {
175        &self.type_args
176    }
177
178    /// The memory this object keeps alive for its value's borrows, to share
179    /// with a part of it parsed from the same bytes.
180    pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
181        self._keep_alive.clone()
182    }
183
184    /// Calls `f` with the Rust value, type-erased.
185    pub fn with_any<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
186        f(lock(&self.value).as_ref())
187    }
188}
189
190impl fmt::Debug for NativeObject {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        f.debug_tuple("NativeObject").field(&self.ty).finish()
193    }
194}
195
196/// Named fields: a value of a Rust struct or enum converted to Xur, or a
197/// record read with a layout.
198#[derive(Debug, Clone, PartialEq)]
199pub struct Record {
200    /// The type registered for the Rust type's shape, if any, which names
201    /// it and is what written types check against.
202    pub ty: Option<NativeTypeId>,
203    /// For a value of a Rust enum, its variant, e.g. `Amd64`.
204    pub variant: Option<Symbol>,
205    pub fields: Vec<(Symbol, Value)>,
206}
207
208impl Record {
209    /// A record of no particular type.
210    pub fn new(fields: Vec<(Symbol, Value)>) -> Self {
211        Self {
212            ty: None,
213            variant: None,
214            fields,
215        }
216    }
217
218    pub fn field(&self, name: Symbol) -> Option<&Value> {
219        self.fields
220            .iter()
221            .find(|(field, _)| *field == name)
222            .map(|(_, value)| value)
223    }
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct Range {
228    pub start: Option<i64>,
229    pub end: Option<i64>,
230    /// Whether `end` is included, as in `a..=b`.
231    pub inclusive: bool,
232}
233
234impl Value {
235    pub fn str(s: &str) -> Self {
236        Self::Str(s.into())
237    }
238
239    pub fn list(items: Vec<Value>) -> Self {
240        Self::List(Arc::new(Mutex::new(items)))
241    }
242
243    pub fn map(entries: Vec<(Value, Value)>) -> Self {
244        let map = DashMap::new();
245        for (k, v) in entries {
246            map.insert(MapKey(k), v);
247        }
248        Self::Map(Arc::new(map))
249    }
250
251    pub fn bytes(bytes: Vec<u8>) -> Self {
252        Self::Bytes(Arc::new(Mutex::new(bytes)))
253    }
254
255    pub fn tuple(items: Vec<Value>) -> Self {
256        if items.is_empty() {
257            Self::Unit
258        } else {
259            Self::Tuple(items.into())
260        }
261    }
262
263    pub fn adt(ctor: DefId, fields: Vec<Value>) -> Self {
264        Self::Adt(Arc::new(Adt { ctor, fields }))
265    }
266
267    /// How the kind of value is named in error messages.
268    pub fn kind(&self) -> &'static str {
269        match self {
270            Self::Unit => "unit",
271            Self::Bool(_) => "bool",
272            Self::Int(_) => "integer",
273            Self::Float(_) => "float",
274            Self::Str(_) => "string",
275            Self::Tuple(_) => "tuple",
276            Self::List(_) => "list",
277            Self::Map(_) => "map",
278            Self::Bytes(_) => "bytes",
279            Self::Ptr(_) => "pointer",
280            Self::Adt(_) => "struct or enum",
281            Self::Native(_) => "native object",
282            Self::Record(_) => "record",
283            Self::Fn(_) | Self::NativeFn(_) => "function",
284            Self::Closure(_) => "closure",
285            Self::Iterator(_) => "iterator",
286            Self::Ctor(_) => "constructor",
287            Self::Module(_) => "module",
288            Self::Range(_) => "range",
289            Self::Type(_) => "type",
290        }
291    }
292}
293
294/// The kinds of built-in value that have methods, like `list.push(x)`.
295#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
296pub enum BuiltinType {
297    Bool,
298    Int,
299    Float,
300    Str,
301    Tuple,
302    List,
303    Map,
304    Bytes,
305    Ptr,
306    Range,
307    Record,
308    /// Every struct and enum variant defined in Xur, for methods they all
309    /// have, like `to_bytes`. Their own `impl` functions come first.
310    Struct,
311}
312
313impl fmt::Display for BuiltinType {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        f.write_str(match self {
316            Self::Bool => "bool",
317            Self::Int => "int",
318            Self::Float => "float",
319            Self::Str => "str",
320            Self::Tuple => "tuple",
321            Self::List => "list",
322            Self::Map => "map",
323            Self::Bytes => "bytes",
324            Self::Ptr => "ptr",
325            Self::Range => "range",
326            Self::Record => "record",
327            Self::Struct => "struct",
328        })
329    }
330}
331
332impl Value {
333    /// The built-in type whose methods `value.method()` looks up.
334    pub fn builtin_type(&self) -> Option<BuiltinType> {
335        Some(match self {
336            Self::Bool(_) => BuiltinType::Bool,
337            Self::Int(_) => BuiltinType::Int,
338            Self::Float(_) => BuiltinType::Float,
339            Self::Str(_) => BuiltinType::Str,
340            Self::Tuple(_) => BuiltinType::Tuple,
341            Self::List(_) => BuiltinType::List,
342            Self::Map(_) => BuiltinType::Map,
343            Self::Bytes(_) => BuiltinType::Bytes,
344            Self::Ptr(_) => BuiltinType::Ptr,
345            Self::Range(_) => BuiltinType::Range,
346            Self::Record(_) => BuiltinType::Record,
347            Self::Adt(_) => BuiltinType::Struct,
348            _ => return None,
349        })
350    }
351}
352
353/// Structural equality, as `==` sees it. Values of different kinds are
354/// never equal; in particular `1 == 1.0` is false.
355impl PartialEq for Value {
356    fn eq(&self, other: &Self) -> bool {
357        match (self, other) {
358            (Self::Unit, Self::Unit) => true,
359            (Self::Bool(a), Self::Bool(b)) => a == b,
360            (Self::Int(a), Self::Int(b)) => a == b,
361            (Self::Float(a), Self::Float(b)) => a == b,
362            (Self::Str(a), Self::Str(b)) => a == b,
363            (Self::Tuple(a), Self::Tuple(b)) => a == b,
364            (Self::List(a), Self::List(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
365            (Self::Map(a), Self::Map(b)) => {
366                Arc::ptr_eq(a, b)
367                    || (a.len() == b.len()
368                        && a.iter().all(|entry| {
369                            b.get(entry.key())
370                                .is_some_and(|v| *v.value() == *entry.value())
371                        }))
372            }
373            (Self::Bytes(a), Self::Bytes(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
374            (Self::Ptr(a), Self::Ptr(b)) => a == b,
375            (Self::Adt(a), Self::Adt(b)) => a.ctor == b.ctor && a.fields == b.fields,
376            // Native objects are compared by identity here; the interpreter
377            // compares their Rust values when the type supports it.
378            (Self::Native(a), Self::Native(b)) => Arc::ptr_eq(a, b),
379            (Self::Record(a), Self::Record(b)) => a == b,
380            (Self::Fn(a), Self::Fn(b)) | (Self::Ctor(a), Self::Ctor(b)) => a == b,
381            (Self::Module(a), Self::Module(b)) => a == b,
382            (Self::NativeFn(a), Self::NativeFn(b)) => a == b,
383            (Self::Range(a), Self::Range(b)) => a == b,
384            (Self::Type(a), Self::Type(b)) => a == b,
385            (Self::Closure(a), Self::Closure(b)) => Arc::ptr_eq(a, b),
386            (Self::Iterator(a), Self::Iterator(b)) => Arc::ptr_eq(a, b),
387            _ => false,
388        }
389    }
390}
391
392/// A value used as a map key. Only hashable types (str, int, bool) are
393/// accepted; unhashable ones (list, map, etc.) will panic if used as keys.
394#[derive(Debug, Clone)]
395pub struct MapKey(pub Value);
396
397impl PartialEq for MapKey {
398    fn eq(&self, other: &Self) -> bool {
399        self.0 == other.0
400    }
401}
402
403impl Eq for MapKey {}
404
405impl Hash for MapKey {
406    fn hash<H: Hasher>(&self, state: &mut H) {
407        std::mem::discriminant(&self.0).hash(state);
408        match &self.0 {
409            Value::Unit => {}
410            Value::Bool(b) => b.hash(state),
411            Value::Int(i) => i.hash(state),
412            Value::Str(s) => s.hash(state),
413            Value::Adt(adt) if adt.fields.is_empty() => adt.ctor.hash(state),
414            other => panic!("{} is not hashable", other.kind()),
415        }
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    #[test]
424    fn values_can_be_shared_between_threads() {
425        fn assert_send_sync<T: Send + Sync>() {}
426        assert_send_sync::<Value>();
427    }
428
429    #[test]
430    fn equality_is_structural_and_kind_strict() {
431        assert_eq!(
432            Value::list(vec![Value::Int(1)]),
433            Value::list(vec![Value::Int(1)])
434        );
435        assert_ne!(Value::Int(1), Value::Float(1.0));
436        assert_eq!(Value::str("a"), Value::str("a"));
437        assert_eq!(Value::tuple(vec![]), Value::Unit);
438    }
439}