use crate::heap::{Bound, Heap, NativeCall, Object, ObjectId, PropertyDescriptor, PropertyKey};
use crate::realm::Realm;
use crate::value::{Abrupt, Completion, Value};
use crate::vm::Vm;
use super::{define_method, define_value, key};
pub fn call(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let arguments: Vec<Value> = call.arguments.iter().skip(1).copied().collect();
vm.call_value(call.this_value, call.argument(0), &arguments, heap)
}
fn to_string(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
if !heap.is_callable(call.this_value) {
return Err(Abrupt::type_error(
"Function.prototype.toString requires a function",
));
}
let name = key(heap, "name");
let held = vm.get_property_key(call.this_value, name, heap)?;
let spelled = match held {
Value::Undefined => Vec::new(),
given => {
let text = vm.to_string(given, heap)?;
heap.string(text).unwrap_or(&[]).to_vec()
}
};
let mut text: Vec<u16> = "function ".encode_utf16().collect();
text.extend_from_slice(&spelled);
text.extend("() { [native code] }".encode_utf16());
Ok(Value::String(heap.intern(&text)))
}
pub fn apply(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let arguments = match call.argument(1) {
Value::Undefined | Value::Null => Vec::new(),
list => list_from(
vm,
heap,
list,
"the arguments given to apply must be an object",
)?,
};
vm.call_value(call.this_value, call.argument(0), &arguments, heap)
}
#[allow(clippy::manual_clamp)] pub(crate) fn list_from(
vm: &mut Vm,
heap: &mut Heap,
list: Value,
wanted: &'static str,
) -> Completion<Vec<Value>> {
let Value::Object(object) = list else {
return Err(Abrupt::type_error(wanted));
};
let name = key(heap, "length");
let value = vm.get_property_key(Value::Object(object), name, heap)?;
let length = vm.to_number(value, heap)?;
let count = length.max(0.0).min(65_535.0) as u64;
let mut arguments = Vec::new();
for index in 0..count {
let at =
PropertyKey::from_units(heap, &index.to_string().encode_utf16().collect::<Vec<_>>());
arguments.push(vm.get_property_key(Value::Object(object), at, heap)?);
}
Ok(arguments)
}
pub fn bind(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let Value::Object(target) = call.this_value else {
return Err(Abrupt::type_error("bind must be called on a function"));
};
if heap.object(target).and_then(Object::call).is_none() {
return Err(Abrupt::type_error("bind must be called on a function"));
}
let this_value = call.argument(0);
let arguments: Vec<Value> = call.arguments.iter().skip(1).copied().collect();
let taken = arguments.len();
let prototype = heap.object(target).and_then(Object::prototype);
let bound = heap.new_bound_function(
prototype,
Bound {
constructs: heap
.object(target)
.and_then(crate::heap::Object::call)
.is_some_and(crate::heap::Callable::constructs),
target,
this_value,
arguments,
},
);
let length_key = key(heap, "length");
let remaining = match heap
.object(target)
.and_then(|found| found.get_own_property(length_key))
{
Some(property) => match property.kind {
crate::heap::PropertyKind::Data {
value: Value::Number(length),
..
} => (length - taken as f64).max(0.0),
_ => 0.0,
},
None => 0.0,
};
let name_key = key(heap, "name");
let target_name = match heap
.object(target)
.and_then(|found| found.get_own_property(name_key))
{
Some(property) => match property.kind {
crate::heap::PropertyKind::Data {
value: Value::String(name),
..
} => String::from_utf16_lossy(heap.string(name).unwrap_or(&[])),
_ => String::new(),
},
None => String::new(),
};
let name = crate::builtins::text(heap, &format!("bound {target_name}"));
crate::builtins::define_metadata(heap, bound, Value::Number(remaining), name);
let _ = vm;
Ok(Value::Object(bound))
}
fn construct(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
dynamic_function(vm, heap, call, Kind::Ordinary)
}
fn async_construct(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
dynamic_function(vm, heap, call, Kind::Async)
}
fn generator_construct(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
dynamic_function(vm, heap, call, Kind::Generator)
}
fn async_generator_construct(
vm: &mut Vm,
heap: &mut Heap,
call: &NativeCall<'_>,
) -> Completion<Value> {
dynamic_function(vm, heap, call, Kind::AsyncGenerator)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Ordinary,
Async,
Generator,
AsyncGenerator,
}
impl Kind {
fn prefix(self) -> &'static str {
match self {
Self::Ordinary => "function",
Self::Async => "async function",
Self::Generator => "function*",
Self::AsyncGenerator => "async function*",
}
}
fn prototype(self, realm: &crate::realm::Realm) -> crate::heap::ObjectId {
match self {
Self::Ordinary => realm.function_prototype(),
Self::Async => realm.async_function_prototype(),
Self::Generator => realm.generator_function_prototype(),
Self::AsyncGenerator => realm.async_generator_function_prototype(),
}
}
}
fn dynamic_function(
vm: &mut Vm,
heap: &mut Heap,
call: &NativeCall<'_>,
kind: Kind,
) -> Completion<Value> {
let (parameters, body) = match call.arguments.split_last() {
Some((body, parameters)) => (parameters, *body),
None => (&[] as &[Value], Value::Undefined),
};
let mut written = String::new();
for (at, parameter) in parameters.iter().enumerate() {
if at > 0 {
written.push(',');
}
written.push_str(&text_of(vm, heap, *parameter)?);
}
let body = match call.arguments.is_empty() {
true => String::new(),
false => text_of(vm, heap, body)?,
};
let source = format!("{} anonymous({written}\n) {{\n{body}\n}}", kind.prefix());
let script = crate::parser::parse_script(&source).map_err(|_| {
Abrupt::Raised(
crate::value::ErrorKind::Syntax,
"the source of a dynamic function does not parse",
)
})?;
if script.body.len() != 1 {
return Err(Abrupt::Raised(
crate::value::ErrorKind::Syntax,
"the source of a dynamic function does not parse as one function",
));
}
let compiled = crate::compile::compile_script(&script, heap)
.map_err(|error| Abrupt::type_error(leaked(error.message())))?;
let Some(inner) = compiled.function(0) else {
return Err(Abrupt::type_error("a dynamic function compiled to nothing"));
};
let inner = std::rc::Rc::clone(inner);
let prototype = super::prototype_from(vm, heap, call, |realm| kind.prototype(realm))?;
let environment = heap.new_environment(None, 0);
let object = heap.new_function(prototype, inner, environment, None, vm.realm().id());
let length = u32::try_from(parameters.len()).unwrap_or(u32::MAX);
super::define_function_metadata(heap, object, "anonymous", length);
reflect_legacy(heap, &vm.realm(), object);
match kind {
Kind::Ordinary => vm.realm().make_constructor(heap, object),
Kind::Async => {}
Kind::Generator => vm.realm().make_generator_function(heap, object, false),
Kind::AsyncGenerator => vm.realm().make_generator_function(heap, object, true),
}
Ok(Value::Object(object))
}
fn leaked(message: String) -> &'static str {
let _ = message;
"building this function from source text is not implemented yet"
}
fn text_of(vm: &mut Vm, heap: &mut Heap, value: Value) -> Completion<String> {
let text = vm.to_string(value, heap)?;
Ok(String::from_utf16_lossy(heap.string(text).unwrap_or(&[])))
}
pub fn install(heap: &mut Heap, realm: &Realm, global: ObjectId) {
let prototype = realm.function_prototype();
heap.make_callable(prototype, returns_undefined, false, realm.id());
crate::builtins::define_function_metadata(heap, prototype, "", 0);
define_method(heap, realm, prototype, "toString", 0, to_string);
define_method(heap, realm, prototype, "apply", 2, apply);
define_method(heap, realm, prototype, "call", 1, call);
define_method(heap, realm, prototype, "bind", 1, bind);
let function = heap.new_native_constructor(prototype, construct, realm.id());
crate::builtins::define_function_metadata(heap, function, "Function", 1);
crate::builtins::define_fixed(heap, function, "prototype", Value::Object(prototype));
define_value(heap, prototype, "constructor", Value::Object(function));
define_value(heap, global, "Function", Value::Object(function));
let has_instance = heap.new_native_function(prototype, has_instance, realm.id());
crate::builtins::define_function_metadata(heap, has_instance, "[Symbol.hasInstance]", 1);
if let Some(symbol) = heap.well_known(crate::builtins::well_known_at("hasInstance")) {
let _ = heap.define_own_property(
prototype,
crate::heap::PropertyKey::from_symbol(symbol),
&crate::heap::PropertyDescriptor {
value: Some(Value::Object(has_instance)),
writable: Some(false),
enumerable: Some(false),
configurable: Some(false),
..crate::heap::PropertyDescriptor::EMPTY
},
);
}
let async_prototype = realm.async_function_prototype();
let async_function = heap.new_native_constructor(function, async_construct, realm.id());
crate::builtins::define_function_metadata(heap, async_function, "AsyncFunction", 1);
crate::builtins::define_fixed(
heap,
async_function,
"prototype",
Value::Object(async_prototype),
);
let name = crate::builtins::key(heap, "constructor");
let _ = heap.define_own_property(
async_prototype,
name,
&crate::heap::PropertyDescriptor {
value: Some(Value::Object(async_function)),
writable: Some(false),
enumerable: Some(false),
configurable: Some(true),
..crate::heap::PropertyDescriptor::EMPTY
},
);
for (name, target, build) in [
(
"GeneratorFunction",
realm.generator_function_prototype(),
generator_construct as crate::heap::Native,
),
(
"AsyncGeneratorFunction",
realm.async_generator_function_prototype(),
async_generator_construct as crate::heap::Native,
),
] {
let made = heap.new_native_constructor(function, build, realm.id());
crate::builtins::define_function_metadata(heap, made, name, 1);
crate::builtins::define_fixed(heap, made, "prototype", Value::Object(target));
let key = crate::builtins::key(heap, "constructor");
let _ = heap.define_own_property(
target,
key,
&crate::heap::PropertyDescriptor {
value: Some(Value::Object(made)),
writable: Some(false),
enumerable: Some(false),
configurable: Some(true),
..crate::heap::PropertyDescriptor::EMPTY
},
);
}
restrict(heap, realm, prototype);
}
fn returns_undefined(_: &mut Vm, _: &mut Heap, _: &NativeCall<'_>) -> Completion<Value> {
Ok(Value::Undefined)
}
fn has_instance(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
vm.ordinary_has_instance(call.this_value, call.argument(0), heap)
}
#[must_use]
pub(crate) fn legacy_reflectable(heap: &Heap, function: ObjectId) -> bool {
let Some(code) = sloppy_body(heap, function) else {
return false;
};
!code.is_generator() && !code.is_async() && !code.is_arrow() && !code.is_method()
}
#[must_use]
pub(crate) fn sloppy_caller(heap: &Heap, function: ObjectId) -> bool {
sloppy_body(heap, function).is_some()
}
fn sloppy_body(heap: &Heap, function: ObjectId) -> Option<&std::rc::Rc<crate::compile::Chunk>> {
let crate::heap::Callable::Bytecode { code, .. } =
heap.object(function).and_then(crate::heap::Object::call)?
else {
return None;
};
match code.is_strict() {
true => None,
false => Some(code),
}
}
pub(crate) fn reflect_legacy(heap: &mut Heap, realm: &Realm, function: ObjectId) {
if !legacy_reflectable(heap, function) {
return;
}
for (name, getter) in [
("caller", realm.legacy_caller()),
("arguments", realm.legacy_arguments()),
] {
let key = key(heap, name);
let _ = heap.define_own_property(
function,
key,
&PropertyDescriptor {
getter: Some(Value::Object(getter)),
enumerable: Some(false),
configurable: Some(true),
..PropertyDescriptor::EMPTY
},
);
}
}
fn legacy_receiver(heap: &Heap, call: &NativeCall<'_>) -> Completion<ObjectId> {
match call.this_value {
Value::Object(function) if legacy_reflectable(heap, function) => Ok(function),
_ => Err(Abrupt::type_error(
"this property may not be read or written",
)),
}
}
pub(crate) fn legacy_caller(
vm: &mut Vm,
heap: &mut Heap,
call: &NativeCall<'_>,
) -> Completion<Value> {
let function = legacy_receiver(heap, call)?;
Ok(vm.legacy_caller_of(function, heap))
}
pub(crate) fn legacy_arguments(
_: &mut Vm,
heap: &mut Heap,
call: &NativeCall<'_>,
) -> Completion<Value> {
legacy_receiver(heap, call)?;
Ok(Value::Null)
}
fn restrict(heap: &mut Heap, realm: &Realm, prototype: ObjectId) {
let thrower = realm.thrower();
for name in ["caller", "arguments"] {
let key = key(heap, name);
let _ = heap.define_own_property(
prototype,
key,
&PropertyDescriptor {
getter: Some(Value::Object(thrower)),
setter: Some(Value::Object(thrower)),
enumerable: Some(false),
configurable: Some(true),
..PropertyDescriptor::EMPTY
},
);
}
}