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 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 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 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 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 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 pub fn type_args(&self) -> &[BuiltinType] {
175 &self.type_args
176 }
177
178 pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
181 self._keep_alive.clone()
182 }
183
184 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#[derive(Debug, Clone, PartialEq)]
199pub struct Record {
200 pub ty: Option<NativeTypeId>,
203 pub variant: Option<Symbol>,
205 pub fields: Vec<(Symbol, Value)>,
206}
207
208impl Record {
209 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 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 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#[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 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 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
353impl 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 (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#[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}