#[cfg(test)]
mod tests;
use crate::builtins::{
function::{Function, NativeFunction, NativeFunctionData},
object::{
internal_methods_trait::ObjectInternalMethods, InternalState, InternalStateCell, Object,
ObjectKind, INSTANCE_PROTOTYPE, PROTOTYPE,
},
property::Property,
};
use gc::{Gc, GcCell};
use gc_derive::{Finalize, Trace};
use serde_json::{map::Map, Number as JSONNumber, Value as JSONValue};
use std::{
any::Any,
collections::HashSet,
f64::NAN,
fmt::{self, Display},
ops::{Add, BitAnd, BitOr, BitXor, Deref, DerefMut, Div, Mul, Not, Rem, Shl, Shr, Sub},
str::FromStr,
};
#[must_use]
pub type ResultValue = Result<Value, Value>;
pub type Value = Gc<ValueData>;
pub fn undefined() -> Value {
Gc::new(ValueData::Undefined)
}
#[derive(Trace, Finalize, Debug, Clone)]
pub enum ValueData {
Null,
Undefined,
Boolean(bool),
String(String),
Number(f64),
Integer(i32),
Object(GcCell<Object>),
Function(Box<GcCell<Function>>),
Symbol(GcCell<Object>),
}
impl ValueData {
pub fn new_obj(global: Option<&Value>) -> Value {
if let Some(glob) = global {
let obj_proto = glob.get_field_slice("Object").get_field_slice(PROTOTYPE);
let obj = Object::create(obj_proto);
Gc::new(ValueData::Object(GcCell::new(obj)))
} else {
let obj = Object::default();
Gc::new(ValueData::Object(GcCell::new(obj)))
}
}
pub fn new_obj_from_prototype(proto: Value, kind: ObjectKind) -> Value {
let mut obj = Object::default();
obj.kind = kind;
obj.internal_slots
.insert(INSTANCE_PROTOTYPE.to_string(), proto);
Gc::new(ValueData::Object(GcCell::new(obj)))
}
pub fn is_extensible(&self) -> bool {
true
}
pub fn is_object(&self) -> bool {
match *self {
ValueData::Object(_) => true,
_ => false,
}
}
pub fn is_symbol(&self) -> bool {
match *self {
ValueData::Symbol(_) => true,
_ => false,
}
}
pub fn is_function(&self) -> bool {
match *self {
ValueData::Function(_) => true,
ValueData::Object(ref o) => o.deref().borrow().get_internal_slot("call").is_function(),
_ => false,
}
}
pub fn is_undefined(&self) -> bool {
match *self {
ValueData::Undefined => true,
_ => false,
}
}
pub fn is_null(&self) -> bool {
match *self {
ValueData::Null => true,
_ => false,
}
}
pub fn is_null_or_undefined(&self) -> bool {
match *self {
ValueData::Null | ValueData::Undefined => true,
_ => false,
}
}
pub fn is_double(&self) -> bool {
match *self {
ValueData::Number(_) => true,
_ => false,
}
}
pub fn is_num(&self) -> bool {
self.is_double()
}
pub fn is_string(&self) -> bool {
match *self {
ValueData::String(_) => true,
_ => false,
}
}
pub fn is_boolean(&self) -> bool {
match *self {
ValueData::Boolean(_) => true,
_ => false,
}
}
pub fn is_true(&self) -> bool {
match *self {
ValueData::Object(_) => true,
ValueData::String(ref s) if !s.is_empty() => true,
ValueData::Number(n) if n != 0.0 && !n.is_nan() => true,
ValueData::Integer(n) if n != 0 => true,
ValueData::Boolean(v) => v,
_ => false,
}
}
pub fn to_num(&self) -> f64 {
match *self {
ValueData::Object(_)
| ValueData::Symbol(_)
| ValueData::Undefined
| ValueData::Function(_) => NAN,
ValueData::String(ref str) => match FromStr::from_str(str) {
Ok(num) => num,
Err(_) => NAN,
},
ValueData::Number(num) => num,
ValueData::Boolean(true) => 1.0,
ValueData::Boolean(false) | ValueData::Null => 0.0,
ValueData::Integer(num) => f64::from(num),
}
}
pub fn to_int(&self) -> i32 {
match *self {
ValueData::Object(_)
| ValueData::Undefined
| ValueData::Symbol(_)
| ValueData::Null
| ValueData::Boolean(false)
| ValueData::Function(_) => 0,
ValueData::String(ref str) => match FromStr::from_str(str) {
Ok(num) => num,
Err(_) => 0,
},
ValueData::Number(num) => num as i32,
ValueData::Boolean(true) => 1,
ValueData::Integer(num) => num,
}
}
pub fn remove_prop(&self, field: &str) {
match *self {
ValueData::Object(ref obj) => obj.borrow_mut().deref_mut().properties.remove(field),
ValueData::Function(ref func) => match func.borrow_mut().deref_mut() {
Function::NativeFunc(ref mut func) => func.object.properties.remove(field),
Function::RegularFunc(ref mut func) => func.object.properties.remove(field),
},
_ => None,
};
}
pub fn get_prop(&self, field: &str) -> Option<Property> {
if self.is_string() && field == "length" {
if let ValueData::String(ref s) = *self {
return Some(Property::default().value(to_value(s.len() as i32)));
}
}
let obj: Object = match *self {
ValueData::Object(ref obj) => {
let hash = obj.clone();
hash.into_inner()
}
ValueData::Function(ref func) => match func.clone().into_inner() {
Function::NativeFunc(ref func) => func.object.clone(),
Function::RegularFunc(ref func) => func.object.clone(),
},
ValueData::Symbol(ref obj) => {
let hash = obj.clone();
hash.into_inner()
}
_ => return None,
};
match obj.properties.get(field) {
Some(val) => Some(val.clone()),
None => match obj.internal_slots.get(&INSTANCE_PROTOTYPE.to_string()) {
Some(value) => value.get_prop(field),
None => None,
},
}
}
pub fn update_prop(
&self,
field: &str,
value: Option<Value>,
enumerable: Option<bool>,
writable: Option<bool>,
configurable: Option<bool>,
) {
let obj: Option<Object> = match self {
ValueData::Object(ref obj) => Some(obj.borrow_mut().deref_mut().clone()),
ValueData::Function(ref func) => match func.borrow_mut().deref_mut() {
Function::NativeFunc(ref mut func) => Some(func.object.clone()),
Function::RegularFunc(ref mut func) => Some(func.object.clone()),
},
_ => None,
};
if let Some(mut obj_data) = obj {
if let Some(ref mut prop) = obj_data.properties.get_mut(field) {
prop.value = value;
prop.enumerable = enumerable;
prop.writable = writable;
prop.configurable = configurable;
}
}
}
pub fn get_internal_slot(&self, field: &str) -> Value {
let obj: Object = match *self {
ValueData::Object(ref obj) => {
let hash = obj.clone();
hash.into_inner()
}
ValueData::Symbol(ref obj) => {
let hash = obj.clone();
hash.into_inner()
}
_ => return Gc::new(ValueData::Undefined),
};
match obj.internal_slots.get(field) {
Some(val) => val.clone(),
None => Gc::new(ValueData::Undefined),
}
}
pub fn get_field(&self, field: Value) -> Value {
match *field {
ValueData::String(ref s) => {
match self.get_prop(s) {
Some(prop) => {
let prop_getter = match prop.get {
Some(_) => None,
None => None,
};
if let Some(val) = prop_getter {
val
} else {
let val = prop
.value
.as_ref()
.expect("Could not get property as reference");
val.clone()
}
}
None => Gc::new(ValueData::Undefined),
}
}
ValueData::Symbol(_) => unimplemented!(),
_ => Gc::new(ValueData::Undefined),
}
}
pub fn has_internal_state(&self) -> bool {
if let ValueData::Object(ref obj) = *self {
obj.borrow().state.is_some()
} else {
false
}
}
pub fn get_internal_state(&self) -> Option<InternalStateCell> {
if let ValueData::Object(ref obj) = *self {
obj.borrow()
.state
.as_ref()
.map(|state| state.deref().clone())
} else {
None
}
}
pub fn with_internal_state_ref<S: Any + InternalState, R, F: FnOnce(&S) -> R>(
&self,
f: F,
) -> R {
if let ValueData::Object(ref obj) = *self {
let o = obj.borrow();
let state = o
.state
.as_ref()
.expect("no state")
.downcast_ref()
.expect("wrong state type");
f(state)
} else {
panic!("not an object");
}
}
pub fn with_internal_state_mut<S: Any + InternalState, R, F: FnOnce(&mut S) -> R>(
&self,
f: F,
) -> R {
if let ValueData::Object(ref obj) = *self {
let mut o = obj.borrow_mut();
let state = o
.state
.as_mut()
.expect("no state")
.downcast_mut()
.expect("wrong state type");
f(state)
} else {
panic!("not an object");
}
}
pub fn has_field(&self, field: &str) -> bool {
self.get_prop(field).is_some()
}
pub fn get_field_slice(&self, field: &str) -> Value {
let f = Gc::new(ValueData::String(field.to_string()));
self.get_field(f)
}
pub fn set_field(&self, field: Value, val: Value) -> Value {
match *self {
ValueData::Object(ref obj) => {
if obj.borrow().kind == ObjectKind::Array {
if let Ok(num) = field.to_string().parse::<usize>() {
if num > 0 {
let len: i32 = from_value(self.get_field_slice("length"))
.expect("Could not convert argument to i32");
if len < (num + 1) as i32 {
self.set_field_slice("length", to_value(num + 1));
}
}
}
}
if field.is_symbol() {
obj.borrow_mut().set(field, val.clone());
} else {
obj.borrow_mut()
.set(to_value(field.to_string()), val.clone());
}
}
ValueData::Function(ref func) => {
match *func.borrow_mut().deref_mut() {
Function::NativeFunc(ref mut f) => f
.object
.properties
.insert(field.to_string(), Property::default().value(val.clone())),
Function::RegularFunc(ref mut f) => f
.object
.properties
.insert(field.to_string(), Property::default().value(val.clone())),
};
}
_ => (),
}
val
}
pub fn set_field_slice<'a>(&self, field: &'a str, val: Value) -> Value {
let f = Gc::new(ValueData::String(field.to_string()));
self.set_field(f, val)
}
pub fn set_internal_slot(&self, field: &str, val: Value) -> Value {
if let ValueData::Object(ref obj) = *self {
obj.borrow_mut()
.internal_slots
.insert(field.to_string(), val.clone());
}
val
}
pub fn set_kind(&self, kind: ObjectKind) -> ObjectKind {
if let ValueData::Object(ref obj) = *self {
obj.borrow_mut().kind = kind.clone();
}
kind
}
pub fn set_prop(&self, field: String, prop: Property) -> Property {
match *self {
ValueData::Object(ref obj) => {
obj.borrow_mut().properties.insert(field, prop.clone());
}
ValueData::Function(ref func) => {
match *func.borrow_mut().deref_mut() {
Function::NativeFunc(ref mut f) => {
f.object.properties.insert(field, prop.clone())
}
Function::RegularFunc(ref mut f) => {
f.object.properties.insert(field, prop.clone())
}
};
}
_ => (),
}
prop
}
pub fn set_prop_slice<'t>(&self, field: &'t str, prop: Property) -> Property {
self.set_prop(field.to_string(), prop)
}
pub fn set_internal_state<T: Any + InternalState>(&self, state: T) {
if let ValueData::Object(ref obj) = *self {
obj.borrow_mut()
.state
.replace(Box::new(InternalStateCell::new(state)));
}
}
pub fn from_json(json: JSONValue) -> Self {
match json {
JSONValue::Number(v) => {
ValueData::Number(v.as_f64().expect("Could not convert value to f64"))
}
JSONValue::String(v) => ValueData::String(v),
JSONValue::Bool(v) => ValueData::Boolean(v),
JSONValue::Array(vs) => {
let mut new_obj = Object::default();
for (idx, json) in vs.iter().enumerate() {
new_obj.properties.insert(
idx.to_string(),
Property::default().value(to_value(json.clone())),
);
}
new_obj.properties.insert(
"length".to_string(),
Property::default().value(to_value(vs.len() as i32)),
);
ValueData::Object(GcCell::new(new_obj))
}
JSONValue::Object(obj) => {
let mut new_obj = Object::default();
for (key, json) in obj.iter() {
new_obj.properties.insert(
key.clone(),
Property::default().value(to_value(json.clone())),
);
}
ValueData::Object(GcCell::new(new_obj))
}
JSONValue::Null => ValueData::Null,
}
}
pub fn to_json(&self) -> JSONValue {
match *self {
ValueData::Null
| ValueData::Symbol(_)
| ValueData::Undefined
| ValueData::Function(_) => JSONValue::Null,
ValueData::Boolean(b) => JSONValue::Bool(b),
ValueData::Object(ref obj) => {
let mut new_obj = Map::new();
for (k, v) in obj.borrow().internal_slots.iter() {
if k != INSTANCE_PROTOTYPE {
new_obj.insert(k.clone(), v.to_json());
}
}
JSONValue::Object(new_obj)
}
ValueData::String(ref str) => JSONValue::String(str.clone()),
ValueData::Number(num) => JSONValue::Number(
JSONNumber::from_f64(num).expect("Could not convert to JSONNumber"),
),
ValueData::Integer(val) => JSONValue::Number(JSONNumber::from(val)),
}
}
pub fn get_type(&self) -> &'static str {
match *self {
ValueData::Number(_) | ValueData::Integer(_) => "number",
ValueData::String(_) => "string",
ValueData::Boolean(_) => "boolean",
ValueData::Symbol(_) => "symbol",
ValueData::Null => "null",
ValueData::Undefined => "undefined",
ValueData::Function(_) => "function",
ValueData::Object(ref o) => {
if o.deref().borrow().get_internal_slot("call").is_null() {
"object"
} else {
"function"
}
}
}
}
pub fn as_num_to_power(&self, other: ValueData) -> ValueData {
ValueData::Number(self.to_num().powf(other.to_num()))
}
}
impl Default for ValueData {
fn default() -> Self {
ValueData::Undefined
}
}
macro_rules! print_obj_value {
(all of $obj:expr, $display_fn:ident, $indent:expr, $encounters:expr) => {
{
let mut internals = print_obj_value!(internals of $obj, $display_fn, $indent, $encounters);
let mut props = print_obj_value!(props of $obj, $display_fn, $indent, $encounters, true);
props.reserve(internals.len());
props.append(&mut internals);
props
}
};
(internals of $obj:expr, $display_fn:ident, $indent:expr, $encounters:expr) => {
print_obj_value!(impl internal_slots, $obj, |(key, val)| {
format!(
"{}{}: {}",
String::from_utf8(vec![b' '; $indent])
.expect("Could not create indentation string"),
key,
$display_fn(&val, $encounters, $indent.wrapping_add(4), true)
)
})
};
(props of $obj:expr, $display_fn:ident, $indent:expr, $encounters:expr, $print_internals:expr) => {
print_obj_value!(impl properties, $obj, |(key, val)| {
let v = &val
.value
.as_ref()
.expect("Could not get the property's value");
format!(
"{}{}: {}",
String::from_utf8(vec![b' '; $indent])
.expect("Could not create indentation string"),
key,
$display_fn(v, $encounters, $indent.wrapping_add(4), $print_internals)
)
})
};
(impl $field:ident, $v:expr, $f:expr) => {
$v
.borrow()
.$field
.iter()
.map($f)
.collect::<Vec<String>>()
};
}
pub(crate) fn log_string_from(x: &ValueData, print_internals: bool) -> String {
match x {
ValueData::Object(ref v) => {
match v.borrow().kind {
ObjectKind::String => from_value(
v.borrow()
.internal_slots
.get("StringData")
.expect("Cannot get primitive value from String")
.clone(),
)
.expect("Cannot clone primitive value from String"),
ObjectKind::Boolean => {
let bool_data = v.borrow().get_internal_slot("BooleanData").to_string();
format!("Boolean {{ {} }}", bool_data)
}
ObjectKind::Array => {
let len: i32 = from_value(
v.borrow()
.properties
.get("length")
.unwrap()
.value
.clone()
.expect("Could not borrow value"),
)
.expect("Could not convert JS value to i32");
if len == 0 {
return String::from("[]");
}
let arr = (0..len)
.map(|i| {
log_string_from(
&v.borrow()
.properties
.get(&i.to_string())
.unwrap()
.value
.clone()
.expect("Could not borrow value"),
print_internals,
)
})
.collect::<Vec<String>>()
.join(", ");
format!("[ {} ]", arr)
}
_ => display_obj(&x, print_internals),
}
}
ValueData::Symbol(ref sym) => {
let desc: Value = sym.borrow().get_internal_slot("Description");
match *desc {
ValueData::String(ref st) => format!("Symbol(\"{}\")", st.to_string()),
_ => String::from("Symbol()"),
}
}
_ => format!("{}", x),
}
}
fn display_obj(v: &ValueData, print_internals: bool) -> String {
fn address_of<T>(t: &T) -> usize {
let my_ptr: *const T = t;
my_ptr as usize
}
let mut encounters = HashSet::new();
fn display_obj_internal(
data: &ValueData,
encounters: &mut HashSet<usize>,
indent: usize,
print_internals: bool,
) -> String {
if let ValueData::Object(ref v) = *data {
let addr = address_of(v.borrow().deref());
if encounters.contains(&addr) {
return String::from("[Cycle]");
}
encounters.insert(addr);
let result = if print_internals {
print_obj_value!(all of v, display_obj_internal, indent, encounters).join(",\n")
} else {
print_obj_value!(props of v, display_obj_internal, indent, encounters, print_internals)
.join(",\n")
};
encounters.remove(&addr);
let closing_indent = String::from_utf8(vec![b' '; indent.wrapping_sub(4)])
.expect("Could not create the closing brace's indentation string");
format!("{{\n{}\n{}}}", result, closing_indent)
} else {
format!("{}", data)
}
}
display_obj_internal(v, &mut encounters, 4, print_internals)
}
impl Display for ValueData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValueData::Null => write!(f, "null"),
ValueData::Undefined => write!(f, "undefined"),
ValueData::Boolean(v) => write!(f, "{}", v),
ValueData::Symbol(ref v) => match *v.borrow().get_internal_slot("Description") {
ValueData::String(ref v) => write!(f, "{}", format!("Symbol({})", v)),
_ => write!(f, "Symbol()"),
},
ValueData::String(ref v) => write!(f, "{}", v),
ValueData::Number(v) => write!(
f,
"{}",
match v {
_ if v.is_nan() => "NaN".to_string(),
_ if v.is_infinite() && v.is_sign_negative() => "-Infinity".to_string(),
_ if v.is_infinite() => "Infinity".to_string(),
_ => v.to_string(),
}
),
ValueData::Object(_) => write!(f, "{}", log_string_from(self, true)),
ValueData::Integer(v) => write!(f, "{}", v),
ValueData::Function(ref v) => match *v.borrow() {
Function::NativeFunc(_) => write!(f, "function() {{ [native code] }}"),
Function::RegularFunc(ref rf) => {
write!(f, "function{}(", if rf.args.is_empty() { "" } else { " " })?;
for (index, arg) in rf.args.iter().enumerate() {
write!(f, "{}", arg)?;
if index + 1 != rf.args.len() {
write!(f, ", ")?;
}
}
write!(f, ") {}", rf.node)
}
},
}
}
}
impl PartialEq for ValueData {
fn eq(&self, other: &Self) -> bool {
match (self.clone(), other.clone()) {
_ if self.is_null_or_undefined() && other.is_null_or_undefined() => true,
(ValueData::String(_), _) | (_, ValueData::String(_)) => {
self.to_string() == other.to_string()
}
(ValueData::Boolean(a), ValueData::Boolean(b)) if a == b => true,
(ValueData::Number(a), ValueData::Number(b))
if a == b && !a.is_nan() && !b.is_nan() =>
{
true
}
(ValueData::Number(a), _) if a == other.to_num() => true,
(_, ValueData::Number(a)) if a == self.to_num() => true,
(ValueData::Integer(a), ValueData::Integer(b)) if a == b => true,
_ => false,
}
}
}
impl Add for ValueData {
type Output = Self;
fn add(self, other: Self) -> Self {
match (self, other) {
(ValueData::String(ref s), ref o) => {
ValueData::String(format!("{}{}", s.clone(), &o.to_string()))
}
(ref s, ValueData::String(ref o)) => {
ValueData::String(format!("{}{}", s.to_string(), o))
}
(ref s, ref o) => ValueData::Number(s.to_num() + o.to_num()),
}
}
}
impl Sub for ValueData {
type Output = Self;
fn sub(self, other: Self) -> Self {
ValueData::Number(self.to_num() - other.to_num())
}
}
impl Mul for ValueData {
type Output = Self;
fn mul(self, other: Self) -> Self {
ValueData::Number(self.to_num() * other.to_num())
}
}
impl Div for ValueData {
type Output = Self;
fn div(self, other: Self) -> Self {
ValueData::Number(self.to_num() / other.to_num())
}
}
impl Rem for ValueData {
type Output = Self;
fn rem(self, other: Self) -> Self {
ValueData::Number(self.to_num() % other.to_num())
}
}
impl BitAnd for ValueData {
type Output = Self;
fn bitand(self, other: Self) -> Self {
ValueData::Integer(self.to_int() & other.to_int())
}
}
impl BitOr for ValueData {
type Output = Self;
fn bitor(self, other: Self) -> Self {
ValueData::Integer(self.to_int() | other.to_int())
}
}
impl BitXor for ValueData {
type Output = Self;
fn bitxor(self, other: Self) -> Self {
ValueData::Integer(self.to_int() ^ other.to_int())
}
}
impl Shl for ValueData {
type Output = Self;
fn shl(self, other: Self) -> Self {
ValueData::Integer(self.to_int() << other.to_int())
}
}
impl Shr for ValueData {
type Output = Self;
fn shr(self, other: Self) -> Self {
ValueData::Integer(self.to_int() >> other.to_int())
}
}
impl Not for ValueData {
type Output = Self;
fn not(self) -> Self {
ValueData::Boolean(!self.is_true())
}
}
pub trait ToValue {
fn to_value(&self) -> Value;
}
pub trait FromValue {
fn from_value(value: Value) -> Result<Self, &'static str>
where
Self: Sized;
}
impl ToValue for Value {
fn to_value(&self) -> Value {
self.clone()
}
}
impl FromValue for Value {
fn from_value(value: Value) -> Result<Self, &'static str> {
Ok(value)
}
}
impl ToValue for String {
fn to_value(&self) -> Value {
Gc::new(ValueData::String(self.clone()))
}
}
impl FromValue for String {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.to_string())
}
}
impl<'s> ToValue for &'s str {
fn to_value(&self) -> Value {
Gc::new(ValueData::String(
String::from_str(*self).expect("Could not convert string to self to String"),
))
}
}
impl ToValue for char {
fn to_value(&self) -> Value {
Gc::new(ValueData::String(self.to_string()))
}
}
impl FromValue for char {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.to_string()
.chars()
.next()
.expect("Could not get next char"))
}
}
impl ToValue for f64 {
fn to_value(&self) -> Value {
Gc::new(ValueData::Number(*self))
}
}
impl FromValue for f64 {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.to_num())
}
}
impl ToValue for i32 {
fn to_value(&self) -> Value {
Gc::new(ValueData::Integer(*self))
}
}
impl FromValue for i32 {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.to_int())
}
}
impl ToValue for usize {
fn to_value(&self) -> Value {
Gc::new(ValueData::Integer(*self as i32))
}
}
impl FromValue for usize {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.to_int() as usize)
}
}
impl ToValue for bool {
fn to_value(&self) -> Value {
Gc::new(ValueData::Boolean(*self))
}
}
impl FromValue for bool {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.is_true())
}
}
impl<'s, T: ToValue> ToValue for &'s [T] {
fn to_value(&self) -> Value {
let mut arr = Object::default();
for (i, item) in self.iter().enumerate() {
arr.properties
.insert(i.to_string(), Property::default().value(item.to_value()));
}
to_value(arr)
}
}
impl<T: ToValue> ToValue for Vec<T> {
fn to_value(&self) -> Value {
let mut arr = Object::default();
for (i, item) in self.iter().enumerate() {
arr.properties
.insert(i.to_string(), Property::default().value(item.to_value()));
}
to_value(arr)
}
}
impl<T: FromValue> FromValue for Vec<T> {
fn from_value(v: Value) -> Result<Self, &'static str> {
let len = v.get_field_slice("length").to_int();
let mut vec = Self::with_capacity(len as usize);
for i in 0..len {
vec.push(from_value(v.get_field_slice(&i.to_string()))?)
}
Ok(vec)
}
}
impl ToValue for Object {
fn to_value(&self) -> Value {
Gc::new(ValueData::Object(GcCell::new(self.clone())))
}
}
impl FromValue for Object {
fn from_value(v: Value) -> Result<Self, &'static str> {
match *v {
ValueData::Object(ref obj) => Ok(obj.clone().into_inner()),
ValueData::Function(ref func) => Ok(match *func.borrow().deref() {
Function::NativeFunc(ref data) => data.object.clone(),
Function::RegularFunc(ref data) => data.object.clone(),
}),
_ => Err("Value is not a valid object"),
}
}
}
impl ToValue for JSONValue {
fn to_value(&self) -> Value {
Gc::new(ValueData::from_json(self.clone()))
}
}
impl FromValue for JSONValue {
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(v.to_json())
}
}
impl ToValue for () {
fn to_value(&self) -> Value {
Gc::new(ValueData::Null)
}
}
impl FromValue for () {
fn from_value(_: Value) -> Result<(), &'static str> {
Ok(())
}
}
impl<T: ToValue> ToValue for Option<T> {
fn to_value(&self) -> Value {
match *self {
Some(ref v) => v.to_value(),
None => Gc::new(ValueData::Null),
}
}
}
impl<T: FromValue> FromValue for Option<T> {
fn from_value(value: Value) -> Result<Self, &'static str> {
Ok(if value.is_null_or_undefined() {
None
} else {
Some(FromValue::from_value(value)?)
})
}
}
impl ToValue for NativeFunctionData {
fn to_value(&self) -> Value {
Gc::new(ValueData::Function(Box::new(GcCell::new(
Function::NativeFunc(NativeFunction::new(*self)),
))))
}
}
impl FromValue for NativeFunctionData {
fn from_value(v: Value) -> Result<Self, &'static str> {
match *v {
ValueData::Function(ref func) => match *func.borrow() {
Function::NativeFunc(ref data) => Ok(data.data),
_ => Err("Value is not a native function"),
},
_ => Err("Value is not a function"),
}
}
}
pub fn from_value<A: FromValue>(v: Value) -> Result<A, &'static str> {
FromValue::from_value(v)
}
pub fn to_value<A: ToValue>(v: A) -> Value {
v.to_value()
}
pub fn same_value(x: &Value, y: &Value, strict: bool) -> bool {
if strict {
let x_ptr = Gc::into_raw(x.clone());
let y_ptr = Gc::into_raw(y.clone());
return x_ptr == y_ptr;
}
if x.get_type() != y.get_type() {
return false;
}
if x.get_type() == "number" {
let native_x: f64 = from_value(x.clone()).expect("failed to get value");
let native_y: f64 = from_value(y.clone()).expect("failed to get value");
return native_x.abs() - native_y.abs() == 0.0;
}
same_value_non_number(x, y)
}
pub fn same_value_non_number(x: &Value, y: &Value) -> bool {
debug_assert!(x.get_type() == y.get_type());
match x.get_type() {
"undefined" => true,
"null" => true,
"string" => {
if x.to_string() == y.to_string() {
return true;
}
false
}
"boolean" => {
from_value::<bool>(x.clone()).expect("failed to get value")
== from_value::<bool>(y.clone()).expect("failed to get value")
}
"object" => *x == *y,
_ => false,
}
}