use crate::builtins::{arg, define_method};
use crate::interp::{Interp, JsResult, Signal};
use crate::object::{JsObject, Property};
use crate::value::Value;
use js_gc::Gc;
pub fn install(interp: &mut Interp<'_>, function_proto: &Gc<JsObject>) {
function_proto.define("length", Property::name_or_length(Value::Int(0)));
function_proto.define("name", Property::name_or_length(interp.string("")));
define_method(function_proto, "call", 1, call, interp);
define_method(function_proto, "apply", 2, apply, interp);
define_method(function_proto, "bind", 1, bind, interp);
define_method(function_proto, "toString", 0, to_string, interp);
for (name, getter) in [
("fileName", file_name as crate::object::NativeFn),
("lineNumber", line_number),
("columnNumber", column_number),
] {
let getter = interp.new_native(name, 0, getter);
function_proto.define(
name,
Property::accessor_with(Some(Value::Object(getter)), None, false),
);
}
let constructor = interp.new_native_constructor("Function", 1, constructor);
constructor.define(
"prototype",
Property::with_attributes(Value::Object(function_proto.clone()), false, false),
);
function_proto.define(
"constructor",
Property::with_attributes(Value::Object(constructor.clone()), true, false),
);
let global = interp.realm.global.clone();
global.define(
"Function",
Property::with_attributes(Value::Object(constructor.clone()), true, false),
);
}
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let body = match args.last() {
Some(value) => value.to_js_string(),
None => String::new(),
};
let params: Vec<String> = args
.iter()
.take(args.len().saturating_sub(1))
.map(|value| value.to_js_string())
.collect();
let params = params.join(",");
let source = format!("(function({params}) {{{body}}})");
let program = js_parse::parse_script(&source)
.map_err(|error| Signal::Throw(interp.make_error("SyntaxError", &error.message.clone())))?;
let compiled = js_compile::compile_script(&program)
.map_err(|error| Signal::Throw(interp.make_error("SyntaxError", &error.message)))?;
let function = interp.run_function_source(compiled)?;
if let Value::Object(object) = &function {
object.define(
"name",
Property::with_attributes(interp.string("anonymous"), false, false),
);
}
Ok(function)
}
fn call(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let new_this = arg(args, 0);
let rest: Vec<Value> = args.iter().skip(1).cloned().collect();
interp.call_value(this, new_this, rest)
}
fn apply(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let new_this = arg(args, 0);
let rest = match arg(args, 1) {
Value::Undefined | Value::Null => Vec::new(),
Value::Object(object) => {
let length = interp
.get_property(&object, "length")?
.map(|value| value.to_number().max(0.0) as usize)
.unwrap_or(0);
let mut out = Vec::with_capacity(length);
for index in 0..length {
out.push(
interp
.get_property(&object, &index.to_string())?
.unwrap_or(Value::Undefined),
);
}
out
}
_ => return Err(interp.type_error("apply arguments must be an array-like")),
};
interp.call_value(this, new_this, rest)
}
fn bind(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
let bound_this = arg(args, 0);
let leading: Vec<Value> = args.iter().skip(1).cloned().collect();
let bound = interp.new_bound(this.clone(), bound_this, leading.clone());
let length = this
.as_object()
.and_then(|object| object.own_property("length"))
.and_then(|property| property.value)
.map(|value| value.to_number())
.unwrap_or(0.0);
let remaining = (length - leading.len() as f64).max(0.0);
bound.define(
"length",
Property::name_or_length(Value::Int(remaining as i32)),
);
if let Some(object) = this.as_object()
&& let Some(Value::String(name)) = object.own_property("name").and_then(|p| p.value)
{
let text = format!("bound {}", name.to_string_lossy());
bound.define("name", Property::name_or_length(interp.string(text)));
}
Ok(Value::Object(bound))
}
fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
if !matches!(&this, Value::Object(object) if object.is_callable()) {
return Err(interp.type_error("Function.prototype.toString called on a non-callable"));
}
let name = this
.as_object()
.and_then(|object| object.own_property("name"))
.and_then(|property| property.value)
.map(|value| value.to_js_string())
.unwrap_or_default();
Ok(interp.string(format!("function {name}() {{\n [native code]\n}}")))
}
fn declaration_position(this: &Value) -> Option<(Option<String>, u32, u32)> {
this.as_object().and_then(|object| {
object.with(|data| match &data.kind {
crate::object::ObjectKind::Function(crate::object::Callable::Bytecode {
code, ..
}) => Some((code.code.filename.clone(), code.code.line, code.code.column)),
_ => None,
})
})
}
fn file_name(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
Ok(match declaration_position(&this) {
Some((Some(name), _, _)) => interp.string(name),
_ => Value::Undefined,
})
}
fn line_number(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
Ok(match declaration_position(&this) {
Some((_, line, _)) => Value::Int(line as i32),
None => Value::Undefined,
})
}
fn column_number(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
Ok(match declaration_position(&this) {
Some((_, _, column)) => Value::Int(column as i32),
None => Value::Undefined,
})
}