use std::any::Any;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use dashmap::DashMap;
use xur_resolve::{DefId, NativeFnId, NativeTypeId, RtType};
use xur_span::Symbol;
pub fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Debug, Clone)]
pub enum Value {
Unit,
Bool(bool),
Int(i64),
Float(f64),
Str(Arc<str>),
Tuple(Arc<[Value]>),
List(Arc<Mutex<Vec<Value>>>),
Map(Arc<DashMap<MapKey, Value>>),
Bytes(Arc<Mutex<Vec<u8>>>),
Ptr(u64),
Adt(Arc<Adt>),
Native(Arc<NativeObject>),
Record(Arc<Record>),
Fn(DefId),
Ctor(DefId),
NativeFn(NativeFnId),
Closure(Arc<Closure>),
Iterator(Arc<ValueIter>),
Module(DefId),
Range(Range),
Type(Box<RtType>),
}
#[derive(Debug, Clone)]
pub struct Adt {
pub ctor: DefId,
pub fields: Vec<Value>,
}
#[derive(Debug)]
pub struct Closure {
pub code: Arc<dyn Any + Send + Sync>,
pub captures: Mutex<Vec<Value>>,
pub type_args: Vec<crate::TypeRef>,
}
pub struct ValueIter(Mutex<Box<dyn Iterator<Item = Value> + Send>>);
impl ValueIter {
pub fn new(iter: impl Iterator<Item = Value> + Send + 'static) -> Self {
Self(Mutex::new(Box::new(iter)))
}
#[allow(clippy::should_implement_trait)] pub fn next(&self) -> Option<Value> {
lock(&self.0).next()
}
}
impl fmt::Debug for ValueIter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ValueIter")
}
}
pub struct NativeObject {
pub ty: NativeTypeId,
value: Mutex<Box<dyn Any + Send>>,
_keep_alive: Option<Arc<dyn Any + Send + Sync>>,
}
impl NativeObject {
pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
Self {
ty,
value: Mutex::new(value),
_keep_alive: None,
}
}
pub fn borrowing(
ty: NativeTypeId,
value: Box<dyn Any + Send>,
keep_alive: Arc<dyn Any + Send + Sync>,
) -> Self {
Self {
ty,
value: Mutex::new(value),
_keep_alive: Some(keep_alive),
}
}
pub fn with<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
lock(&self.value).downcast_ref().map(f)
}
pub fn with_mut<T: 'static, R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
lock(&self.value).downcast_mut().map(f)
}
pub fn keep_alive(&self) -> Option<Arc<dyn Any + Send + Sync>> {
self._keep_alive.clone()
}
pub fn with_any<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
f(lock(&self.value).as_ref())
}
}
impl fmt::Debug for NativeObject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("NativeObject").field(&self.ty).finish()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Record {
pub ty: Option<NativeTypeId>,
pub variant: Option<Symbol>,
pub fields: Vec<(Symbol, Value)>,
}
impl Record {
pub fn new(fields: Vec<(Symbol, Value)>) -> Self {
Self {
ty: None,
variant: None,
fields,
}
}
pub fn field(&self, name: Symbol) -> Option<&Value> {
self.fields
.iter()
.find(|(field, _)| *field == name)
.map(|(_, value)| value)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Range {
pub start: Option<i64>,
pub end: Option<i64>,
pub inclusive: bool,
}
impl Value {
pub fn str(s: &str) -> Self {
Self::Str(s.into())
}
pub fn list(items: Vec<Value>) -> Self {
Self::List(Arc::new(Mutex::new(items)))
}
pub fn map(entries: Vec<(Value, Value)>) -> Self {
let map = DashMap::new();
for (k, v) in entries {
map.insert(MapKey(k), v);
}
Self::Map(Arc::new(map))
}
pub fn bytes(bytes: Vec<u8>) -> Self {
Self::Bytes(Arc::new(Mutex::new(bytes)))
}
pub fn tuple(items: Vec<Value>) -> Self {
if items.is_empty() {
Self::Unit
} else {
Self::Tuple(items.into())
}
}
pub fn adt(ctor: DefId, fields: Vec<Value>) -> Self {
Self::Adt(Arc::new(Adt { ctor, fields }))
}
pub fn kind(&self) -> &'static str {
match self {
Self::Unit => "unit",
Self::Bool(_) => "bool",
Self::Int(_) => "integer",
Self::Float(_) => "float",
Self::Str(_) => "string",
Self::Tuple(_) => "tuple",
Self::List(_) => "list",
Self::Map(_) => "map",
Self::Bytes(_) => "bytes",
Self::Ptr(_) => "pointer",
Self::Adt(_) => "struct or enum",
Self::Native(_) => "native object",
Self::Record(_) => "record",
Self::Fn(_) | Self::NativeFn(_) => "function",
Self::Closure(_) => "closure",
Self::Iterator(_) => "iterator",
Self::Ctor(_) => "constructor",
Self::Module(_) => "module",
Self::Range(_) => "range",
Self::Type(_) => "type",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinType {
Bool,
Int,
Float,
Str,
Tuple,
List,
Map,
Bytes,
Ptr,
Range,
Record,
Struct,
}
impl Value {
pub fn builtin_type(&self) -> Option<BuiltinType> {
Some(match self {
Self::Bool(_) => BuiltinType::Bool,
Self::Int(_) => BuiltinType::Int,
Self::Float(_) => BuiltinType::Float,
Self::Str(_) => BuiltinType::Str,
Self::Tuple(_) => BuiltinType::Tuple,
Self::List(_) => BuiltinType::List,
Self::Map(_) => BuiltinType::Map,
Self::Bytes(_) => BuiltinType::Bytes,
Self::Ptr(_) => BuiltinType::Ptr,
Self::Range(_) => BuiltinType::Range,
Self::Record(_) => BuiltinType::Record,
Self::Adt(_) => BuiltinType::Struct,
_ => return None,
})
}
}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Unit, Self::Unit) => true,
(Self::Bool(a), Self::Bool(b)) => a == b,
(Self::Int(a), Self::Int(b)) => a == b,
(Self::Float(a), Self::Float(b)) => a == b,
(Self::Str(a), Self::Str(b)) => a == b,
(Self::Tuple(a), Self::Tuple(b)) => a == b,
(Self::List(a), Self::List(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
(Self::Map(a), Self::Map(b)) => {
Arc::ptr_eq(a, b)
|| (a.len() == b.len()
&& a.iter().all(|entry| {
b.get(entry.key())
.is_some_and(|v| *v.value() == *entry.value())
}))
}
(Self::Bytes(a), Self::Bytes(b)) => Arc::ptr_eq(a, b) || *lock(a) == *lock(b),
(Self::Ptr(a), Self::Ptr(b)) => a == b,
(Self::Adt(a), Self::Adt(b)) => a.ctor == b.ctor && a.fields == b.fields,
(Self::Native(a), Self::Native(b)) => Arc::ptr_eq(a, b),
(Self::Record(a), Self::Record(b)) => a == b,
(Self::Fn(a), Self::Fn(b)) | (Self::Ctor(a), Self::Ctor(b)) => a == b,
(Self::Module(a), Self::Module(b)) => a == b,
(Self::NativeFn(a), Self::NativeFn(b)) => a == b,
(Self::Range(a), Self::Range(b)) => a == b,
(Self::Type(a), Self::Type(b)) => a == b,
(Self::Closure(a), Self::Closure(b)) => Arc::ptr_eq(a, b),
(Self::Iterator(a), Self::Iterator(b)) => Arc::ptr_eq(a, b),
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct MapKey(pub Value);
impl PartialEq for MapKey {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for MapKey {}
impl Hash for MapKey {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(&self.0).hash(state);
match &self.0 {
Value::Unit => {}
Value::Bool(b) => b.hash(state),
Value::Int(i) => i.hash(state),
Value::Str(s) => s.hash(state),
Value::Adt(adt) if adt.fields.is_empty() => adt.ctor.hash(state),
other => panic!("{} is not hashable", other.kind()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn values_can_be_shared_between_threads() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Value>();
}
#[test]
fn equality_is_structural_and_kind_strict() {
assert_eq!(
Value::list(vec![Value::Int(1)]),
Value::list(vec![Value::Int(1)])
);
assert_ne!(Value::Int(1), Value::Float(1.0));
assert_eq!(Value::str("a"), Value::str("a"));
assert_eq!(Value::tuple(vec![]), Value::Unit);
}
}