use std::cell::RefCell;
use std::rc::Rc;
use crate::RuntimeError;
use crate::vm::object::{JSObject, NativeFunctionObject};
use crate::vm::property::PropertyKey;
use crate::vm::value::Value;
pub fn function_constructor(_args: &[Value]) -> Result<Value, RuntimeError> {
Err(RuntimeError::TypeError(
"Function constructor is not supported (eval-like features are disabled)".to_string(),
))
}
pub fn function_prototype_to_string(obj: &Value) -> Result<Value, RuntimeError> {
let name = match obj {
Value::Function(_) => "anonymous".to_string(),
Value::Object(obj_ref) => {
let borrowed = obj_ref.borrow();
if borrowed.kind() == crate::vm::property::ObjectKind::NativeFunction {
if let Some(nf) = borrowed.as_any().downcast_ref::<NativeFunctionObject>() {
nf.name.clone()
} else {
"anonymous".to_string()
}
} else {
"anonymous".to_string()
}
}
_ => {
return Err(RuntimeError::TypeError(
"Function.prototype.toString called on non-function".to_string(),
));
}
};
Ok(Value::string(&format!(
"function {}() {{ [native code] }}",
name
)))
}
pub fn register_function_statics(
function_fn_val: &Value,
function_prototype: &Rc<RefCell<dyn JSObject>>,
) {
if let Value::Object(obj_ref) = function_fn_val {
let mut obj = obj_ref.borrow_mut();
obj.define_property(
PropertyKey::from_str("prototype"),
super::constructor_prototype_descriptor(Value::Object(Rc::clone(function_prototype))),
)
.ok();
}
}
pub fn setup_function_prototype(proto: &Rc<RefCell<dyn JSObject>>) {
let mut p = proto.borrow_mut();
for name in ["call", "apply", "bind", "toString"] {
p.define_property(
PropertyKey::from_str(name),
super::method_descriptor(Value::Object(Rc::new(RefCell::new(
NativeFunctionObject::new(name),
)))),
)
.ok();
}
}