1use 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
20pub 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 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 Map(Arc<DashMap<MapKey, Value>>),
38 Bytes(Arc<Mutex<Vec<u8>>>),
40 Ptr(u64),
42 Adt(Arc<Adt>),
44 Native(Arc<NativeObject>),
46 Record(Arc<Record>),
48 Fn(DefId),
50 Ctor(DefId),
53 NativeFn(NativeFnId),
55 Closure(Arc<Closure>),
57 Iterator(Arc<ValueIter>),
59 Module(DefId),
61 Range(Range),
63 Type(Box<RtType>),
65}
66
67#[derive(Debug, Clone)]
69pub struct Adt {
70 pub ctor: DefId,
72 pub fields: Vec<Value>,
73}
74
75#[derive(Debug)]
77pub struct Closure {
78 pub code: Arc<dyn Any + Send + Sync>,
80 pub captures: Mutex<Vec<Value>>,
83 pub type_args: Vec<crate::TypeRef>,
85}
86
87pub 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)] 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
107pub struct NativeObject {
111 pub ty: NativeTypeId,
112 value: Mutex<Box<dyn Any + Send>>,
113 _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 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 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 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 pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
156 self._keep_alive.clone()
157 }
158
159 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#[derive(Debug, Clone, PartialEq)]
174pub struct Record {
175 pub ty: Option<NativeTypeId>,
178 pub variant: Option<Symbol>,
180 pub fields: Vec<(Symbol, Value)>,
181}
182
183impl Record {
184 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 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 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#[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 Struct,
286}
287
288impl Value {
289 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
309impl 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 (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#[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}