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::sync::{Arc, Mutex, MutexGuard, PoisonError};
13
14use xur_resolve::{DefId, NativeFnId, NativeTypeId};
15use xur_span::Symbol;
16
17/// Locks `mutex`. A panic while it was held doesn't stop the program from
18/// using the value, as Xur values have no invariants a panic could break.
19pub fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
20    mutex.lock().unwrap_or_else(PoisonError::into_inner)
21}
22
23#[derive(Debug, Clone)]
24pub enum Value {
25    /// `()`, the value of expressions that produce nothing.
26    Unit,
27    Bool(bool),
28    Int(i64),
29    Float(f64),
30    Str(Arc<str>),
31    Tuple(Arc<[Value]>),
32    List(Arc<Mutex<Vec<Value>>>),
33    /// An instance of a struct or enum variant defined in Xur.
34    Adt(Arc<Adt>),
35    /// A value of a registered Rust type, held as the Rust value itself.
36    Native(Arc<NativeObject>),
37    /// A value of an unregistered Rust struct, converted to named fields.
38    Record(Arc<Record>),
39    /// A function defined in Xur, including those in `impl` blocks.
40    Fn(DefId),
41    /// The constructor of a tuple struct or tuple variant used as a
42    /// function, as in `Some(1)` or `list.map(Some)`.
43    Ctor(DefId),
44    /// A function implemented in Rust.
45    NativeFn(NativeFnId),
46    /// A closure: code owned by the engine running it, and what it captured.
47    Closure(Arc<Closure>),
48    /// An iterator, from iterating a list or range or from a native function.
49    Iterator(Arc<ValueIter>),
50    /// A module: modules are values.
51    Module(DefId),
52    /// `a..b`, `a..=b`, `a..`, `..b` over integers.
53    Range(Range),
54}
55
56/// An instance of a struct, or of an enum variant, defined in Xur.
57#[derive(Debug, Clone)]
58pub struct Adt {
59    /// The struct or variant.
60    pub ctor: DefId,
61    pub fields: Vec<Value>,
62}
63
64/// A closure value.
65#[derive(Debug)]
66pub struct Closure {
67    /// The closure's code, in whatever form the engine running it uses.
68    pub code: Arc<dyn Any + Send + Sync>,
69    /// The values of the variables it captured when it was created.
70    pub captures: Vec<Value>,
71    /// The type arguments in effect where it was created.
72    pub type_args: Vec<String>,
73}
74
75/// A shared iterator over values.
76pub struct ValueIter(Mutex<Box<dyn Iterator<Item = Value> + Send>>);
77
78impl ValueIter {
79    pub fn new(iter: impl Iterator<Item = Value> + Send + 'static) -> Self {
80        Self(Mutex::new(Box::new(iter)))
81    }
82
83    #[allow(clippy::should_implement_trait)] // it is shared, so `&self`
84    pub fn next(&self) -> Option<Value> {
85        lock(&self.0).next()
86    }
87}
88
89impl fmt::Debug for ValueIter {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str("ValueIter")
92    }
93}
94
95/// A value of a registered Rust type. Methods registered as taking
96/// `&mut self` change it in place, and every Xur value referring to it sees
97/// the change.
98pub struct NativeObject {
99    pub ty: NativeTypeId,
100    value: Mutex<Box<dyn Any + Send>>,
101}
102
103impl NativeObject {
104    pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
105        Self {
106            ty,
107            value: Mutex::new(value),
108        }
109    }
110
111    /// Calls `f` with the Rust value, if it is a `T`.
112    pub fn with<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
113        lock(&self.value).downcast_ref().map(f)
114    }
115
116    /// Calls `f` with the Rust value mutably, if it is a `T`.
117    pub fn with_mut<T: 'static, R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
118        lock(&self.value).downcast_mut().map(f)
119    }
120
121    /// Calls `f` with the Rust value, type-erased.
122    pub fn with_any<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
123        f(lock(&self.value).as_ref())
124    }
125}
126
127impl fmt::Debug for NativeObject {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.debug_tuple("NativeObject").field(&self.ty).finish()
130    }
131}
132
133/// A value of an unregistered Rust struct, converted to named fields.
134#[derive(Debug, Clone, PartialEq)]
135pub struct Record {
136    pub fields: Vec<(Symbol, Value)>,
137}
138
139impl Record {
140    pub fn field(&self, name: Symbol) -> Option<&Value> {
141        self.fields
142            .iter()
143            .find(|(field, _)| *field == name)
144            .map(|(_, value)| value)
145    }
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub struct Range {
150    pub start: Option<i64>,
151    pub end: Option<i64>,
152    /// Whether `end` is included, as in `a..=b`.
153    pub inclusive: bool,
154}
155
156impl Value {
157    pub fn str(s: &str) -> Self {
158        Self::Str(s.into())
159    }
160
161    pub fn list(items: Vec<Value>) -> Self {
162        Self::List(Arc::new(Mutex::new(items)))
163    }
164
165    pub fn tuple(items: Vec<Value>) -> Self {
166        Self::Tuple(items.into())
167    }
168
169    pub fn adt(ctor: DefId, fields: Vec<Value>) -> Self {
170        Self::Adt(Arc::new(Adt { ctor, fields }))
171    }
172
173    /// How the kind of value is named in error messages.
174    pub fn kind(&self) -> &'static str {
175        match self {
176            Self::Unit => "unit",
177            Self::Bool(_) => "bool",
178            Self::Int(_) => "integer",
179            Self::Float(_) => "float",
180            Self::Str(_) => "string",
181            Self::Tuple(_) => "tuple",
182            Self::List(_) => "list",
183            Self::Adt(_) => "struct or enum",
184            Self::Native(_) => "native object",
185            Self::Record(_) => "record",
186            Self::Fn(_) | Self::NativeFn(_) => "function",
187            Self::Closure(_) => "closure",
188            Self::Iterator(_) => "iterator",
189            Self::Ctor(_) => "constructor",
190            Self::Module(_) => "module",
191            Self::Range(_) => "range",
192        }
193    }
194}
195
196/// The kinds of built-in value that have methods, like `list.push(x)`.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
198pub enum BuiltinType {
199    Bool,
200    Int,
201    Float,
202    Str,
203    Tuple,
204    List,
205    Range,
206}
207
208impl Value {
209    /// The built-in type whose methods `value.method()` looks up.
210    pub fn builtin_type(&self) -> Option<BuiltinType> {
211        Some(match self {
212            Self::Bool(_) => BuiltinType::Bool,
213            Self::Int(_) => BuiltinType::Int,
214            Self::Float(_) => BuiltinType::Float,
215            Self::Str(_) => BuiltinType::Str,
216            Self::Tuple(_) => BuiltinType::Tuple,
217            Self::List(_) => BuiltinType::List,
218            Self::Range(_) => BuiltinType::Range,
219            _ => return None,
220        })
221    }
222}
223
224/// Structural equality, as `==` sees it. Values of different kinds are
225/// never equal; in particular `1 == 1.0` is false.
226impl PartialEq for Value {
227    fn eq(&self, other: &Self) -> bool {
228        match (self, other) {
229            (Self::Unit, Self::Unit) => true,
230            (Self::Bool(a), Self::Bool(b)) => a == b,
231            (Self::Int(a), Self::Int(b)) => a == b,
232            (Self::Float(a), Self::Float(b)) => a == b,
233            (Self::Str(a), Self::Str(b)) => a == b,
234            (Self::Tuple(a), Self::Tuple(b)) => a == b,
235            (Self::List(a), Self::List(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
236            (Self::Adt(a), Self::Adt(b)) => a.ctor == b.ctor && a.fields == b.fields,
237            // Native objects are compared by identity here; the interpreter
238            // compares their Rust values when the type supports it.
239            (Self::Native(a), Self::Native(b)) => Arc::ptr_eq(a, b),
240            (Self::Record(a), Self::Record(b)) => a == b,
241            (Self::Fn(a), Self::Fn(b)) | (Self::Ctor(a), Self::Ctor(b)) => a == b,
242            (Self::Module(a), Self::Module(b)) => a == b,
243            (Self::NativeFn(a), Self::NativeFn(b)) => a == b,
244            (Self::Range(a), Self::Range(b)) => a == b,
245            (Self::Closure(a), Self::Closure(b)) => Arc::ptr_eq(a, b),
246            (Self::Iterator(a), Self::Iterator(b)) => Arc::ptr_eq(a, b),
247            _ => false,
248        }
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn values_can_be_shared_between_threads() {
258        fn assert_send_sync<T: Send + Sync>() {}
259        assert_send_sync::<Value>();
260    }
261
262    #[test]
263    fn equality_is_structural_and_kind_strict() {
264        assert_eq!(
265            Value::list(vec![Value::Int(1)]),
266            Value::list(vec![Value::Int(1)])
267        );
268        assert_ne!(Value::Int(1), Value::Float(1.0));
269        assert_eq!(Value::str("a"), Value::str("a"));
270        assert_ne!(Value::tuple(vec![]), Value::Unit);
271    }
272}