1use 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
17pub 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 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 Adt(Arc<Adt>),
35 Native(Arc<NativeObject>),
37 Record(Arc<Record>),
39 Fn(DefId),
41 Ctor(DefId),
44 NativeFn(NativeFnId),
46 Closure(Arc<Closure>),
48 Iterator(Arc<ValueIter>),
50 Module(DefId),
52 Range(Range),
54}
55
56#[derive(Debug, Clone)]
58pub struct Adt {
59 pub ctor: DefId,
61 pub fields: Vec<Value>,
62}
63
64#[derive(Debug)]
66pub struct Closure {
67 pub code: Arc<dyn Any + Send + Sync>,
69 pub captures: Vec<Value>,
71 pub type_args: Vec<String>,
73}
74
75pub 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)] 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
95pub 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 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 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 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#[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 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 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#[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 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
224impl 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 (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}