use num::bigint::BigInt; use num::traits::cast::ToPrimitive; use std::cmp::{Ordering}; use std::fmt::Debug; use std::hash::{Hash,Hasher}; use std::ops::Index; use std::ops::IndexMut; use std::string::String; use std::vec::Vec; pub use std::collections::BTreeSet as Set; pub use std::collections::BTreeMap as Map; pub trait Domain: Sized + Debug + Clone + Eq + Hash + Ord { fn as_preserves(&self) -> Result { Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("Cannot Preserves-encode domain-specific value {:?}", self))) } } pub trait NestedValue: Sized + Debug + Clone + Eq + Hash + Ord { type BoxType: Sized + Debug + Clone + Eq + Hash + Ord; fn wrap(v: Value) -> Self; fn wrap_ann(anns: Vec, v: Value) -> Self; fn boxwrap(self) -> Self::BoxType; fn boxunwrap(b: &Self::BoxType) -> &Self; fn annotations(&self) -> &[Self]; fn value(&self) -> &Value; fn value_owned(self) -> Value; fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for ann in self.annotations() { write!(f, "@{:?} ", ann)?; } self.value().fmt(f) } fn copy_via, E: Domain, F>(&self, f: &F) -> M where F: Fn(&D) -> Value { M::wrap_ann(self.annotations().iter().map(|a| a.copy_via(f)).collect(), self.value().copy_via(f)) } fn copy_via_id>(&self) -> M { self.copy_via(&|d| Value::Domain(d.clone())) } fn to_io_value(&self) -> IOValue { self.copy_via(&|d| d.as_preserves().unwrap().value().clone()) } fn from_io_value(v: &IOValue) -> Self { v.copy_via(&|_| unreachable!()) } } /// The `Value`s from the specification. #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Value where N: NestedValue, D: Domain { Boolean(bool), Float(Float), Double(Double), SignedInteger(BigInt), String(String), ByteString(Vec), Symbol(String), Record(Record), Sequence(Vec), Set(Set), Dictionary(Map), Domain(D), } /// Single-precision IEEE 754 Value #[derive(Clone, Debug)] pub struct Float(pub f32); /// Double-precision IEEE 754 Value #[derive(Clone, Debug)] pub struct Double(pub f64); /// A Record `Value` pub type Record = (>::BoxType, Vec); impl From for Float { fn from(v: f32) -> Self { Float(v) } } impl From for f32 { fn from(v: Float) -> Self { v.0 } } impl Hash for Float { fn hash(&self, state: &mut H) { self.0.to_bits().hash(state); } } impl PartialEq for Float { fn eq(&self, other: &Self) -> bool { self.0.to_bits() == other.0.to_bits() } } impl Ord for Float { fn cmp(&self, other: &Self) -> Ordering { let mut a: u32 = self.0.to_bits(); let mut b: u32 = other.0.to_bits(); if a & 0x8000_0000 != 0 { a ^= 0x7fff_ffff; } if b & 0x8000_0000 != 0 { b ^= 0x7fff_ffff; } (a as i32).cmp(&(b as i32)) } } impl PartialOrd for Float { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Eq for Float {} impl From for Double { fn from(v: f64) -> Self { Double(v) } } impl From for f64 { fn from(v: Double) -> Self { v.0 } } impl Hash for Double { fn hash(&self, state: &mut H) { self.0.to_bits().hash(state); } } impl PartialEq for Double { fn eq(&self, other: &Self) -> bool { self.0.to_bits() == other.0.to_bits() } } impl Ord for Double { fn cmp(&self, other: &Self) -> Ordering { let mut a: u64 = self.0.to_bits(); let mut b: u64 = other.0.to_bits(); if a & 0x8000_0000_0000_0000 != 0 { a ^= 0x7fff_ffff_ffff_ffff; } if b & 0x8000_0000_0000_0000 != 0 { b ^= 0x7fff_ffff_ffff_ffff; } (a as i64).cmp(&(b as i64)) } } impl PartialOrd for Double { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Eq for Double {} impl, D: Domain> From for Value { fn from(v: bool) -> Self { Value::Boolean(v) } } impl, D: Domain> From for Value { fn from(v: f32) -> Self { Value::Float(Float::from(v)) } } impl, D: Domain> From for Value { fn from(v: f64) -> Self { Value::Double(Double::from(v)) } } impl, D: Domain> From for Value { fn from(v: u8) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: i8) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: u16) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: i16) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: u32) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: i32) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: u64) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: i64) -> Self { Value::from(i128::from(v)) } } impl, D: Domain> From for Value { fn from(v: u128) -> Self { Value::SignedInteger(BigInt::from(v)) } } impl, D: Domain> From for Value { fn from(v: i128) -> Self { Value::SignedInteger(BigInt::from(v)) } } impl, D: Domain> From for Value { fn from(v: BigInt) -> Self { Value::SignedInteger(v) } } impl, D: Domain> From<&str> for Value { fn from(v: &str) -> Self { Value::String(String::from(v)) } } impl, D: Domain> From for Value { fn from(v: String) -> Self { Value::String(v) } } impl, D: Domain> From<&[u8]> for Value { fn from(v: &[u8]) -> Self { Value::ByteString(Vec::from(v)) } } // impl, D: Domain> From> for Value { fn from(v: Vec) -> Self { Value::ByteString(v) } } impl, D: Domain> From> for Value { fn from(v: Vec) -> Self { Value::Sequence(v) } } impl, D: Domain> From> for Value { fn from(v: Set) -> Self { Value::Set(v) } } impl, D: Domain> From> for Value { fn from(v: Map) -> Self { Value::Dictionary(v) } } impl, D: Domain> Debug for Value { // Not *quite* a formatter for the Preserves text syntax, since it // doesn't escape strings/symbols properly. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Value::Boolean(false) => f.write_str("#false"), Value::Boolean(true) => f.write_str("#true"), Value::Float(Float(v)) => write!(f, "{:?}f", v), Value::Double(Double(v)) => write!(f, "{:?}", v), Value::SignedInteger(v) => write!(f, "{}", v), Value::String(ref v) => write!(f, "{:?}", v), // TODO: proper escaping! Value::ByteString(ref v) => { f.write_str("#hex{")?; for b in v { write!(f, "{:02x}", b)? } f.write_str("}") } Value::Symbol(ref v) => { // TODO: proper escaping! if v.is_empty() { f.write_str("||") } else { write!(f, "{}", v) } } Value::Record((ref l, ref fs)) => { f.write_str("<")?; l.fmt(f)?; for v in fs { f.write_str(" ")?; v.fmt(f)?; } f.write_str(">") } Value::Sequence(ref v) => v.fmt(f), Value::Set(ref v) => { f.write_str("#set")?; f.debug_set().entries(v.iter()).finish() } Value::Dictionary(ref v) => f.debug_map().entries(v.iter()).finish(), Value::Domain(ref d) => write!(f, "{:?}", d), } } } //--------------------------------------------------------------------------- impl, D: Domain> Value { pub fn wrap(self) -> N { N::wrap(self) } pub fn is_boolean(&self) -> bool { self.as_boolean().is_some() } pub fn as_boolean(&self) -> Option { if let Value::Boolean(b) = *self { Some(b) } else { None } } pub fn as_boolean_mut(&mut self) -> Option<&mut bool> { if let Value::Boolean(ref mut b) = *self { Some(b) } else { None } } pub fn is_float(&self) -> bool { self.as_float().is_some() } pub fn as_float(&self) -> Option { if let Value::Float(Float(f)) = *self { Some(f) } else { None } } pub fn as_float_mut(&mut self) -> Option<&mut f32> { if let Value::Float(Float(ref mut f)) = *self { Some(f) } else { None } } pub fn is_double(&self) -> bool { self.as_double().is_some() } pub fn as_double(&self) -> Option { if let Value::Double(Double(f)) = *self { Some(f) } else { None } } pub fn as_double_mut(&mut self) -> Option<&mut f64> { if let Value::Double(Double(ref mut f)) = *self { Some(f) } else { None } } pub fn is_signedinteger(&self) -> bool { self.as_signedinteger().is_some() } pub fn as_signedinteger(&self) -> Option<&BigInt> { if let Value::SignedInteger(ref i) = *self { Some(i) } else { None } } pub fn as_signedinteger_mut(&mut self) -> Option<&mut BigInt> { if let Value::SignedInteger(ref mut i) = *self { Some(i) } else { None } } pub fn as_u8(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_u8()) } pub fn as_i8(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_i8()) } pub fn as_u16(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_u16()) } pub fn as_i16(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_i16()) } pub fn as_u32(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_u32()) } pub fn as_i32(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_i32()) } pub fn as_u64(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_u64()) } pub fn as_i64(&self) -> Option { self.as_signedinteger().and_then(|i| i.to_i64()) } pub fn is_string(&self) -> bool { self.as_string().is_some() } pub fn as_string(&self) -> Option<&String> { if let Value::String(ref s) = *self { Some(s) } else { None } } pub fn as_string_mut(&mut self) -> Option<&mut String> { if let Value::String(ref mut s) = *self { Some(s) } else { None } } pub fn is_bytestring(&self) -> bool { self.as_bytestring().is_some() } pub fn as_bytestring(&self) -> Option<&Vec> { if let Value::ByteString(ref s) = *self { Some(s) } else { None } } pub fn as_bytestring_mut(&mut self) -> Option<&mut Vec> { if let Value::ByteString(ref mut s) = *self { Some(s) } else { None } } pub fn symbol(s: &str) -> Value { Value::Symbol(s.to_string()) } pub fn is_symbol(&self) -> bool { self.as_symbol().is_some() } pub fn as_symbol(&self) -> Option<&String> { if let Value::Symbol(ref s) = *self { Some(s) } else { None } } pub fn as_symbol_mut(&mut self) -> Option<&mut String> { if let Value::Symbol(ref mut s) = *self { Some(s) } else { None } } pub fn record(label: N, fields: Vec) -> Value { Value::Record((label.boxwrap(), fields)) } pub fn is_record(&self) -> bool { self.as_record(None).is_some() } pub fn as_record(&self, arity: Option) -> Option<&Record> { if let Value::Record(ref r) = *self { match arity { Some(expected) if r.1.len() == expected => Some(r), Some(_other) => None, None => Some(r) } } else { None } } pub fn as_record_mut(&mut self, arity: Option) -> Option<&mut Record> { if let Value::Record(ref mut r) = *self { match arity { Some(expected) if r.1.len() == expected => Some(r), Some(_other) => None, None => Some(r) } } else { None } } pub fn simple_record(label: &str, fields: Vec) -> Value { Value::record(Value::symbol(label).wrap(), fields) } pub fn is_simple_record(&self, label: &str, arity: Option) -> bool { self.as_simple_record(label, arity).is_some() } pub fn as_simple_record(&self, label: &str, arity: Option) -> Option<&Vec> { self.as_record(arity).and_then(|(lp,fs)| { match N::boxunwrap(lp).value() { Value::Symbol(ref s) if s == label => Some(fs), _ => None } }) } pub fn is_sequence(&self) -> bool { self.as_sequence().is_some() } pub fn as_sequence(&self) -> Option<&Vec> { if let Value::Sequence(ref s) = *self { Some(s) } else { None } } pub fn as_sequence_mut(&mut self) -> Option<&mut Vec> { if let Value::Sequence(ref mut s) = *self { Some(s) } else { None } } pub fn is_set(&self) -> bool { self.as_set().is_some() } pub fn as_set(&self) -> Option<&Set> { if let Value::Set(ref s) = *self { Some(s) } else { None } } pub fn as_set_mut(&mut self) -> Option<&mut Set> { if let Value::Set(ref mut s) = *self { Some(s) } else { None } } pub fn is_dictionary(&self) -> bool { self.as_dictionary().is_some() } pub fn as_dictionary(&self) -> Option<&Map> { if let Value::Dictionary(ref s) = *self { Some(s) } else { None } } pub fn as_dictionary_mut(&mut self) -> Option<&mut Map> { if let Value::Dictionary(ref mut s) = *self { Some(s) } else { None } } pub fn copy_via, E: Domain, F>(&self, f: &F) -> Value where F: Fn(&D) -> Value { match self { Value::Boolean(b) => Value::Boolean(*b), Value::Float(f) => Value::Float(f.clone()), Value::Double(d) => Value::Double(d.clone()), Value::SignedInteger(i) => Value::SignedInteger(i.clone()), Value::String(ref s) => Value::String(s.clone()), Value::ByteString(ref v) => Value::ByteString(v.clone()), Value::Symbol(ref v) => Value::Symbol(v.clone()), Value::Record((ref l, ref fs)) => Value::Record((N::boxunwrap(l).copy_via::(f).boxwrap(), fs.iter().map(|a| a.copy_via(f)).collect())), Value::Sequence(ref v) => Value::Sequence(v.iter().map(|a| a.copy_via(f)).collect()), Value::Set(ref v) => Value::Set(v.iter().map(|a| a.copy_via(f)).collect()), Value::Dictionary(ref v) => Value::Dictionary(v.iter().map(|(a,b)| (a.copy_via(f), b.copy_via(f))).collect()), Value::Domain(d) => f(d), } } } impl, D: Domain> Index for Value { type Output = N; fn index(&self, i: usize) -> &Self::Output { &self.as_sequence().unwrap()[i] } } impl, D: Domain> IndexMut for Value { fn index_mut(&mut self, i: usize) -> &mut Self::Output { &mut self.as_sequence_mut().unwrap()[i] } } impl, D: Domain> Index<&N> for Value { type Output = N; fn index(&self, i: &N) -> &Self::Output { &(*self.as_dictionary().unwrap())[i] } } //--------------------------------------------------------------------------- // This part is a terrible hack impl serde::Serialize for UnwrappedIOValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { super::magic::output_value(serializer, self.clone().wrap()) } } impl<'de> serde::Deserialize<'de> for UnwrappedIOValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { Ok(super::magic::input_value::<'de, D>(deserializer)?.value_owned()) } } pub fn serialize_nested_value(v: &N, serializer: S) -> Result where S: serde::Serializer, N: NestedValue + serde::Serialize { super::magic::output_value(serializer, v.to_io_value()) } pub fn deserialize_nested_value<'de, D, N, Dom: Domain>(deserializer: D) -> Result where D: serde::Deserializer<'de>, N: NestedValue + serde::Deserialize<'de> { Ok(N::from_io_value(&super::magic::input_value(deserializer)?)) } //--------------------------------------------------------------------------- /// An possibly-annotated Value, with annotations (themselves /// possibly-annotated) in order of appearance. #[derive(Clone)] pub struct AnnotatedValue, D: Domain>(pub Vec, pub Value); impl, D: Domain> PartialEq for AnnotatedValue { fn eq(&self, other: &Self) -> bool { self.1.eq(&other.1) } } impl, D: Domain> Eq for AnnotatedValue {} impl, D: Domain> Hash for AnnotatedValue { fn hash(&self, state: &mut H) { self.1.hash(state); } } impl, D: Domain> PartialOrd for AnnotatedValue { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl, D: Domain> Ord for AnnotatedValue { fn cmp(&self, other: &Self) -> Ordering { self.1.cmp(&other.1) } } //--------------------------------------------------------------------------- #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct PlainValue(AnnotatedValue, D>); impl PlainValue { pub fn annotations_mut(&mut self) -> &mut Vec { &mut (self.0).0 } pub fn value_mut(&mut self) -> &mut Value { &mut (self.0).1 } } impl NestedValue for PlainValue { type BoxType = Box; fn wrap(v: Value) -> Self { Self::wrap_ann(Vec::new(), v) } fn wrap_ann(anns: Vec, v: Value) -> Self { PlainValue(AnnotatedValue(anns, v)) } fn boxwrap(self) -> Self::BoxType { Box::new(self) } fn boxunwrap(b: &Self::BoxType) -> &Self { &**b } fn annotations(&self) -> &[Self] { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn value_owned(self) -> Value { (self.0).1 } } impl Debug for PlainValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } impl serde::Serialize for PlainValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { serialize_nested_value(self, serializer) } } impl<'de, Dom: Domain> serde::Deserialize<'de> for PlainValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } } //--------------------------------------------------------------------------- use std::rc::Rc; #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RcValue(Rc, D>>); impl NestedValue for RcValue { type BoxType = Self; fn wrap(v: Value) -> Self { Self::wrap_ann(Vec::new(), v) } fn wrap_ann(anns: Vec, v: Value) -> Self { RcValue(Rc::new(AnnotatedValue(anns, v))) } fn boxwrap(self) -> Self::BoxType { self } fn boxunwrap(b: &Self::BoxType) -> &Self { b } fn annotations(&self) -> &[Self] { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn value_owned(self) -> Value { Rc::try_unwrap(self.0).unwrap_or_else(|_| panic!("value_owned on RcValue with refcount greater than one")).1 } } impl Debug for RcValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } impl serde::Serialize for RcValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { serialize_nested_value(self, serializer) } } impl<'de, Dom: Domain> serde::Deserialize<'de> for RcValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } } //--------------------------------------------------------------------------- use std::sync::Arc; #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ArcValue(Arc, D>>); impl NestedValue for ArcValue { type BoxType = Self; fn wrap(v: Value) -> Self { Self::wrap_ann(Vec::new(), v) } fn wrap_ann(anns: Vec, v: Value) -> Self { ArcValue(Arc::new(AnnotatedValue(anns, v))) } fn boxwrap(self) -> Self::BoxType { self } fn boxunwrap(b: &Self::BoxType) -> &Self { b } fn annotations(&self) -> &[Self] { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn value_owned(self) -> Value { Arc::try_unwrap(self.0).unwrap_or_else(|_| panic!("value_owned on ArcValue with refcount greater than one")).1 } } impl Debug for ArcValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } impl serde::Serialize for ArcValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { serialize_nested_value(self, serializer) } } impl<'de, Dom: Domain> serde::Deserialize<'de> for ArcValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } } //--------------------------------------------------------------------------- #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum NullDomain {} impl Domain for NullDomain {} #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct IOValue(Arc>); pub type UnwrappedIOValue = Value; impl NestedValue for IOValue { type BoxType = Self; fn wrap(v: Value) -> Self { Self::wrap_ann(Vec::new(), v) } fn wrap_ann(anns: Vec, v: Value) -> Self { IOValue(Arc::new(AnnotatedValue(anns, v))) } fn boxwrap(self) -> Self::BoxType { self } fn boxunwrap(b: &Self::BoxType) -> &Self { b } fn annotations(&self) -> &[Self] { &(self.0).0 } fn value(&self) -> &Value { &(self.0).1 } fn value_owned(self) -> Value { match Arc::try_unwrap(self.0) { Ok(AnnotatedValue(_anns, v)) => v, Err(r) => r.1.clone(), } } fn to_io_value(&self) -> IOValue { self.clone() } fn from_io_value(v: &IOValue) -> Self { v.clone() } } impl Debug for IOValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_fmt(f) } } impl serde::Serialize for IOValue { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { serialize_nested_value(self, serializer) } } impl<'de> serde::Deserialize<'de> for IOValue { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { deserialize_nested_value(deserializer) } }