use crate::heap::{Heap, NativeCall, ObjectId, PropertyDescriptor};
use crate::realm::Realm;
use crate::value::{Abrupt, Completion, ErrorKind, Value};
use crate::vm::Vm;
use super::{define_method, define_value, key};
pub fn construct(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let prototype = super::prototype_from(vm, heap, call, Realm::array_prototype)?;
if call.arguments.len() == 1
&& let Value::Number(length) = call.argument(0)
{
let rounded = length as u32;
if f64::from(rounded) != length {
return Err(Abrupt::Raised(
ErrorKind::Range,
"an array length must be an integer index",
));
}
return Ok(Value::Object(heap.new_array(prototype, rounded)));
}
let array = heap.new_array(prototype, 0);
for (at, value) in call.arguments.iter().enumerate() {
let key = key(heap, &at.to_string());
let descriptor = PropertyDescriptor {
value: Some(*value),
writable: Some(true),
enumerable: Some(true),
configurable: Some(true),
..PropertyDescriptor::EMPTY
};
let _ = heap.define_own_property(array, key, &descriptor);
}
Ok(Value::Object(array))
}
pub(crate) fn from_values(vm: &Vm, heap: &mut Heap, values: &[Value]) -> Completion<Value> {
let array = heap.new_array(vm.realm().array_prototype(), 0);
for (at, value) in values.iter().enumerate() {
let key = key(heap, &at.to_string());
let descriptor = PropertyDescriptor {
value: Some(*value),
writable: Some(true),
enumerable: Some(true),
configurable: Some(true),
..PropertyDescriptor::EMPTY
};
let _ = heap.define_own_property(array, key, &descriptor);
}
Ok(Value::Object(array))
}
pub fn is_array(_vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let Value::Object(object) = call.argument(0) else {
return Ok(Value::Boolean(false));
};
Ok(Value::Boolean(heap.is_array_through(object)?))
}
pub fn install(heap: &mut Heap, realm: &Realm, global: ObjectId) {
let prototype = realm.array_prototype();
let function = heap.new_native_constructor(realm.function_prototype(), construct, realm.id());
super::define_function_metadata(heap, function, "Array", 1);
let key = key(heap, "prototype");
let descriptor = PropertyDescriptor {
value: Some(Value::Object(prototype)),
writable: Some(false),
enumerable: Some(false),
configurable: Some(false),
..PropertyDescriptor::EMPTY
};
let _ = heap.define_own_property(function, key, &descriptor);
define_value(heap, prototype, "constructor", Value::Object(function));
define_value(heap, global, "Array", Value::Object(function));
for (name, length, native) in [
("from", 1, from as crate::heap::Native),
("isArray", 1, is_array),
("of", 0, of),
] {
define_method(heap, realm, function, name, length, native);
}
super::buffer::define_species(heap, realm, function);
define_unscopables(heap, prototype);
}
fn define_unscopables(heap: &mut Heap, prototype: ObjectId) {
let list = heap.new_object(None);
for name in [
"at",
"copyWithin",
"entries",
"fill",
"find",
"findIndex",
"findLast",
"findLastIndex",
"flat",
"flatMap",
"includes",
"keys",
"toReversed",
"toSorted",
"toSpliced",
"values",
] {
super::create_data_property(heap, list, name, Value::Boolean(true));
}
let Some(symbol) = heap.well_known(super::well_known_at("unscopables")) else {
return;
};
let descriptor = PropertyDescriptor {
value: Some(Value::Object(list)),
writable: Some(false),
enumerable: Some(false),
configurable: Some(true),
..PropertyDescriptor::EMPTY
};
let _ = heap.define_own_property(
prototype,
crate::heap::PropertyKey::from_symbol(symbol),
&descriptor,
);
}
fn from(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let items = call.argument(0);
let mapper = match call.argument(1) {
Value::Undefined => None,
value if is_callable(heap, value) => Some(value),
_ => return Err(Abrupt::type_error("the mapping function must be callable")),
};
let receiver = call.argument(2);
if let Some(method) = iterator_method_of(vm, heap, items)? {
let walk = super::iterator::Walk::from_method(vm, heap, items, method)?;
let target = collect_into(vm, heap, call.this_value, &[])?;
let Value::Object(object) = target else {
return Err(Abrupt::type_error("a constructor must answer an object"));
};
let mut at = 0_u64;
while let Some(value) = walk.step(vm, heap)? {
let mapped = match mapper {
Some(mapper) => {
match vm.call_value(mapper, receiver, &[value, Value::Number(at as f64)], heap)
{
Ok(mapped) => mapped,
Err(error) => {
walk.close(vm, heap);
return Err(error);
}
}
}
None => value,
};
if let Err(error) = super::array_methods::create_index(heap, object, at, mapped) {
walk.close(vm, heap);
return Err(error);
}
at += 1;
super::array_methods::within_budget(heap)?;
}
set_final_length(vm, heap, target, at)?;
return Ok(target);
}
let taken = spread_array_like(vm, heap, items)?;
let length = taken.len() as u64;
let target = collect_into(vm, heap, call.this_value, &[Value::Number(length as f64)])?;
let Value::Object(object) = target else {
return Err(Abrupt::type_error("a constructor must answer an object"));
};
for (at, value) in taken.into_iter().enumerate() {
let mapped = match mapper {
Some(mapper) => {
let index = Value::Number(at as f64);
vm.call_value(mapper, receiver, &[value, index], heap)?
}
None => value,
};
super::array_methods::create_index(heap, object, at as u64, mapped)?;
}
set_final_length(vm, heap, target, length)?;
Ok(target)
}
pub(super) fn iterator_of(vm: &mut Vm, heap: &mut Heap, items: Value) -> Completion<Option<Value>> {
let Some(method) = iterator_method_of(vm, heap, items)? else {
return Ok(None);
};
let iterator = vm.call_value(method, items, &[], heap)?;
match iterator {
Value::Object(_) => Ok(Some(iterator)),
_ => Err(Abrupt::type_error("an iterator must be an object")),
}
}
pub(super) fn iterator_method_of(
vm: &mut Vm,
heap: &mut Heap,
items: Value,
) -> Completion<Option<Value>> {
let Some(symbol) = heap.well_known(super::well_known_at("iterator")) else {
return Ok(None);
};
let key = crate::heap::PropertyKey::from_symbol(symbol);
let method = vm.get_property_key(items, key, heap)?;
if matches!(method, Value::Undefined | Value::Null) {
return Ok(None);
}
Ok(Some(method))
}
fn spread_array_like(vm: &mut Vm, heap: &mut Heap, items: Value) -> Completion<Vec<Value>> {
let object = vm.object_for(items, heap)?;
let name = key(heap, "length");
let length = vm.get_property_key(object, name, heap)?;
let length = super::array_methods::to_length(vm.to_number(length, heap)?);
let mut taken = Vec::new();
for at in 0..length {
let index = super::array_methods::index_key(heap, at);
taken.push(vm.get_property_key(object, index, heap)?);
super::array_methods::within_budget(heap)?;
}
Ok(taken)
}
fn collect_into(
vm: &mut Vm,
heap: &mut Heap,
this_value: Value,
arguments: &[Value],
) -> Completion<Value> {
let constructor = matches!(this_value, Value::Object(id)
if heap.object(id).is_some_and(crate::heap::Object::is_constructor));
if constructor {
return vm.construct_value(this_value, arguments, heap);
}
Ok(Value::Object(
heap.new_array(vm.realm().array_prototype(), 0),
))
}
fn set_final_length(vm: &mut Vm, heap: &mut Heap, target: Value, length: u64) -> Completion<()> {
let name = key(heap, "length");
let accepted = vm.set_property_key(target, name, Value::Number(length as f64), heap)?;
match accepted.to_boolean(heap) {
true => Ok(()),
false => Err(Abrupt::type_error(
"the length of what this was collected into could not be set",
)),
}
}
fn of(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let length = call.arguments.len() as u64;
let target = collect_into(vm, heap, call.this_value, &[Value::Number(length as f64)])?;
for (at, value) in call.arguments.iter().enumerate() {
let Value::Object(object) = target else {
return Err(Abrupt::type_error("a constructor must answer an object"));
};
super::array_methods::create_index(heap, object, at as u64, *value)?;
}
set_final_length(vm, heap, target, length)?;
Ok(target)
}
fn is_callable(heap: &Heap, value: Value) -> bool {
let Value::Object(object) = value else {
return false;
};
heap.object(object)
.is_some_and(|found| found.call().is_some())
}