use crate::RuntimeError;
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)
}
pub fn with_pair<T: ?Sized, R>(
a: &Arc<Mutex<T>>,
b: &Arc<Mutex<T>>,
f: impl FnOnce(&T, &T) -> R,
) -> R {
if Arc::ptr_eq(a, b) {
let g = lock(a);
f(&g, &g)
} else {
let ga = lock(a);
let gb = lock(b);
f(&ga, &gb)
}
}
#[derive(Debug, Clone, Copy)]
pub enum IntValue {
I8(i8),
I16(i16),
I32(i32),
I64(i64),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
}
impl IntValue {
pub fn to_i128(self) -> i128 {
match self {
Self::I8(v) => v as i128,
Self::I16(v) => v as i128,
Self::I32(v) => v as i128,
Self::I64(v) => v as i128,
Self::U8(v) => v as i128,
Self::U16(v) => v as i128,
Self::U32(v) => v as i128,
Self::U64(v) => v as i128,
}
}
pub fn to_i64(self) -> Option<i64> {
i64::try_from(self.to_i128()).ok()
}
pub fn to_u64(self) -> Option<u64> {
u64::try_from(self.to_i128()).ok()
}
pub fn to_u32(self) -> Option<u32> {
u32::try_from(self.to_i128()).ok()
}
pub fn to_usize(self) -> Option<usize> {
usize::try_from(self.to_i128()).ok()
}
pub fn as_f64(self) -> f64 {
self.to_i128() as f64
}
pub fn is_signed(self) -> bool {
matches!(
self,
Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_)
)
}
pub fn is_zero(self) -> bool {
self.to_i128() == 0
}
pub fn width(self) -> u8 {
match self {
Self::I8(_) | Self::U8(_) => 1,
Self::I16(_) | Self::U16(_) => 2,
Self::I32(_) | Self::U32(_) => 4,
Self::I64(_) | Self::U64(_) => 8,
}
}
pub fn promote_type(a: Self, b: Self) -> (bool, u8) {
(a.is_signed() || b.is_signed(), a.width().max(b.width()))
}
pub fn wrap(value: i128, signed: bool, width: u8) -> Self {
match (signed, width) {
(true, 1) => Self::I8(value as i8),
(true, 2) => Self::I16(value as i16),
(true, 4) => Self::I32(value as i32),
(true, _) => Self::I64(value as i64),
(false, 1) => Self::U8(value as u8),
(false, 2) => Self::U16(value as u16),
(false, 4) => Self::U32(value as u32),
(false, _) => Self::U64(value as u64),
}
}
pub fn wrapping_neg(self) -> Self {
Self::wrap(self.to_i128().wrapping_neg(), true, self.width())
}
pub fn rt_type(self) -> RtType {
let (name, min, max) = match self {
Self::I8(_) => ("i8", i8::MIN as i128, i8::MAX as i128),
Self::I16(_) => ("i16", i16::MIN as i128, i16::MAX as i128),
Self::I32(_) => ("i32", i32::MIN as i128, i32::MAX as i128),
Self::I64(_) => ("i64", i64::MIN as i128, i64::MAX as i128),
Self::U8(_) => ("u8", 0, u8::MAX as i128),
Self::U16(_) => ("u16", 0, u16::MAX as i128),
Self::U32(_) => ("u32", 0, u32::MAX as i128),
Self::U64(_) => ("u64", 0, u64::MAX as i128),
};
RtType::Int { name, min, max }
}
pub fn bit_not(self) -> Self {
match self {
Self::I8(v) => Self::I8(!v),
Self::I16(v) => Self::I16(!v),
Self::I32(v) => Self::I32(!v),
Self::I64(v) => Self::I64(!v),
Self::U8(v) => Self::U8(!v),
Self::U16(v) => Self::U16(!v),
Self::U32(v) => Self::U32(!v),
Self::U64(v) => Self::U64(!v),
}
}
}
impl PartialEq for IntValue {
fn eq(&self, other: &Self) -> bool {
self.to_i128() == other.to_i128()
}
}
impl Eq for IntValue {}
impl PartialOrd for IntValue {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for IntValue {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.to_i128().cmp(&other.to_i128())
}
}
impl Hash for IntValue {
fn hash<H: Hasher>(&self, state: &mut H) {
self.to_i128().hash(state);
}
}
impl fmt::Display for IntValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::I8(v) => write!(f, "{v}"),
Self::I16(v) => write!(f, "{v}"),
Self::I32(v) => write!(f, "{v}"),
Self::I64(v) => write!(f, "{v}"),
Self::U8(v) => write!(f, "{v}"),
Self::U16(v) => write!(f, "{v}"),
Self::U32(v) => write!(f, "{v}"),
Self::U64(v) => write!(f, "{v}"),
}
}
}
impl From<i8> for IntValue {
fn from(v: i8) -> Self {
Self::I8(v)
}
}
impl From<i16> for IntValue {
fn from(v: i16) -> Self {
Self::I16(v)
}
}
impl From<i32> for IntValue {
fn from(v: i32) -> Self {
Self::I32(v)
}
}
impl From<i64> for IntValue {
fn from(v: i64) -> Self {
Self::I64(v)
}
}
impl From<u8> for IntValue {
fn from(v: u8) -> Self {
Self::U8(v)
}
}
impl From<u16> for IntValue {
fn from(v: u16) -> Self {
Self::U16(v)
}
}
impl From<u32> for IntValue {
fn from(v: u32) -> Self {
Self::U32(v)
}
}
impl From<u64> for IntValue {
fn from(v: u64) -> Self {
Self::U64(v)
}
}
impl From<usize> for IntValue {
fn from(v: usize) -> Self {
Self::U64(v as u64)
}
}
impl From<bool> for IntValue {
fn from(v: bool) -> Self {
Self::U8(v as u8)
}
}
#[derive(Debug, Clone, Copy)]
pub enum FloatValue {
F32(f32),
F64(f64),
}
impl FloatValue {
pub fn as_f64(self) -> f64 {
match self {
Self::F32(v) => v as f64,
Self::F64(v) => v,
}
}
pub fn as_f32(self) -> f32 {
match self {
Self::F32(v) => v,
Self::F64(v) => v as f32,
}
}
pub fn negate(self) -> Self {
match self {
Self::F32(v) => Self::F32(-v),
Self::F64(v) => Self::F64(-v),
}
}
pub fn width(self) -> u8 {
match self {
Self::F32(_) => 4,
Self::F64(_) => 8,
}
}
pub fn rt_type(self) -> RtType {
RtType::Float {
name: match self {
Self::F32(_) => "f32",
Self::F64(_) => "f64",
},
}
}
}
impl PartialEq for FloatValue {
fn eq(&self, other: &Self) -> bool {
self.as_f64() == other.as_f64()
}
}
impl fmt::Display for FloatValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::F32(v) => write!(f, "{v}"),
Self::F64(v) => write!(f, "{v}"),
}
}
}
impl From<f32> for FloatValue {
fn from(v: f32) -> Self {
Self::F32(v)
}
}
impl From<f64> for FloatValue {
fn from(v: f64) -> Self {
Self::F64(v)
}
}
#[derive(Debug, Clone)]
pub enum Value {
Unit,
Bool(bool),
Int(IntValue),
Float(FloatValue),
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>),
NativeEnum(Arc<NativeEnum>),
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>>,
type_args: Vec<BuiltinType>,
}
impl NativeObject {
pub fn new(ty: NativeTypeId, value: Box<dyn Any + Send>) -> Self {
Self {
ty,
value: Mutex::new(value),
_keep_alive: None,
type_args: Vec::new(),
}
}
pub fn with_type_args(
ty: NativeTypeId,
value: Box<dyn Any + Send>,
type_args: Vec<BuiltinType>,
) -> Self {
Self {
ty,
value: Mutex::new(value),
_keep_alive: None,
type_args,
}
}
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),
type_args: Vec::new(),
}
}
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 type_args(&self) -> &[BuiltinType] {
&self.type_args
}
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()
}
}
pub struct NativeEnum {
pub object: Arc<NativeObject>,
pub variant: Symbol,
pub fields: Vec<(Symbol, Value)>,
}
impl NativeEnum {
pub fn field(&self, name: Symbol) -> Option<&Value> {
self.fields
.iter()
.find(|(field, _)| *field == name)
.map(|(_, value)| value)
}
}
impl fmt::Debug for NativeEnum {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NativeEnum")
.field("ty", &self.object.ty)
.field("variant", &self.variant)
.finish()
}
}
impl PartialEq for NativeEnum {
fn eq(&self, other: &Self) -> bool {
self.object.ty == other.object.ty
&& self.variant == other.variant
&& self.fields == other.fields
}
}
#[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 int(v: i64) -> Self {
Self::Int(IntValue::I64(v))
}
pub fn float(v: f64) -> Self {
Self::Float(FloatValue::F64(v))
}
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)>) -> Result<Self, RuntimeError> {
let map = DashMap::new();
for (k, v) in entries {
map.insert(MapKey::new(k)?, v);
}
Ok(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::NativeEnum(_) => "native enum",
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 fmt::Display for BuiltinType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Bool => "bool",
Self::Int => "int",
Self::Float => "float",
Self::Str => "str",
Self::Tuple => "tuple",
Self::List => "list",
Self::Map => "map",
Self::Bytes => "bytes",
Self::Ptr => "ptr",
Self::Range => "range",
Self::Record => "record",
Self::Struct => "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::NativeEnum(a), Self::NativeEnum(b)) => 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 MapKey {
pub fn new(value: Value) -> Result<Self, RuntimeError> {
if Self::hashable(&value) {
Ok(Self(value))
} else {
Err(RuntimeError::new(format!(
"a {} can't be a map key (use a str, int, bool or unit enum variant)",
value.kind()
)))
}
}
fn hashable(value: &Value) -> bool {
match value {
Value::Unit | Value::Bool(_) | Value::Int(_) | Value::Str(_) => true,
Value::Adt(adt) => adt.fields.is_empty(),
_ => false,
}
}
}
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),
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_hashable_values_are_map_keys() {
assert!(MapKey::new(Value::int(1)).is_ok());
assert!(MapKey::new(Value::str("a")).is_ok());
assert!(MapKey::new(Value::float(1.5)).is_err());
assert!(MapKey::new(Value::list(vec![])).is_err());
assert!(Value::map(vec![(Value::float(1.0), Value::Unit)]).is_err());
}
#[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);
}
#[test]
fn int_value_cross_width_equality() {
assert_eq!(IntValue::I64(42), IntValue::U8(42));
assert_eq!(IntValue::U32(0), IntValue::I8(0));
assert_ne!(IntValue::I64(-1), IntValue::U64(u64::MAX));
}
#[test]
fn int_value_ordering() {
assert!(IntValue::I64(-1) < IntValue::U8(0));
assert!(IntValue::U64(u64::MAX) > IntValue::I64(i64::MAX));
}
#[test]
fn int_value_conversions() {
assert_eq!(IntValue::U64(u64::MAX).to_i64(), None);
assert_eq!(IntValue::U64(42).to_i64(), Some(42));
assert_eq!(IntValue::I64(-1).to_u64(), None);
assert_eq!(IntValue::U8(255).to_u64(), Some(255));
}
#[test]
fn float_value_cross_width_equality() {
assert_eq!(FloatValue::F32(1.0), FloatValue::F64(1.0));
}
}