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}
119
120impl NativeObject {
121    pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
122        Self {
123            ty,
124            value: Mutex::new(value),
125            _keep_alive: None,
126        }
127    }
128
129    /// A native object whose value borrows `keep_alive`, which is held as
130    /// long as the object so those borrows stay valid.
131    pub fn borrowing(
132        ty: NativeTypeId,
133        value: Box<dyn Any + Send>,
134        keep_alive: Arc<dyn Any + Send + Sync>,
135    ) -> Self {
136        Self {
137            ty,
138            value: Mutex::new(value),
139            _keep_alive: Some(keep_alive),
140        }
141    }
142
143    /// Calls `f` with the Rust value, if it is a `T`.
144    pub fn with<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
145        lock(&self.value).downcast_ref().map(f)
146    }
147
148    /// Calls `f` with the Rust value mutably, if it is a `T`.
149    pub fn with_mut<T: 'static, R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
150        lock(&self.value).downcast_mut().map(f)
151    }
152
153    /// The memory this object keeps alive for its value's borrows, to share
154    /// with a part of it parsed from the same bytes.
155    pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
156        self._keep_alive.clone()
157    }
158
159    /// Calls `f` with the Rust value, type-erased.
160    pub fn with_any<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
161        f(lock(&self.value).as_ref())
162    }
163}
164
165impl fmt::Debug for NativeObject {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_tuple("NativeObject").field(&self.ty).finish()
168    }
169}
170
171/// Named fields: a value of a Rust struct or enum converted to Xur, or a
172/// record read with a layout.
173#[derive(Debug, Clone, PartialEq)]
174pub struct Record {
175    /// The type registered for the Rust type's shape, if any, which names
176    /// it and is what written types check against.
177    pub ty: Option<NativeTypeId>,
178    /// For a value of a Rust enum, its variant, e.g. `Amd64`.
179    pub variant: Option<Symbol>,
180    pub fields: Vec<(Symbol, Value)>,
181}
182
183impl Record {
184    /// A record of no particular type.
185    pub fn new(fields: Vec<(Symbol, Value)>) -> Self {
186        Self {
187            ty: None,
188            variant: None,
189            fields,
190        }
191    }
192
193    pub fn field(&self, name: Symbol) -> Option<&Value> {
194        self.fields
195            .iter()
196            .find(|(field, _)| *field == name)
197            .map(|(_, value)| value)
198    }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub struct Range {
203    pub start: Option<i64>,
204    pub end: Option<i64>,
205    /// Whether `end` is included, as in `a..=b`.
206    pub inclusive: bool,
207}
208
209impl Value {
210    pub fn str(s: &str) -> Self {
211        Self::Str(s.into())
212    }
213
214    pub fn list(items: Vec<Value>) -> Self {
215        Self::List(Arc::new(Mutex::new(items)))
216    }
217
218    pub fn map(entries: Vec<(Value, Value)>) -> Self {
219        let map = DashMap::new();
220        for (k, v) in entries {
221            map.insert(MapKey(k), v);
222        }
223        Self::Map(Arc::new(map))
224    }
225
226    pub fn bytes(bytes: Vec<u8>) -> Self {
227        Self::Bytes(Arc::new(Mutex::new(bytes)))
228    }
229
230    pub fn tuple(items: Vec<Value>) -> Self {
231        if items.is_empty() {
232            Self::Unit
233        } else {
234            Self::Tuple(items.into())
235        }
236    }
237
238    pub fn adt(ctor: DefId, fields: Vec<Value>) -> Self {
239        Self::Adt(Arc::new(Adt { ctor, fields }))
240    }
241
242    /// How the kind of value is named in error messages.
243    pub fn kind(&self) -> &'static str {
244        match self {
245            Self::Unit => "unit",
246            Self::Bool(_) => "bool",
247            Self::Int(_) => "integer",
248            Self::Float(_) => "float",
249            Self::Str(_) => "string",
250            Self::Tuple(_) => "tuple",
251            Self::List(_) => "list",
252            Self::Map(_) => "map",
253            Self::Bytes(_) => "bytes",
254            Self::Ptr(_) => "pointer",
255            Self::Adt(_) => "struct or enum",
256            Self::Native(_) => "native object",
257            Self::Record(_) => "record",
258            Self::Fn(_) | Self::NativeFn(_) => "function",
259            Self::Closure(_) => "closure",
260            Self::Iterator(_) => "iterator",
261            Self::Ctor(_) => "constructor",
262            Self::Module(_) => "module",
263            Self::Range(_) => "range",
264            Self::Type(_) => "type",
265        }
266    }
267}
268
269/// The kinds of built-in value that have methods, like `list.push(x)`.
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
271pub enum BuiltinType {
272    Bool,
273    Int,
274    Float,
275    Str,
276    Tuple,
277    List,
278    Map,
279    Bytes,
280    Ptr,
281    Range,
282    Record,
283    /// Every struct and enum variant defined in Xur, for methods they all
284    /// have, like `to_bytes`. Their own `impl` functions come first.
285    Struct,
286}
287
288impl Value {
289    /// The built-in type whose methods `value.method()` looks up.
290    pub fn builtin_type(&self) -> Option<BuiltinType> {
291        Some(match self {
292            Self::Bool(_) => BuiltinType::Bool,
293            Self::Int(_) => BuiltinType::Int,
294            Self::Float(_) => BuiltinType::Float,
295            Self::Str(_) => BuiltinType::Str,
296            Self::Tuple(_) => BuiltinType::Tuple,
297            Self::List(_) => BuiltinType::List,
298            Self::Map(_) => BuiltinType::Map,
299            Self::Bytes(_) => BuiltinType::Bytes,
300            Self::Ptr(_) => BuiltinType::Ptr,
301            Self::Range(_) => BuiltinType::Range,
302            Self::Record(_) => BuiltinType::Record,
303            Self::Adt(_) => BuiltinType::Struct,
304            _ => return None,
305        })
306    }
307}
308
309/// Structural equality, as `==` sees it. Values of different kinds are
310/// never equal; in particular `1 == 1.0` is false.
311impl PartialEq for Value {
312    fn eq(&self, other: &Self) -> bool {
313        match (self, other) {
314            (Self::Unit, Self::Unit) => true,
315            (Self::Bool(a), Self::Bool(b)) => a == b,
316            (Self::Int(a), Self::Int(b)) => a == b,
317            (Self::Float(a), Self::Float(b)) => a == b,
318            (Self::Str(a), Self::Str(b)) => a == b,
319            (Self::Tuple(a), Self::Tuple(b)) => a == b,
320            (Self::List(a), Self::List(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
321            (Self::Map(a), Self::Map(b)) => {
322                Arc::ptr_eq(a, b)
323                    || (a.len() == b.len()
324                        && a.iter().all(|entry| {
325                            b.get(entry.key())
326                                .is_some_and(|v| *v.value() == *entry.value())
327                        }))
328            }
329            (Self::Bytes(a), Self::Bytes(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
330            (Self::Ptr(a), Self::Ptr(b)) => a == b,
331            (Self::Adt(a), Self::Adt(b)) => a.ctor == b.ctor && a.fields == b.fields,
332            // Native objects are compared by identity here; the interpreter
333            // compares their Rust values when the type supports it.
334            (Self::Native(a), Self::Native(b)) => Arc::ptr_eq(a, b),
335            (Self::Record(a), Self::Record(b)) => a == b,
336            (Self::Fn(a), Self::Fn(b)) | (Self::Ctor(a), Self::Ctor(b)) => a == b,
337            (Self::Module(a), Self::Module(b)) => a == b,
338            (Self::NativeFn(a), Self::NativeFn(b)) => a == b,
339            (Self::Range(a), Self::Range(b)) => a == b,
340            (Self::Type(a), Self::Type(b)) => a == b,
341            (Self::Closure(a), Self::Closure(b)) => Arc::ptr_eq(a, b),
342            (Self::Iterator(a), Self::Iterator(b)) => Arc::ptr_eq(a, b),
343            _ => false,
344        }
345    }
346}
347
348/// A value used as a map key. Only hashable types (str, int, bool) are
349/// accepted; unhashable ones (list, map, etc.) will panic if used as keys.
350#[derive(Debug, Clone)]
351pub struct MapKey(pub Value);
352
353impl PartialEq for MapKey {
354    fn eq(&self, other: &Self) -> bool {
355        self.0 == other.0
356    }
357}
358
359impl Eq for MapKey {}
360
361impl Hash for MapKey {
362    fn hash<H: Hasher>(&self, state: &mut H) {
363        std::mem::discriminant(&self.0).hash(state);
364        match &self.0 {
365            Value::Unit => {}
366            Value::Bool(b) => b.hash(state),
367            Value::Int(i) => i.hash(state),
368            Value::Str(s) => s.hash(state),
369            Value::Adt(adt) if adt.fields.is_empty() => adt.ctor.hash(state),
370            other => panic!("{} is not hashable", other.kind()),
371        }
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn values_can_be_shared_between_threads() {
381        fn assert_send_sync<T: Send + Sync>() {}
382        assert_send_sync::<Value>();
383    }
384
385    #[test]
386    fn equality_is_structural_and_kind_strict() {
387        assert_eq!(
388            Value::list(vec![Value::Int(1)]),
389            Value::list(vec![Value::Int(1)])
390        );
391        assert_ne!(Value::Int(1), Value::Float(1.0));
392        assert_eq!(Value::str("a"), Value::str("a"));
393        assert_eq!(Value::tuple(vec![]), Value::Unit);
394    }
395}