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);
let has_instance = interp.new_native("[Symbol.hasInstance]", 1, symbol_has_instance);
let key = interp
.realm
.well_known_key(crate::interp::WellKnown::HasInstance);
function_proto.define_key(
&key,
Property {
value: Some(Value::Object(has_instance)),
..Property::default()
},
);
let thrower = interp.new_native("", 0, throw_type_error);
for name in ["length", "name"] {
let value = thrower
.own_property(name)
.and_then(|property| property.value)
.unwrap_or(Value::Undefined);
thrower.define(name, Property::frozen(value));
}
thrower.set_extensible(false);
interp.realm.throw_type_error = Some(thrower.clone());
for name in ["caller", "arguments"] {
function_proto.define(
name,
Property {
getter: Some(Value::Object(thrower.clone())),
setter: Some(Value::Object(thrower.clone())),
enumerable: false,
configurable: true,
..Property::default()
},
);
}
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> {
if !matches!(&this, Value::Object(object) if object.is_callable()) {
return Err(interp.type_error("not a function"));
}
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)
.unwrap_or(Value::Undefined)
.to_number();
let remaining = (length - leading.len() as f64).max(0.0);
let remaining = if remaining.is_nan() {
0.0
} else {
remaining.trunc()
};
bound.define("length", Property::name_or_length(Value::Float(remaining)));
let name = interp.get_property(this.as_object().expect("callable"), "name")?;
let name = match name {
Some(Value::String(text)) => text.to_string_lossy().to_string(),
_ => String::new(),
};
let text = format!("bound {name}");
bound.define("name", Property::name_or_length(interp.string(text)));
Ok(Value::Object(bound))
}
fn throw_type_error(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
Err(interp.type_error("'caller', 'callee', and 'arguments' properties may not be accessed"))
}
fn symbol_has_instance(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
if !matches!(&this, Value::Object(object) if object.is_callable()) {
return Ok(Value::Bool(false));
}
let answer = interp.ordinary_instance_of(&arg(args, 0), &this)?;
Ok(Value::Bool(answer))
}
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();
if let Some(text) = source_text(&this) {
return Ok(interp.string(text));
}
Ok(interp.string(format!("function {name}() {{\n [native code]\n}}")))
}
fn source_text(this: &Value) -> Option<String> {
this.as_object().and_then(|object| {
object.with(|data| match &data.kind {
crate::object::ObjectKind::Function(crate::object::Callable::Bytecode {
code, ..
}) => {
if code.code.filename.as_deref() == Some("<builtin>") {
None
} else {
code.code.source.clone()
}
}
_ => None,
})
})
}
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,
})
}