From baaf3619f9b5c16b96dfbbc95dcb2d02ccb90370 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sun, 22 Nov 2026 10:59:43 +0000 Subject: [PATCH 1/6] WIP clazel-js-vm: array exotic objects, unfinished and untested Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-vm/src/heap.rs | 121 +++++++++++++++++++++++++++++- crates/clazel-js-vm/src/interp.rs | 4 +- crates/clazel-js-vm/src/lib.rs | 1 + 3 files changed, 124 insertions(+), 2 deletions(-) diff --git a/crates/clazel-js-vm/src/heap.rs b/crates/clazel-js-vm/src/heap.rs index 20ccdec6..463b4872 100644 --- a/crates/clazel-js-vm/src/heap.rs +++ b/crates/clazel-js-vm/src/heap.rs @@ -46,6 +46,12 @@ pub enum ObjKind { /// primitive as `[[BooleanData]]`, `[[NumberData]]` or `[[StringData]]` /// (§20.3†, §21.1†, §22.1†). Primitive(Value), + /// An Array exotic object (§10.4.2†). Its `length` is the first property + /// (slot 0), made by [`Heap::new_array`] and never removed, so reading it + /// is one slot access. The index properties are ordinary data properties + /// in the shape, because `clazel-js-heap`'s elements (#211) are not on + /// this base. + Array, } /// An object: properties by shape, a prototype and a kind. @@ -138,16 +144,26 @@ pub struct Heap { arena: Arena, shapes: Shapes, keys: Interner, + /// The interned `length`, which an array keeps in slot 0. + length_key: Key, } impl Heap { /// An empty heap whose arena holds at most `limit` cells. #[must_use] pub fn new(limit: usize) -> Self { + let mut keys = Interner::new(); + // "length" is 6 code units: it fits the string limit, so the + // interner cannot refuse it; the fallback key is never used. + let length_key = JsString::from_rust_str("length") + .ok() + .and_then(|s| keys.intern(&s).ok()) + .unwrap_or(Key(0)); Self { arena: Arena::with_limit(limit), shapes: Shapes::new(), - keys: Interner::new(), + keys, + length_key, } } @@ -195,6 +211,100 @@ impl Heap { })) } + /// Allocates an Array exotic object whose `length` is `len`: the + /// property is writable, not enumerable, not configurable + /// (§10.4.2.2† ArrayCreate steps 6 to 8). `len` must already be checked + /// against 2^32 - 1. + /// + /// # Errors + /// [`HeapError::Full`] if the arena is full. + pub fn new_array(&mut self, proto: Value, len: u32) -> Result { + let a = self.new_object(proto, ObjKind::Array)?; + let k = self.length_key; + self.define(a, k, length_value(len), Attrs(Attrs::WRITABLE))?; + Ok(a) + } + + /// The `length` of an Array exotic object, with whether it is writable. + #[must_use] + pub fn array_length(&self, arr: Value) -> Option<(u32, bool)> { + let o = self.obj(arr)?; + if !matches!(o.kind, ObjKind::Array) { + return None; + } + let (slot, attrs) = self.shapes.lookup(o.shape, self.length_key)?; + let v = o.slots.get(usize::try_from(slot).ok()?).copied()?; + let d = crate::numeric::num(v)?.to_f64(); + let n = d as u32; + (f64::from(n) == d).then_some((n, attrs.0 & Attrs::WRITABLE != 0)) + } + + /// Stores `len` as the `length` of an array (the caller has checked that + /// the property is writable, or is applying a definition). + /// + /// # Errors + /// [`HeapError::Corrupt`] if `arr` is not an array. + pub fn set_array_length(&mut self, arr: Value, len: u32) -> Result<(), HeapError> { + let o = self.obj(arr).ok_or(HeapError::Corrupt)?; + let (slot, _) = self + .shapes + .lookup(o.shape, self.length_key) + .ok_or(HeapError::Corrupt)?; + self.set_slot(arr, slot, length_value(len)) + } + + /// Whether a value is an Array exotic object. + #[must_use] + pub fn is_array_object(&self, v: Value) -> bool { + self.obj(v).is_some_and(|o| matches!(o.kind, ObjKind::Array)) + } + + /// The array index a key names (§6.1.7†), if it names one. + #[must_use] + pub fn key_index(&self, k: Key) -> Option { + self.keys.resolve(k).and_then(canonical_index) + } + + /// Removes the own properties `keys` of `obj` (a key it does not have is + /// ignored): the shape is rebuilt from the root without them, so the + /// others keep their order and get consecutive slots. A shared shape + /// reuses its transitions; a dictionary shape (an object with more than + /// 128 properties) gets a new dictionary shape each time, which stays in + /// the shape table until the collector of #236 frees it. + /// + /// # Errors + /// [`HeapError::Corrupt`] if `obj` is not an object, [`HeapError::Full`] + /// on overflow. + pub fn remove_properties(&mut self, obj: Value, keys: &[Key]) -> Result<(), HeapError> { + let o = self.obj(obj).ok_or(HeapError::Corrupt)?; + let props = self.shapes.properties(o.shape); + if !props.iter().any(|(k, _, _)| keys.contains(k)) { + return Ok(()); + } + let mut shape = ROOT; + let mut slots: Vec = Vec::with_capacity(props.len()); + for (k, slot, a) in props { + if keys.contains(&k) { + continue; + } + let v = usize::try_from(slot) + .ok() + .and_then(|i| o.slots.get(i)) + .copied() + .ok_or(HeapError::Corrupt)?; + let (next, new_slot) = self.shapes.add_property(shape, k, a)?; + if usize::try_from(new_slot).ok() != Some(slots.len()) { + return Err(HeapError::Corrupt); + } + shape = next; + slots.push(v); + } + let o = self.obj_mut(obj).ok_or(HeapError::Corrupt)?; + o.shape = shape; + o.slots = slots; + Ok(()) + } + /// The live cell a value refers to. #[must_use] pub fn cell(&self, v: Value) -> Option<&Cell> { @@ -459,6 +569,15 @@ impl Heap { } } +/// A `length` value: an int32 when it fits, else a double. +#[must_use] +pub fn length_value(len: u32) -> Value { + match i32::try_from(len) { + Ok(i) => Value::int32(i), + Err(_) => Value::double(f64::from(len)), + } +} + /// The array index a string names (§6.1.7†): decimal digits, no leading /// zero except `0` itself, below 2^32 - 1. fn canonical_index(s: &JsString) -> Option { diff --git a/crates/clazel-js-vm/src/interp.rs b/crates/clazel-js-vm/src/interp.rs index 7b935517..bb963451 100644 --- a/crates/clazel-js-vm/src/interp.rs +++ b/crates/clazel-js-vm/src/interp.rs @@ -149,10 +149,12 @@ pub enum Intrinsic { NumberPrototype, /// `%String.prototype%`. StringPrototype, + /// `%Array.prototype%`. + ArrayPrototype, } /// How many [`Intrinsic`]s there are. -const INTRINSICS: usize = 10; +const INTRINSICS: usize = 11; /// The hint of ToPrimitive (§7.1.1†). #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/clazel-js-vm/src/lib.rs b/crates/clazel-js-vm/src/lib.rs index f4884fac..cd2f1e39 100644 --- a/crates/clazel-js-vm/src/lib.rs +++ b/crates/clazel-js-vm/src/lib.rs @@ -49,6 +49,7 @@ pub mod lemmas; pub mod literal; pub mod numeric; pub mod ops; +pub mod props; pub mod scope; pub mod spec; From 6dd8d1e2d0fc07ebe550a01f500fe36ffde33fd1 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sun, 22 Nov 2026 15:18:30 +0000 Subject: [PATCH 2/6] clazel-js-vm, clazel-js-builtins: array exotic objects, Array and Array.prototype PropDesc and [[DefineOwnProperty]] (OrdinaryDefineOwnProperty and the Array exotic object's, ArraySetLength), ArrayCreate, [[Delete]], NewArray and DeleteProp handlers, array literals with trailing elisions, a bound on nested natives, and the Array constructor with the core of Array.prototype. Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-builtins/src/array.rs | 1276 ++++++++++++++++++++++ crates/clazel-js-builtins/src/lib.rs | 2 + crates/clazel-js-builtins/src/object.rs | 77 +- crates/clazel-js-builtins/src/util.rs | 14 +- crates/clazel-js-builtins/tests/array.rs | 425 +++++++ crates/clazel-js-vm/src/compile/misc.rs | 23 + crates/clazel-js-vm/src/handlers.rs | 22 +- crates/clazel-js-vm/src/heap.rs | 3 +- crates/clazel-js-vm/src/interp.rs | 49 +- crates/clazel-js-vm/src/props.rs | 504 +++++++++ 10 files changed, 2313 insertions(+), 82 deletions(-) create mode 100644 crates/clazel-js-builtins/src/array.rs create mode 100644 crates/clazel-js-builtins/tests/array.rs create mode 100644 crates/clazel-js-vm/src/props.rs diff --git a/crates/clazel-js-builtins/src/array.rs b/crates/clazel-js-builtins/src/array.rs new file mode 100644 index 00000000..f86c7516 --- /dev/null +++ b/crates/clazel-js-builtins/src/array.rs @@ -0,0 +1,1276 @@ +//! `Array` (§23.1†): the constructor, `Array.isArray`, `Array.of`, and the +//! core of `Array.prototype`: `push`, `pop`, `shift`, `unshift`, `slice`, +//! `splice`, `concat`, `join`, `toString`, `indexOf`, `lastIndexOf`, +//! `includes`, `reverse`, `fill`, `forEach`, `map`, `filter`, `some`, `every`, +//! `reduce`, `reduceRight`, `find`, `findIndex` and `sort`. +//! +//! The methods are generic, as the standard writes them: each reads and +//! writes through `Get`, `Set`, `HasProperty` and `DeletePropertyOrThrow` on +//! `ToObject(this value)`, and does not assume an Array exotic object. The +//! "mathematical values" of the algorithms (indices up to 2^53 - 1) are `f64`, +//! which holds them exactly. +//! +//! Left for when Symbols and iterators exist: `Array.from`, `entries`, +//! `keys`, `values` and `@@iterator`, `@@species`, `@@isConcatSpreadable`, +//! `@@unscopables`. `ArraySpeciesCreate` therefore uses the receiver's +//! `constructor` itself where the standard reads its `@@species`. + +use crate::util::{arg, constructor, js_string, method, number, to_integer_or_infinity}; +use clazel_js_heap::string::{JsString, Key}; +use clazel_js_heap::value::Value; +use clazel_js_vm::interp::{Abrupt, Intrinsic, Vm}; + +/// 2^53 - 1: the largest integer index and length (§6.1.6.1†, §7.1.20†). +const MAX_SAFE: f64 = 9_007_199_254_740_991.0; + +/// Installs `Array`, `Array.prototype` and their methods. +/// +/// # Errors +/// As [`crate::install`]. +pub fn install(vm: &mut Vm) -> Result<(), Abrupt> { + // §23.1.3†: "The Array prototype object is an Array exotic object ... with + // a [[Prototype]] of %Object.prototype% and a length of 0". + let object_proto = vm.intrinsic(Intrinsic::ObjectPrototype); + let proto = vm.heap_mut().new_array(object_proto, 0)?; + vm.set_intrinsic(Intrinsic::ArrayPrototype, proto); + let ctor = constructor(vm, "Array", 1, array_constructor, proto)?; + vm.set_intrinsic(Intrinsic::ArrayConstructor, ctor); + method(vm, ctor, "isArray", 1, is_array)?; + method(vm, ctor, "of", 0, array_of)?; + let methods: [(&str, i32, clazel_js_vm::interp::NativeFn); 24] = [ + ("concat", 1, concat), + ("every", 1, every), + ("fill", 1, fill), + ("filter", 1, filter), + ("find", 1, find), + ("findIndex", 1, find_index), + ("forEach", 1, for_each), + ("includes", 1, includes), + ("indexOf", 1, index_of), + ("join", 1, join), + ("lastIndexOf", 1, last_index_of), + ("map", 1, map), + ("pop", 0, pop), + ("push", 1, push), + ("reduce", 1, reduce), + ("reduceRight", 1, reduce_right), + ("reverse", 0, reverse), + ("shift", 0, shift), + ("slice", 2, slice), + ("some", 1, some), + ("sort", 1, sort), + ("splice", 2, splice), + ("toString", 0, to_string), + ("unshift", 1, unshift), + ]; + for (name, len, f) in methods { + method(vm, proto, name, len, f)?; + } + crate::util::global(vm, "Array", ctor) +} + +// --------------------------------------------------------------------- +// Abstract operations +// --------------------------------------------------------------------- + +/// The key `ToString(𝔽(k))` of an integer `k`. +fn pk(vm: &mut Vm, k: f64) -> Result { + vm.index_key(k as u64) +} + +/// `Get(O, ToString(k))`, §7.3.2†. +fn get_at(vm: &mut Vm, o: Value, k: f64) -> Result { + let key = pk(vm, k)?; + vm.get_value(o, key) +} + +/// `HasProperty(O, ToString(k))`, §7.3.12†. +fn has_at(vm: &mut Vm, o: Value, k: f64) -> Result { + let key = pk(vm, k)?; + Ok(vm.heap().find(o, key)?.is_some()) +} + +/// `Set(O, ToString(k), v, true)`, §7.3.4†. +fn set_at(vm: &mut Vm, o: Value, k: f64, v: Value) -> Result<(), Abrupt> { + let key = pk(vm, k)?; + vm.put_value(o, key, v, true) +} + +/// `DeletePropertyOrThrow(O, ToString(k))`, §7.3.10†. +fn delete_at(vm: &mut Vm, o: Value, k: f64) -> Result<(), Abrupt> { + let key = pk(vm, k)?; + vm.delete_property_or_throw(o, key) +} + +/// `CreateDataPropertyOrThrow(O, ToString(k), v)`, §7.3.7†. +fn create_at(vm: &mut Vm, o: Value, k: f64, v: Value) -> Result<(), Abrupt> { + let key = pk(vm, k)?; + vm.create_data_property_or_throw(o, key, v) +} + +/// `Set(O, "length", n, true)`. +fn set_length(vm: &mut Vm, o: Value, n: f64) -> Result<(), Abrupt> { + let key = crate::util::key(vm, "length")?; + vm.put_value(o, key, number(n), true) +} + +/// LengthOfArrayLike ( obj ), §7.3.19†: `ToLength(? Get(obj, "length"))`, and +/// ToLength (§7.1.20†): ToIntegerOrInfinity, then clamp to `[0, 2^53 - 1]`. +fn length_of(vm: &mut Vm, o: Value) -> Result { + let key = crate::util::key(vm, "length")?; + let v = vm.get_value(o, key)?; + let n = to_integer_or_infinity(vm, v)?; + Ok(n.clamp(0.0, MAX_SAFE)) +} + +/// The relative index of `start`, `end` and `fromIndex` arguments: ToIntegerOrInfinity, +/// then "if relative is -infinity, let k be 0; else if relative < 0, let k be +/// max(len + relative, 0); else let k be min(relative, len)". +fn relative(vm: &mut Vm, v: Value, len: f64) -> Result { + let rel = to_integer_or_infinity(vm, v)?; + Ok(if rel == f64::NEG_INFINITY { + 0.0 + } else if rel < 0.0 { + (len + rel).max(0.0) + } else { + rel.min(len) + }) +} + +/// The `end` argument: `len` when `undefined`, else as [`relative`]. +fn relative_end(vm: &mut Vm, v: Value, len: f64) -> Result { + if v == Value::UNDEFINED { + Ok(len) + } else { + relative(vm, v, len) + } +} + +/// A callable argument, else a TypeError (the first steps of `forEach`, `map` +/// and the others: "If IsCallable(callbackfn) is false, throw a TypeError"). +fn callable(vm: &mut Vm, f: Value) -> Result { + if vm.heap().is_callable(f) { + Ok(f) + } else { + let d = vm.describe(f); + Err(vm.type_error(&format!("{d} is not a function"))) + } +} + +/// SameValueZero, §7.2.11†: as SameValue except that `+0` equals `-0`. +fn same_value_zero(vm: &Vm, a: Value, b: Value) -> bool { + if let (Some(x), Some(y)) = (crate::util::as_number(a), crate::util::as_number(b)) { + return x == y || (x.is_nan() && y.is_nan()); + } + vm.same_value(a, b) +} + +/// ArraySpeciesCreate ( originalArray, length ), §10.4.2.3†: +/// 1. If IsArray(originalArray) is false, return ? ArrayCreate(length). +/// 2. Let C be ? Get(originalArray, "constructor"). +/// 3. If IsConstructor(C) is true, then (the cross-realm check: one realm). +/// 4. If C is an Object, then a. Set C to ? Get(C, @@species). (Not +/// consulted: no Symbols; C stays the constructor.) +/// 5. If C is undefined, return ? ArrayCreate(length). +/// 6. If IsConstructor(C) is false, throw a TypeError exception. +/// 7. Return ? Construct(C, « 𝔽(length) »). +fn species_create(vm: &mut Vm, original: Value, length: f64) -> Result { + if !vm.is_array(original) { + return vm.array_create(length, None); + } + let c = vm.get_named(original, "constructor")?; + if c == Value::UNDEFINED || c == vm.intrinsic(Intrinsic::ArrayConstructor) { + return vm.array_create(length, None); + } + if !vm.is_constructor(c) { + return Err(vm.type_error("object.constructor is not a constructor")); + } + vm.construct_value(c, &[number(length)]) +} + +// --------------------------------------------------------------------- +// The constructor and the static functions +// --------------------------------------------------------------------- + +/// `Array ( ...values )`, §23.1.1.1†: +/// 1. If NewTarget is undefined, let newTarget be the active function object; +/// else let newTarget be NewTarget. +/// 2. Let proto be ? GetPrototypeFromConstructor(newTarget, +/// "%Array.prototype%"). +/// 3. Let numberOfArgs be the number of elements in values. +/// 4. If numberOfArgs = 0, then a. Return ! ArrayCreate(0, proto). +/// 5. Else if numberOfArgs = 1, then +/// a. Let len be values[0]. b. Let array be ! ArrayCreate(0, proto). +/// c. If len is not a Number, then i. Perform ! +/// CreateDataPropertyOrThrow(array, "0", len). ii. Let intLen be 1𝔽. +/// d. Else, i. Let intLen be ! ToUint32(len). ii. If SameValueZero(intLen, +/// len) is false, throw a RangeError exception. +/// e. Perform ! Set(array, "length", intLen, true). f. Return array. +/// 6. Else, a. (Assert: numberOfArgs >= 2.) b. Let array be ? +/// ArrayCreate(numberOfArgs, proto). c. Let k be 0. d. Repeat, while k < +/// numberOfArgs, i. Let Pk be ! ToString(𝔽(k)). ii. Let itemK be +/// values[k]. iii. Perform ! CreateDataPropertyOrThrow(array, Pk, itemK). +/// iv. Set k to k + 1. e. (Assert: The mathematical value of array's +/// "length" property is numberOfArgs.) f. Return array. +fn array_constructor(vm: &mut Vm, _this: Value, args: &[Value]) -> Result { + let nt = vm.new_target(); + let new_target = if nt == Value::UNDEFINED { + vm.active_function() + } else { + nt + }; + // GetPrototypeFromConstructor, §10.1.14†. + let proto = vm.get_named(new_target, "prototype")?; + let proto = if vm.heap().is_object(proto) { + proto + } else { + vm.array_prototype() + }; + match args { + [] => vm.array_create(0.0, Some(proto)), + [len] => { + let array = vm.array_create(0.0, Some(proto))?; + let int_len = if let Some(n) = crate::util::as_number(*len) { + let u = clazel_js_vm::numeric::to_uint32(clazel_js_vm::numeric::narrow(n)); + if f64::from(u) != n { + return Err(vm.range_error("Invalid array length")); + } + f64::from(u) + } else { + create_at(vm, array, 0.0, *len)?; + 1.0 + }; + set_length(vm, array, int_len)?; + Ok(array) + } + _ => { + let array = vm.array_create(args.len() as f64, Some(proto))?; + for (k, item) in args.iter().enumerate() { + create_at(vm, array, k as f64, *item)?; + } + Ok(array) + } + } +} + +/// `Array.isArray ( arg )`, §23.1.2.2†: Return ? IsArray(arg) (§7.2.2†). +fn is_array(vm: &mut Vm, _this: Value, args: &[Value]) -> Result { + Ok(Value::boolean(vm.is_array(arg(args, 0)))) +} + +/// `Array.of ( ...items )`, §23.1.2.3†: +/// 1. Let len be the number of elements in items. +/// 2. Let lenNumber be 𝔽(len). +/// 3. Let C be the this value. +/// 4. If IsConstructor(C) is true, then a. Let A be ? Construct(C, « +/// lenNumber »). +/// 5. Else, a. Let A be ? ArrayCreate(len). +/// 6. Let k be 0. +/// 7. Repeat, while k < len, a. Let kValue be items[k]. b. Let Pk be ! +/// ToString(𝔽(k)). c. Perform ? CreateDataPropertyOrThrow(A, Pk, kValue). +/// d. Set k to k + 1. +/// 8. Perform ? Set(A, "length", lenNumber, true). +/// 9. Return A. +fn array_of(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let len = args.len() as f64; + let a = if vm.is_constructor(this) { + vm.construct_value(this, &[number(len)])? + } else { + vm.array_create(len, None)? + }; + for (k, v) in args.iter().enumerate() { + create_at(vm, a, k as f64, *v)?; + } + set_length(vm, a, len)?; + Ok(a) +} + +// --------------------------------------------------------------------- +// Mutators +// --------------------------------------------------------------------- + +/// `Array.prototype.push ( ...items )`, §23.1.3.23†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. Let argCount be the number of elements in items. +/// 4. If len + argCount > 2^53 - 1, throw a TypeError exception. +/// 5. For each element E of items, do a. Perform ? Set(O, ! ToString(𝔽(len)), +/// E, true). b. Set len to len + 1. +/// 6. Perform ? Set(O, "length", 𝔽(len), true). +/// 7. Return 𝔽(len). +fn push(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let mut len = length_of(vm, o)?; + if len + args.len() as f64 > MAX_SAFE { + return Err(vm.type_error("Pushing elements past 2^53-1 length")); + } + for e in args { + set_at(vm, o, len, *e)?; + len += 1.0; + } + set_length(vm, o, len)?; + Ok(number(len)) +} + +/// `Array.prototype.pop ( )`, §23.1.3.22†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If len = 0, then a. Perform ? Set(O, "length", +0𝔽, true). b. Return +/// undefined. +/// 4. Else, a. (Assert: len > 0.) b. Let newLen be 𝔽(len - 1). c. Let index +/// be ! ToString(newLen). d. Let element be ? Get(O, index). e. Perform ? +/// DeletePropertyOrThrow(O, index). f. Perform ? Set(O, "length", newLen, +/// true). g. Return element. +fn pop(vm: &mut Vm, this: Value, _args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + if len == 0.0 { + set_length(vm, o, 0.0)?; + return Ok(Value::UNDEFINED); + } + let new_len = len - 1.0; + let element = get_at(vm, o, new_len)?; + delete_at(vm, o, new_len)?; + set_length(vm, o, new_len)?; + Ok(element) +} + +/// `Array.prototype.shift ( )`, §23.1.3.27†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If len = 0, then a. Perform ? Set(O, "length", +0𝔽, true). b. Return +/// undefined. +/// 4. Let first be ? Get(O, "0"). +/// 5. Let k be 1. +/// 6. Repeat, while k < len, a. Let from be ! ToString(𝔽(k)). b. Let to be ! +/// ToString(𝔽(k - 1)). c. Let fromPresent be ? HasProperty(O, from). d. If +/// fromPresent is true, then i. Let fromVal be ? Get(O, from). ii. Perform +/// ? Set(O, to, fromVal, true). e. Else, i. (Assert: fromPresent is false.) +/// ii. Perform ? DeletePropertyOrThrow(O, to). f. Set k to k + 1. +/// 7. Perform ? DeletePropertyOrThrow(O, ! ToString(𝔽(len - 1))). +/// 8. Perform ? Set(O, "length", 𝔽(len - 1), true). +/// 9. Return first. +fn shift(vm: &mut Vm, this: Value, _args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + if len == 0.0 { + set_length(vm, o, 0.0)?; + return Ok(Value::UNDEFINED); + } + let first = get_at(vm, o, 0.0)?; + let mut k = 1.0; + while k < len { + vm.charge_step()?; + if has_at(vm, o, k)? { + let v = get_at(vm, o, k)?; + set_at(vm, o, k - 1.0, v)?; + } else { + delete_at(vm, o, k - 1.0)?; + } + k += 1.0; + } + delete_at(vm, o, len - 1.0)?; + set_length(vm, o, len - 1.0)?; + Ok(first) +} + +/// `Array.prototype.unshift ( ...items )`, §23.1.3.34†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. Let argCount be the number of elements in items. +/// 4. If argCount > 0, then a. If len + argCount > 2^53 - 1, throw a +/// TypeError exception. b. Let k be len. c. Repeat, while k > 0, i. Let +/// from be ! ToString(𝔽(k - 1)). ii. Let to be ! ToString(𝔽(k + argCount - +/// 1)). iii. Let fromPresent be ? HasProperty(O, from). iv. If fromPresent +/// is true, then 1. Let fromValue be ? Get(O, from). 2. Perform ? Set(O, +/// to, fromValue, true). v. Else, 1. Perform ? DeletePropertyOrThrow(O, +/// to). vi. Set k to k - 1. d. Let j be +0𝔽. e. For each element E of +/// items, do i. Perform ? Set(O, ! ToString(j), E, true). ii. Set j to j + +/// 1𝔽. +/// 5. Perform ? Set(O, "length", 𝔽(len + argCount), true). +/// 6. Return 𝔽(len + argCount). +fn unshift(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let argc = args.len() as f64; + if argc > 0.0 { + if len + argc > MAX_SAFE { + return Err(vm.type_error("Invalid array length")); + } + let mut k = len; + while k > 0.0 { + vm.charge_step()?; + if has_at(vm, o, k - 1.0)? { + let v = get_at(vm, o, k - 1.0)?; + set_at(vm, o, k + argc - 1.0, v)?; + } else { + delete_at(vm, o, k + argc - 1.0)?; + } + k -= 1.0; + } + for (j, e) in args.iter().enumerate() { + set_at(vm, o, j as f64, *e)?; + } + } + set_length(vm, o, len + argc)?; + Ok(number(len + argc)) +} + +/// `Array.prototype.splice ( start, deleteCount, ...items )`, §23.1.3.31†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. Let relativeStart be ? ToIntegerOrInfinity(start). +/// 4. to 6. Let actualStart be len clamped as `relative`. +/// 7. Let itemCount be the number of elements in items. +/// 8. If start is not present, then a. Let actualDeleteCount be 0. +/// 9. Else if deleteCount is not present, then a. Let actualDeleteCount be +/// len - actualStart. +/// 10. Else, a. Let dc be ? ToIntegerOrInfinity(deleteCount). b. Let +/// actualDeleteCount be the result of clamping dc between 0 and len - +/// actualStart. +/// 11. If len + itemCount - actualDeleteCount > 2^53 - 1, throw a TypeError +/// exception. +/// 12. Let A be ? ArraySpeciesCreate(O, actualDeleteCount). +/// 13. Let k be 0. +/// 14. Repeat, while k < actualDeleteCount, a. Let from be ! ToString(𝔽(actualStart +/// + k)). b. If ? HasProperty(O, from) is true, then i. Let fromValue be ? +/// Get(O, from). ii. Perform ? CreateDataPropertyOrThrow(A, ! ToString(𝔽(k)), +/// fromValue). c. Set k to k + 1. +/// 15. Perform ? Set(A, "length", 𝔽(actualDeleteCount), true). +/// 16. If itemCount < actualDeleteCount, then a. Set k to actualStart. b. +/// Repeat, while k < (len - actualDeleteCount), i. from is k + +/// actualDeleteCount, ii. to is k + itemCount, iii. if HasProperty(from) +/// Set(to, Get(from)), else DeletePropertyOrThrow(to), v. Set k to k + 1. +/// c. Set k to len. d. Repeat, while k > (len - actualDeleteCount + +/// itemCount), i. Perform ? DeletePropertyOrThrow(O, ! ToString(𝔽(k - +/// 1))). ii. Set k to k - 1. +/// 17. Else if itemCount > actualDeleteCount, then a. Set k to (len - +/// actualDeleteCount). b. Repeat, while k > actualStart, i. from is k + +/// actualDeleteCount - 1, ii. to is k + itemCount - 1, iii. as in step +/// 16.b.iii, v. Set k to k - 1. +/// 18. Set k to actualStart. +/// 19. For each element E of items, do a. Perform ? Set(O, ! ToString(𝔽(k)), E, +/// true). b. Set k to k + 1. +/// 20. Perform ? Set(O, "length", 𝔽(len - actualDeleteCount + itemCount), +/// true). +/// 21. Return A. +fn splice(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let actual_start = relative(vm, arg(args, 0), len)?; + let items: &[Value] = args.get(2..).unwrap_or(&[]); + let item_count = items.len() as f64; + let actual_delete_count = match args.len() { + 0 => 0.0, + 1 => len - actual_start, + _ => { + let dc = to_integer_or_infinity(vm, arg(args, 1))?; + dc.clamp(0.0, len - actual_start) + } + }; + if len + item_count - actual_delete_count > MAX_SAFE { + return Err(vm.type_error("Invalid array length")); + } + let a = species_create(vm, o, actual_delete_count)?; + let mut k = 0.0; + while k < actual_delete_count { + vm.charge_step()?; + if has_at(vm, o, actual_start + k)? { + let v = get_at(vm, o, actual_start + k)?; + create_at(vm, a, k, v)?; + } + k += 1.0; + } + set_length(vm, a, actual_delete_count)?; + let move_one = |vm: &mut Vm, from: f64, to: f64| -> Result<(), Abrupt> { + vm.charge_step()?; + if has_at(vm, o, from)? { + let v = get_at(vm, o, from)?; + set_at(vm, o, to, v) + } else { + delete_at(vm, o, to) + } + }; + if item_count < actual_delete_count { + let mut k = actual_start; + while k < len - actual_delete_count { + move_one(vm, k + actual_delete_count, k + item_count)?; + k += 1.0; + } + let mut k = len; + while k > len - actual_delete_count + item_count { + delete_at(vm, o, k - 1.0)?; + k -= 1.0; + } + } else if item_count > actual_delete_count { + let mut k = len - actual_delete_count; + while k > actual_start { + move_one(vm, k + actual_delete_count - 1.0, k + item_count - 1.0)?; + k -= 1.0; + } + } + for (i, e) in items.iter().enumerate() { + set_at(vm, o, actual_start + i as f64, *e)?; + } + set_length(vm, o, len - actual_delete_count + item_count)?; + Ok(a) +} + +/// `Array.prototype.reverse ( )`, §23.1.3.26†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. Let middle be floor(len / 2). +/// 4. Let lower be 0. +/// 5. Repeat, while lower ≠ middle, a. Let upper be len - lower - 1. b. Let +/// upperP be ! ToString(𝔽(upper)). c. Let lowerP be ! ToString(𝔽(lower)). +/// d. Let lowerExists be ? HasProperty(O, lowerP). e. If lowerExists is +/// true, then i. Let lowerValue be ? Get(O, lowerP). f. Let upperExists be +/// ? HasProperty(O, upperP). g. If upperExists is true, then i. Let +/// upperValue be ? Get(O, upperP). h. If lowerExists is true and +/// upperExists is true, then i. Perform ? Set(O, lowerP, upperValue, +/// true). ii. Perform ? Set(O, upperP, lowerValue, true). i. Else if +/// lowerExists is false and upperExists is true, then i. Perform ? Set(O, +/// lowerP, upperValue, true). ii. Perform ? DeletePropertyOrThrow(O, +/// upperP). j. Else if lowerExists is true and upperExists is false, then +/// i. Perform ? DeletePropertyOrThrow(O, lowerP). ii. Perform ? Set(O, +/// upperP, lowerValue, true). k. Else, (neither exists) no action. l. Set +/// lower to lower + 1. +/// 6. Return O. +fn reverse(vm: &mut Vm, this: Value, _args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let middle = (len / 2.0).floor(); + let mut lower = 0.0; + while lower != middle { + vm.charge_step()?; + let upper = len - lower - 1.0; + let lower_exists = has_at(vm, o, lower)?; + let lower_value = if lower_exists { + get_at(vm, o, lower)? + } else { + Value::UNDEFINED + }; + let upper_exists = has_at(vm, o, upper)?; + let upper_value = if upper_exists { + get_at(vm, o, upper)? + } else { + Value::UNDEFINED + }; + match (lower_exists, upper_exists) { + (true, true) => { + set_at(vm, o, lower, upper_value)?; + set_at(vm, o, upper, lower_value)?; + } + (false, true) => { + set_at(vm, o, lower, upper_value)?; + delete_at(vm, o, upper)?; + } + (true, false) => { + delete_at(vm, o, lower)?; + set_at(vm, o, upper, lower_value)?; + } + (false, false) => {} + } + lower += 1.0; + } + Ok(o) +} + +/// `Array.prototype.fill ( value [ , start [ , end ] ] )`, §23.1.3.7†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. to 5. Let k be the start, clamped as `relative`. +/// 6. to 8. Let final be the end (len if undefined), clamped. +/// 9. Repeat, while k < final, a. Let Pk be ! ToString(𝔽(k)). b. Perform ? +/// Set(O, Pk, value, true). c. Set k to k + 1. +/// 10. Return O. +fn fill(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let mut k = relative(vm, arg(args, 1), len)?; + let fin = relative_end(vm, arg(args, 2), len)?; + while k < fin { + vm.charge_step()?; + set_at(vm, o, k, arg(args, 0))?; + k += 1.0; + } + Ok(o) +} + +// --------------------------------------------------------------------- +// Accessors +// --------------------------------------------------------------------- + +/// `Array.prototype.slice ( start, end )`, §23.1.3.28†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. to 5. Let k be the start, clamped as `relative`. +/// 6. to 8. Let final be the end (len if undefined), clamped. +/// 9. Let count be max(final - k, 0). +/// 10. Let A be ? ArraySpeciesCreate(O, count). +/// 11. Let n be 0. +/// 12. Repeat, while k < final, a. Let Pk be ! ToString(𝔽(k)). b. Let kPresent +/// be ? HasProperty(O, Pk). c. If kPresent is true, then i. Let kValue be +/// ? Get(O, Pk). ii. Perform ? CreateDataPropertyOrThrow(A, ! +/// ToString(𝔽(n)), kValue). d. Set k to k + 1. e. Set n to n + 1. +/// 13. Perform ? Set(A, "length", 𝔽(n), true). +/// 14. Return A. +fn slice(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let mut k = relative(vm, arg(args, 0), len)?; + let fin = relative_end(vm, arg(args, 1), len)?; + let count = (fin - k).max(0.0); + let a = species_create(vm, o, count)?; + let mut n = 0.0; + while k < fin { + vm.charge_step()?; + if has_at(vm, o, k)? { + let v = get_at(vm, o, k)?; + create_at(vm, a, n, v)?; + } + k += 1.0; + n += 1.0; + } + set_length(vm, a, n)?; + Ok(a) +} + +/// `Array.prototype.concat ( ...items )`, §23.1.3.2†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let A be ? ArraySpeciesCreate(O, 0). +/// 3. Let n be 0. +/// 4. Prepend O to items. +/// 5. For each element E of items, do a. Let spreadable be ? +/// IsConcatSpreadable(E) (§23.1.3.2.1†: if E is not an Object, false; (the +/// `@@isConcatSpreadable` lookup is not consulted: no Symbols;) else +/// IsArray(E)). b. If spreadable is true, then i. Let k be 0. ii. Let len +/// be ? LengthOfArrayLike(E). iii. If n + len > 2^53 - 1, throw a +/// TypeError exception. iv. Repeat, while k < len, 1. Let P be ! +/// ToString(𝔽(k)). 2. Let exists be ? HasProperty(E, P). 3. If exists is +/// true, then a. Let subElement be ? Get(E, P). b. Perform ? +/// CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), subElement). 4. Set n to +/// n + 1. 5. Set k to k + 1. c. Else, i. NOTE: E is added as a single +/// item rather than spread. ii. If n ≥ 2^53 - 1, throw a TypeError +/// exception. iii. Perform ? CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), +/// E). iv. Set n to n + 1. +/// 6. Perform ? Set(A, "length", 𝔽(n), true). +/// 7. Return A. +fn concat(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let a = species_create(vm, o, 0.0)?; + let mut n = 0.0; + let mut items = vec![o]; + items.extend_from_slice(args); + for e in items { + if vm.is_array(e) { + let len = length_of(vm, e)?; + if n + len > MAX_SAFE { + return Err(vm.type_error("Invalid array length")); + } + let mut k = 0.0; + while k < len { + vm.charge_step()?; + if has_at(vm, e, k)? { + let v = get_at(vm, e, k)?; + create_at(vm, a, n, v)?; + } + n += 1.0; + k += 1.0; + } + } else { + if n >= MAX_SAFE { + return Err(vm.type_error("Invalid array length")); + } + create_at(vm, a, n, e)?; + n += 1.0; + } + } + set_length(vm, a, n)?; + Ok(a) +} + +/// `Array.prototype.join ( separator )`, §23.1.3.18†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If separator is undefined, let sep be ",". +/// 4. Else, let sep be ? ToString(separator). +/// 5. Let R be the empty String. +/// 6. Let k be 0. +/// 7. Repeat, while k < len, a. If k > 0, set R to the string-concatenation of +/// R and sep. b. Let element be ? Get(O, ! ToString(𝔽(k))). c. If element +/// is either undefined or null, let next be the empty String; otherwise, +/// let next be ? ToString(element). d. Set R to the string-concatenation of +/// R and next. e. Set k to k + 1. +/// 8. Return R. +fn join(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let sep: Vec = if arg(args, 0) == Value::UNDEFINED { + vec![u16::from(b',')] + } else { + vm.to_js_string(arg(args, 0))?.units().collect() + }; + let mut r: Vec = Vec::new(); + let mut k = 0.0; + while k < len { + vm.charge_step()?; + if k > 0.0 { + r.extend_from_slice(&sep); + } + let element = get_at(vm, o, k)?; + if element != Value::UNDEFINED && element != Value::NULL { + r.extend(vm.to_js_string(element)?.units()); + } + k += 1.0; + } + let s = JsString::from_units(&r).map_err(|_| Abrupt::OutOfMemory)?; + js_string(vm, s) +} + +/// `Array.prototype.toString ( )`, §23.1.3.33†: +/// 1. Let array be ? ToObject(this value). +/// 2. Let func be ? Get(array, "join"). +/// 3. If IsCallable(func) is false, then a. Set func to the intrinsic +/// function %Object.prototype.toString%. +/// 4. Return ? Call(func, array). +fn to_string(vm: &mut Vm, this: Value, _args: &[Value]) -> Result { + let array = vm.to_object(this)?; + let func = vm.get_named(array, "join")?; + let func = if vm.heap().is_callable(func) { + func + } else { + let op = vm.intrinsic(Intrinsic::ObjectPrototype); + vm.get_named(op, "toString")? + }; + vm.call(func, array, &[]) +} + +/// `Array.prototype.indexOf ( searchElement [ , fromIndex ] )`, §23.1.3.17†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If len = 0, return -1𝔽. +/// 4. Let n be ? ToIntegerOrInfinity(fromIndex). +/// 5. (Assert: If fromIndex is undefined, then n is 0.) +/// 6. If n = +∞, return -1𝔽. +/// 7. Else if n = -∞, set n to 0. +/// 8. If n ≥ 0, then a. Let k be n. +/// 9. Else, a. Let k be len + n. b. If k < 0, set k to 0. +/// 10. Repeat, while k < len, a. Let kPresent be ? HasProperty(O, ! +/// ToString(𝔽(k))). b. If kPresent is true, then i. Let elementK be ? +/// Get(O, ! ToString(𝔽(k))). ii. If IsStrictlyEqual(searchElement, +/// elementK) is true, return 𝔽(k). c. Set k to k + 1. +/// 11. Return -1𝔽. +fn index_of(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + if len == 0.0 { + return Ok(Value::int32(-1)); + } + let n = to_integer_or_infinity(vm, arg(args, 1))?; + if n == f64::INFINITY { + return Ok(Value::int32(-1)); + } + let mut k = if n == f64::NEG_INFINITY { + 0.0 + } else if n >= 0.0 { + n + } else { + (len + n).max(0.0) + }; + while k < len { + vm.charge_step()?; + if has_at(vm, o, k)? { + let e = get_at(vm, o, k)?; + if vm.strict_equals(arg(args, 0), e) { + return Ok(number(k)); + } + } + k += 1.0; + } + Ok(Value::int32(-1)) +} + +/// `Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )`, +/// §23.1.3.20†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If len = 0, return -1𝔽. +/// 4. If fromIndex is present, let n be ? ToIntegerOrInfinity(fromIndex); else +/// let n be len - 1. +/// 5. If n = -∞, return -1𝔽. +/// 6. If n ≥ 0, then a. Let k be min(n, len - 1). +/// 7. Else, a. Let k be len + n. +/// 8. Repeat, while k ≥ 0, a. Let kPresent be ? HasProperty(O, ! ToString(𝔽(k))). +/// b. If kPresent is true, then i. Let elementK be ? Get(O, ! ToString(𝔽(k))). +/// ii. If IsStrictlyEqual(searchElement, elementK) is true, return 𝔽(k). +/// c. Set k to k - 1. +/// 9. Return -1𝔽. +fn last_index_of(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + if len == 0.0 { + return Ok(Value::int32(-1)); + } + let n = if args.len() > 1 { + to_integer_or_infinity(vm, arg(args, 1))? + } else { + len - 1.0 + }; + if n == f64::NEG_INFINITY { + return Ok(Value::int32(-1)); + } + let mut k = if n >= 0.0 { n.min(len - 1.0) } else { len + n }; + while k >= 0.0 { + vm.charge_step()?; + if has_at(vm, o, k)? { + let e = get_at(vm, o, k)?; + if vm.strict_equals(arg(args, 0), e) { + return Ok(number(k)); + } + } + k -= 1.0; + } + Ok(Value::int32(-1)) +} + +/// `Array.prototype.includes ( searchElement [ , fromIndex ] )`, §23.1.3.16†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If len = 0, return false. +/// 4. Let n be ? ToIntegerOrInfinity(fromIndex). +/// 5. (Assert: If fromIndex is undefined, then n is 0.) +/// 6. If n = +∞, return false. +/// 7. Else if n = -∞, set n to 0. +/// 8. If n ≥ 0, then a. Let k be n. +/// 9. Else, a. Let k be len + n. b. If k < 0, set k to 0. +/// 10. Repeat, while k < len, a. Let elementK be ? Get(O, ! ToString(𝔽(k))). +/// b. If SameValueZero(searchElement, elementK) is true, return true. c. +/// Set k to k + 1. +/// 11. Return false. +fn includes(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + if len == 0.0 { + return Ok(Value::FALSE); + } + let n = to_integer_or_infinity(vm, arg(args, 1))?; + if n == f64::INFINITY { + return Ok(Value::FALSE); + } + let mut k = if n == f64::NEG_INFINITY { + 0.0 + } else if n >= 0.0 { + n + } else { + (len + n).max(0.0) + }; + while k < len { + vm.charge_step()?; + let e = get_at(vm, o, k)?; + if same_value_zero(vm, arg(args, 0), e) { + return Ok(Value::TRUE); + } + k += 1.0; + } + Ok(Value::FALSE) +} + +// --------------------------------------------------------------------- +// Callback methods +// --------------------------------------------------------------------- + +/// The callback of one element: `Call(callbackfn, thisArg, « kValue, 𝔽(k), O +/// »)`. +fn call3(vm: &mut Vm, f: Value, this_arg: Value, v: Value, k: f64, o: Value) -> Result { + vm.call(f, this_arg, &[v, number(k), o]) +} + +/// `Array.prototype.forEach ( callbackfn [ , thisArg ] )`, §23.1.3.15†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If IsCallable(callbackfn) is false, throw a TypeError exception. +/// 4. Let k be 0. +/// 5. Repeat, while k < len, a. Let Pk be ! ToString(𝔽(k)). b. Let kPresent be +/// ? HasProperty(O, Pk). c. If kPresent is true, then i. Let kValue be ? +/// Get(O, Pk). ii. Perform ? Call(callbackfn, thisArg, « kValue, 𝔽(k), O +/// »). d. Set k to k + 1. +/// 6. Return undefined. +fn for_each(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let f = callable(vm, arg(args, 0))?; + let mut k = 0.0; + while k < len { + vm.charge_step()?; + if has_at(vm, o, k)? { + let v = get_at(vm, o, k)?; + call3(vm, f, arg(args, 1), v, k, o)?; + } + k += 1.0; + } + Ok(Value::UNDEFINED) +} + +/// `Array.prototype.map ( callbackfn [ , thisArg ] )`, §23.1.3.21†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If IsCallable(callbackfn) is false, throw a TypeError exception. +/// 4. Let A be ? ArraySpeciesCreate(O, len). +/// 5. Let k be 0. +/// 6. Repeat, while k < len, a. Let Pk be ! ToString(𝔽(k)). b. Let kPresent be +/// ? HasProperty(O, Pk). c. If kPresent is true, then i. Let kValue be ? +/// Get(O, Pk). ii. Let mappedValue be ? Call(callbackfn, thisArg, « kValue, +/// 𝔽(k), O »). iii. Perform ? CreateDataPropertyOrThrow(A, Pk, +/// mappedValue). d. Set k to k + 1. +/// 7. Return A. +fn map(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let f = callable(vm, arg(args, 0))?; + let a = species_create(vm, o, len)?; + let mut k = 0.0; + while k < len { + vm.charge_step()?; + if has_at(vm, o, k)? { + let v = get_at(vm, o, k)?; + let mapped = call3(vm, f, arg(args, 1), v, k, o)?; + create_at(vm, a, k, mapped)?; + } + k += 1.0; + } + Ok(a) +} + +/// `Array.prototype.filter ( callbackfn [ , thisArg ] )`, §23.1.3.8†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If IsCallable(callbackfn) is false, throw a TypeError exception. +/// 4. Let A be ? ArraySpeciesCreate(O, 0). +/// 5. Let k be 0. +/// 6. Let to be 0. +/// 7. Repeat, while k < len, a. Let Pk be ! ToString(𝔽(k)). b. Let kPresent be +/// ? HasProperty(O, Pk). c. If kPresent is true, then i. Let kValue be ? +/// Get(O, Pk). ii. Let selected be ToBoolean(? Call(callbackfn, thisArg, « +/// kValue, 𝔽(k), O »)). iii. If selected is true, then 1. Perform ? +/// CreateDataPropertyOrThrow(A, ! ToString(𝔽(to)), kValue). 2. Set to to to +/// + 1. d. Set k to k + 1. +/// 8. Return A. +fn filter(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let f = callable(vm, arg(args, 0))?; + let a = species_create(vm, o, 0.0)?; + let (mut k, mut to) = (0.0, 0.0); + while k < len { + vm.charge_step()?; + if has_at(vm, o, k)? { + let v = get_at(vm, o, k)?; + let r = call3(vm, f, arg(args, 1), v, k, o)?; + if vm.to_boolean(r) { + create_at(vm, a, to, v)?; + to += 1.0; + } + } + k += 1.0; + } + Ok(a) +} + +/// `Array.prototype.some ( callbackfn [ , thisArg ] )`, §23.1.3.29†, and +/// `Array.prototype.every`, §23.1.3.6†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If IsCallable(callbackfn) is false, throw a TypeError exception. +/// 4. Let k be 0. +/// 5. Repeat, while k < len, a. Let Pk be ! ToString(𝔽(k)). b. Let kPresent be +/// ? HasProperty(O, Pk). c. If kPresent is true, then i. Let kValue be ? +/// Get(O, Pk). ii. Let testResult be ToBoolean(? Call(callbackfn, thisArg, +/// « kValue, 𝔽(k), O »)). iii. (`some`:) If testResult is true, return +/// true. (`every`:) If testResult is false, return false. d. Set k to k + +/// 1. +/// 6. Return false (`some`) or true (`every`). +fn some_or_every(vm: &mut Vm, this: Value, args: &[Value], is_some: bool) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let f = callable(vm, arg(args, 0))?; + let mut k = 0.0; + while k < len { + vm.charge_step()?; + if has_at(vm, o, k)? { + let v = get_at(vm, o, k)?; + let r = call3(vm, f, arg(args, 1), v, k, o)?; + if vm.to_boolean(r) == is_some { + return Ok(Value::boolean(is_some)); + } + } + k += 1.0; + } + Ok(Value::boolean(!is_some)) +} + +fn some(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + some_or_every(vm, this, args, true) +} + +fn every(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + some_or_every(vm, this, args, false) +} + +/// `Array.prototype.reduce ( callbackfn [ , initialValue ] )`, §23.1.3.24†, +/// and `reduceRight`, §23.1.3.25†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. If IsCallable(callbackfn) is false, throw a TypeError exception. +/// 4. If len = 0 and initialValue is not present, throw a TypeError exception. +/// 5. Let k be 0 (`reduceRight`: len - 1). +/// 6. Let accumulator be undefined. +/// 7. If initialValue is present, then a. Set accumulator to initialValue. +/// 8. Else, a. Let kPresent be false. b. Repeat, while kPresent is false and k +/// < len (k ≥ 0), i. Let Pk be ! ToString(𝔽(k)). ii. Set kPresent to ? +/// HasProperty(O, Pk). iii. If kPresent is true, then 1. Set accumulator to +/// ? Get(O, Pk). iv. Set k to k + 1 (k - 1). c. If kPresent is false, throw +/// a TypeError exception. +/// 9. Repeat, while k < len (k ≥ 0), a. Let Pk be ! ToString(𝔽(k)). b. Let +/// kPresent be ? HasProperty(O, Pk). c. If kPresent is true, then i. Let +/// kValue be ? Get(O, Pk). ii. Set accumulator to ? Call(callbackfn, +/// undefined, « accumulator, kValue, 𝔽(k), O »). d. Set k to k + 1 (k - 1). +/// 10. Return accumulator. +fn reduce_impl(vm: &mut Vm, this: Value, args: &[Value], right: bool) -> Result { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let f = callable(vm, arg(args, 0))?; + if len == 0.0 && args.len() < 2 { + return Err(vm.type_error("Reduce of empty array with no initial value")); + } + let (mut k, step) = if right { (len - 1.0, -1.0) } else { (0.0, 1.0) }; + let in_range = |k: f64| if right { k >= 0.0 } else { k < len }; + let mut acc = Value::UNDEFINED; + if args.len() >= 2 { + acc = arg(args, 1); + } else { + let mut present = false; + while !present && in_range(k) { + vm.charge_step()?; + present = has_at(vm, o, k)?; + if present { + acc = get_at(vm, o, k)?; + } + k += step; + } + if !present { + return Err(vm.type_error("Reduce of empty array with no initial value")); + } + } + while in_range(k) { + vm.charge_step()?; + if has_at(vm, o, k)? { + let v = get_at(vm, o, k)?; + acc = vm.call(f, Value::UNDEFINED, &[acc, v, number(k), o])?; + } + k += step; + } + Ok(acc) +} + +fn reduce(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + reduce_impl(vm, this, args, false) +} + +fn reduce_right(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + reduce_impl(vm, this, args, true) +} + +/// `Array.prototype.find ( predicate [ , thisArg ] )`, §23.1.3.9†, and +/// `findIndex`, §23.1.3.10†, over FindViaPredicate ( O, len, direction, +/// predicate, thisArg ), §23.1.3.9.1†: +/// 1. Let O be ? ToObject(this value). +/// 2. Let len be ? LengthOfArrayLike(O). +/// 3. Let findRec be ? FindViaPredicate(O, len, ascending, predicate, +/// thisArg). +/// 4. Return findRec.[[Value]] (`find`) or findRec.[[Index]] (`findIndex`). +/// +/// FindViaPredicate: +/// 1. If IsCallable(predicate) is false, throw a TypeError exception. +/// 2. If direction is ascending, let indices be a List of the integers in the +/// interval from 0 to len, exclusive, in ascending order. +/// 4. For each integer k of indices, do a. Let Pk be ! ToString(𝔽(k)). b. NOTE: +/// If O is a TypedArray, the following invocation of Get will return a +/// normal completion. c. Let kValue be ? Get(O, Pk). d. Let testResult be ? +/// Call(predicate, thisArg, « kValue, 𝔽(k), O »). e. If ToBoolean(testResult) +/// is true, return the Record { [[Index]]: 𝔽(k), [[Value]]: kValue }. +/// 5. Return the Record { [[Index]]: -1𝔽, [[Value]]: undefined }. +fn find_via_predicate(vm: &mut Vm, this: Value, args: &[Value]) -> Result<(f64, Value), Abrupt> { + let o = vm.to_object(this)?; + let len = length_of(vm, o)?; + let f = callable(vm, arg(args, 0))?; + let mut k = 0.0; + while k < len { + vm.charge_step()?; + let v = get_at(vm, o, k)?; + let r = call3(vm, f, arg(args, 1), v, k, o)?; + if vm.to_boolean(r) { + return Ok((k, v)); + } + k += 1.0; + } + Ok((-1.0, Value::UNDEFINED)) +} + +fn find(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + Ok(find_via_predicate(vm, this, args)?.1) +} + +fn find_index(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + Ok(number(find_via_predicate(vm, this, args)?.0)) +} + +// --------------------------------------------------------------------- +// sort +// --------------------------------------------------------------------- + +/// SortCompare ( x, y ), §23.1.3.30.2†, with the `comparefn` of the call: +/// 1. If x and y are both undefined, return +0𝔽. +/// 2. If x is undefined, return 1𝔽. +/// 3. If y is undefined, return -1𝔽. +/// 4. If comparefn is not undefined, then a. Let v be ? ToNumber(? Call(comparefn, +/// undefined, « x, y »)). b. If v is NaN, return +0𝔽. c. Return v. +/// 5. Let xString be ? ToString(x). +/// 6. Let yString be ? ToString(y). +/// 7. Let xSmaller be ! IsLessThan(xString, yString, true) (by code units). +/// 8. If xSmaller is true, return -1𝔽. +/// 9. Let ySmaller be ! IsLessThan(yString, xString, true). +/// 10. If ySmaller is true, return 1𝔽. +/// 11. Return +0𝔽. +fn sort_compare(vm: &mut Vm, cmp: Value, x: Value, y: Value) -> Result { + if x == Value::UNDEFINED && y == Value::UNDEFINED { + return Ok(0.0); + } + if x == Value::UNDEFINED { + return Ok(1.0); + } + if y == Value::UNDEFINED { + return Ok(-1.0); + } + if cmp != Value::UNDEFINED { + let r = vm.call(cmp, Value::UNDEFINED, &[x, y])?; + let v = vm.to_number(r)?; + return Ok(if v.is_nan() { 0.0 } else { v }); + } + let xs = vm.to_js_string(x)?; + let ys = vm.to_js_string(y)?; + Ok(match xs.units().cmp(ys.units()) { + std::cmp::Ordering::Less => -1.0, + std::cmp::Ordering::Greater => 1.0, + std::cmp::Ordering::Equal => 0.0, + }) +} + +/// A stable merge sort over `items` by `SortCompare` (the standard requires a +/// stable sort, §23.1.3.30† NOTE 2; an exception from the comparator ends it). +fn merge_sort(vm: &mut Vm, cmp: Value, items: Vec) -> Result, Abrupt> { + let n = items.len(); + if n < 2 { + return Ok(items); + } + let mut src = items; + let mut width = 1usize; + while width < n { + let mut dst: Vec = Vec::with_capacity(n); + let mut start = 0usize; + while start < n { + let mid = start.saturating_add(width).min(n); + let end = start.saturating_add(width.saturating_mul(2)).min(n); + let (mut i, mut j) = (start, mid); + while i < mid && j < end { + vm.charge_step()?; + let (l, r) = ( + *src.get(i).ok_or(Abrupt::Internal("sort index"))?, + *src.get(j).ok_or(Abrupt::Internal("sort index"))?, + ); + // Stable: the right one goes first only when it is smaller. + if sort_compare(vm, cmp, l, r)? > 0.0 { + dst.push(r); + j = j.saturating_add(1); + } else { + dst.push(l); + i = i.saturating_add(1); + } + } + while let Some(v) = src.get(i).filter(|_| i < mid) { + dst.push(*v); + i = i.saturating_add(1); + } + while let Some(v) = src.get(j).filter(|_| j < end) { + dst.push(*v); + j = j.saturating_add(1); + } + start = end; + } + src = dst; + width = width.saturating_mul(2); + } + Ok(src) +} + +/// `Array.prototype.sort ( comparefn )`, §23.1.3.30†: +/// 1. If comparefn is not undefined and IsCallable(comparefn) is false, throw +/// a TypeError exception. +/// 2. Let obj be ? ToObject(this value). +/// 3. Let len be ? LengthOfArrayLike(obj). +/// 4. Let SortCompare be a new Abstract Closure ... that performs +/// SortCompare(x, y) with comparefn. +/// 5. Let sortedList be ? SortIndexedProperties(obj, len, SortCompare, +/// skip-holes). +/// 6. Let itemCount be the number of elements in sortedList. +/// 7. Let j be 0. +/// 8. Repeat, while j < itemCount, a. Perform ? Set(obj, ! ToString(𝔽(j)), +/// sortedList[j], true). b. Set j to j + 1. +/// 9. NOTE: The call to SortIndexedProperties in step 5 uses skip-holes. The +/// remaining indices are deleted to preserve the number of holes that were +/// detected and excluded from the sort. +/// 10. Repeat, while j < len, a. Perform ? DeletePropertyOrThrow(obj, ! +/// ToString(𝔽(j))). b. Set j to j + 1. +/// 11. Return obj. +/// +/// SortIndexedProperties ( obj, len, SortCompare, holes ), §23.1.3.30.1†: +/// 1. Let items be a new empty List. +/// 2. Let k be 0. +/// 3. Repeat, while k < len, a. Let Pk be ! ToString(𝔽(k)). b. If holes is +/// skip-holes, then i. Let kRead be ? HasProperty(obj, Pk). c. Else, (read-through-holes) +/// ... d. If kRead is true, then i. Let kValue be ? Get(obj, Pk). ii. +/// Append kValue to items. e. Set k to k + 1. +/// 4. Sort items using an implementation-defined sequence of calls to +/// SortCompare. If any call returns an abrupt completion, stop before +/// performing any further calls and return that Completion Record. (The +/// sort is stable.) +/// 5. Return items. +fn sort(vm: &mut Vm, this: Value, args: &[Value]) -> Result { + let cmp = arg(args, 0); + if cmp != Value::UNDEFINED && !vm.heap().is_callable(cmp) { + return Err(vm.type_error("The comparison function must be either a function or undefined")); + } + let obj = vm.to_object(this)?; + let len = length_of(vm, obj)?; + let mut items = Vec::new(); + let mut k = 0.0; + while k < len { + vm.charge_step()?; + if has_at(vm, obj, k)? { + items.push(get_at(vm, obj, k)?); + } + k += 1.0; + } + let sorted = merge_sort(vm, cmp, items)?; + let mut j = 0.0; + for v in &sorted { + set_at(vm, obj, j, *v)?; + j += 1.0; + } + while j < len { + vm.charge_step()?; + delete_at(vm, obj, j)?; + j += 1.0; + } + Ok(obj) +} diff --git a/crates/clazel-js-builtins/src/lib.rs b/crates/clazel-js-builtins/src/lib.rs index 45178f29..6480449c 100644 --- a/crates/clazel-js-builtins/src/lib.rs +++ b/crates/clazel-js-builtins/src/lib.rs @@ -46,6 +46,7 @@ //! Tier: see `[package.metadata.clazel]` in `Cargo.toml` and //! `docs/VERIFICATION.md`. +pub mod array; pub mod boolean; pub mod error; pub mod function; @@ -66,6 +67,7 @@ use clazel_js_vm::interp::{Abrupt, Vm}; pub fn install(vm: &mut Vm) -> Result<(), Abrupt> { object::install(vm)?; function::install(vm)?; + array::install(vm)?; error::install(vm)?; boolean::install(vm)?; number::install(vm)?; diff --git a/crates/clazel-js-builtins/src/object.rs b/crates/clazel-js-builtins/src/object.rs index 35d2a352..bcada0db 100644 --- a/crates/clazel-js-builtins/src/object.rs +++ b/crates/clazel-js-builtins/src/object.rs @@ -4,12 +4,13 @@ use crate::util::{ arg, constructor, has_own_property, has_property, key, method, new_array_like, new_object_with, - same_value, string, + string, }; use clazel_js_heap::shape::Attrs; use clazel_js_heap::value::{Decoded, Value}; use clazel_js_vm::heap::ObjKind; use clazel_js_vm::interp::{Abrupt, Intrinsic, Vm}; +use clazel_js_vm::props::PropDesc; /// Installs `Object`, `Object.prototype` and their methods. /// @@ -62,7 +63,7 @@ fn has_own_property_fn(vm: &mut Vm, this: Value, args: &[Value]) -> Result Result "Function" } else { match vm.heap().obj(o).map(|o| o.kind) { + Some(ObjKind::Array) => "Array", Some(ObjKind::Error) => "Error", Some(ObjKind::Primitive(p)) => match p.decode() { Decoded::Bool(_) => "Boolean", @@ -258,73 +260,20 @@ fn define_property(vm: &mut Vm, _this: Value, args: &[Value]) -> Result Result<(), Abrupt> { - let current = vm.heap().find(obj, k)?.filter(|f| f.own); - let Some(cur) = current else { - let mut bits = 0; - for (flag, bit) in [ - (desc.writable, Attrs::WRITABLE), - (desc.enumerable, Attrs::ENUMERABLE), - (desc.configurable, Attrs::CONFIGURABLE), - ] { - if flag == Some(true) { - bits |= bit; - } - } - let v = desc.value.unwrap_or(Value::UNDEFINED); - return Ok(vm.heap_mut().define(obj, k, v, Attrs(bits))?); + let d = PropDesc { + value: desc.value, + writable: desc.writable, + enumerable: desc.enumerable, + configurable: desc.configurable, }; - let cur_value = vm - .heap() - .slot(cur.holder, cur.slot) - .ok_or(Abrupt::Internal("property slot"))?; - let flag = |bit: u8| cur.attrs.0 & bit != 0; - if !flag(Attrs::CONFIGURABLE) { - let bad = desc.configurable == Some(true) - || desc - .enumerable - .is_some_and(|e| e != flag(Attrs::ENUMERABLE)) - || (!flag(Attrs::WRITABLE) - && (desc.writable == Some(true) - || desc.value.is_some_and(|v| !same_value(vm, v, cur_value)))); - if bad { - let name = vm - .heap() - .key_string(k) - .map(clazel_js_heap::string::JsString::to_string_lossy) - .unwrap_or_default(); - return Err(vm.type_error(&format!("Cannot redefine property: {name}"))); - } - } - let mut bits = 0; - for (new, bit) in [ - (desc.writable, Attrs::WRITABLE), - (desc.enumerable, Attrs::ENUMERABLE), - (desc.configurable, Attrs::CONFIGURABLE), - ] { - if new.unwrap_or_else(|| flag(bit)) { - bits |= bit; - } - } - let v = desc.value.unwrap_or(cur_value); - Ok(vm.heap_mut().redefine(obj, k, v, Attrs(bits))?) + vm.define_property_or_throw(obj, k, &d) } diff --git a/crates/clazel-js-builtins/src/util.rs b/crates/clazel-js-builtins/src/util.rs index 0ed27ded..b3b17a5d 100644 --- a/crates/clazel-js-builtins/src/util.rs +++ b/crates/clazel-js-builtins/src/util.rs @@ -132,22 +132,12 @@ pub fn new_object_with(vm: &mut Vm, proto: Value, kind: ObjKind) -> Result Result { - let o = vm.new_object()?; - for (i, v) in items.iter().enumerate() { - define(vm, o, &i.to_string(), *v, Attrs::ALL)?; - } - let n = i32::try_from(items.len()).map_err(|_| Abrupt::OutOfMemory)?; - // An array's `length` is writable, not enumerable, not configurable. - define(vm, o, "length", Value::int32(n), Attrs(Attrs::WRITABLE))?; - Ok(o) + vm.create_array_from_list(items) } /// The Number a value is, if it is one. diff --git a/crates/clazel-js-builtins/tests/array.rs b/crates/clazel-js-builtins/tests/array.rs new file mode 100644 index 00000000..d54fad03 --- /dev/null +++ b/crates/clazel-js-builtins/tests/array.rs @@ -0,0 +1,425 @@ +//! Tests of arrays: the Array exotic object (§10.4.2†) and the `Array` +//! built-in, as small scripts run with the built-ins installed. Each +//! expectation is what ECMA-262 says, written by hand; the result is the +//! global `r` as its ToString. No files are read, so these run under Miri +//! too (with every fourth case, as the other built-in tests do). + +use clazel_js_syntax::exec::parse; +use clazel_js_syntax::spec::SourceGoal; +use clazel_js_vm::compile::compile_script; +use clazel_js_vm::interp::{Config, Vm}; + +fn cps(src: &str) -> Vec { + src.chars().map(u32::from).collect() +} + +fn config() -> Config { + if cfg!(miri) { + Config { + region_slots: 1 << 12, + heap_cells: 1 << 14, + } + } else { + Config::default() + } +} + +fn r_of(src: &str) -> Result { + let c = cps(src); + let ast = parse(&c, SourceGoal::Script).map_err(|_| format!("does not parse: {src}"))?; + let p = compile_script(&ast, &c).map_err(|e| format!("{src}: {e}"))?; + let mut vm = Vm::new(config()).map_err(|e| format!("{e:?}"))?; + clazel_js_builtins::install(&mut vm).map_err(|e| format!("install: {e:?}"))?; + let script = vm.load(&p).map_err(|e| format!("{e:?}"))?; + vm.set_budget(5_000_000); + vm.run(&script).map_err(|e| format!("{src}: {e:?}"))?; + let g = vm.global(); + let r = vm.get_named(g, "r").map_err(|e| format!("{e:?}"))?; + let s = vm.to_js_string(r).map_err(|e| format!("{src}: {e:?}"))?; + Ok(s.to_string_lossy()) +} + +fn check(cases: &[(&str, &str)]) -> Result<(), String> { + let stride = if cfg!(miri) { 4 } else { 1 }; + for (src, want) in cases.iter().step_by(stride) { + let got = r_of(src)?; + if got != *want { + return Err(format!("{src}: expected {want:?}, got {got:?}")); + } + } + Ok(()) +} + +#[test] +fn array_exotic_objects() -> Result<(), String> { + check(&[ + // §10.4.2.1 step 2.h: an index at or above `length` grows it. + ("var a = []; a[4] = 1; var r = a.length;", "5"), + ("var a = [1, 2, 3]; var r = a.length;", "3"), + ("var a = [1, , 3]; var r = a.length + ',' + (1 in a);", "3,false"), + ("var a = [1, 2, ,]; var r = a.length;", "3"), + // A key that is not a canonical index does not. + ("var a = []; a['01'] = 1; a.x = 2; var r = a.length;", "0"), + ( + "var a = []; a[4294967294] = 1; var r = a.length;", + "4294967295", + ), + ("var a = []; a[4294967295] = 1; var r = a.length;", "0"), + // ArraySetLength truncates, §10.4.2.4. + ( + "var a = [1, 2, 3, 4]; a.length = 2; var r = a + ',' + a.length;", + "1,2,2", + ), + ( + "var a = [1, 2]; a.length = 5; var r = a.length + ',' + (3 in a);", + "5,false", + ), + ( + "var a = [1, 2, 3]; a.length = 0; var r = a.length + ',' + (0 in a);", + "0,false", + ), + // Step 5: a RangeError for a length that is not a Uint32. + ( + "var r; try { [].length = -1; } catch (e) { r = e.name; }", + "RangeError", + ), + ( + "var r; try { [].length = 1.5; } catch (e) { r = e.name; }", + "RangeError", + ), + ("var a = []; a.length = '3'; var r = a.length;", "3"), + // A non-configurable element stops the truncation (step 16.b). + ( + "var a = [1, 2]; Object.defineProperty(a, 2, { value: 5 }); a.length = 0; var r = a.length + ',' + a[0] + ',' + a[2];", + "3,undefined,5", + ), + // `length` is not enumerable, writable, not configurable. + ( + "var a = [1]; var r = Object.keys(a).join() + '|' + a.hasOwnProperty('length');", + "0|true", + ), + ( + "var a = [1, 2]; Object.defineProperty(a, 'length', { writable: false }); a[2] = 3; var r = a.length + ',' + (2 in a);", + "2,false", + ), + ( + "'use strict'; var a = [1]; Object.defineProperty(a, 'length', { writable: false }); var r; try { a.push(2); } catch (e) { r = e.name + a.length; }", + "TypeError1", + ), + // Array.prototype is an array, Object.prototype.toString says so. + ( + "var r = Array.isArray(Array.prototype) + ',' + Object.prototype.toString.call([]);", + "true,[object Array]", + ), + ( + "var r = Array.isArray({ length: 0 }) + ',' + Array.isArray([]);", + "false,true", + ), + ("var r = [] instanceof Object;", "true"), + // Object.keys returns an array now. + ("var r = Array.isArray(Object.keys({ a: 1 }));", "true"), + ( + "var a = [3, 4]; var r = delete a[0]; r = r + ',' + a.length + ',' + (0 in a);", + "true,2,false", + ), + ]) +} + +#[test] +fn array_constructor_and_statics() -> Result<(), String> { + check(&[ + ("var r = new Array().length;", "0"), + ( + "var r = new Array(3).length + ',' + (0 in new Array(3));", + "3,false", + ), + ("var r = Array(1, 2, 3).join();", "1,2,3"), + ("var r = Array('a').join() + new Array('a').length;", "a1"), + ( + "var r; try { new Array(-1); } catch (e) { r = e.name; }", + "RangeError", + ), + ( + "var r; try { new Array(1.5); } catch (e) { r = e.name; }", + "RangeError", + ), + ("var r = new Array(4294967295).length;", "4294967295"), + ( + "var r = Array.of(7, 8, 9).join('-') + Array.of(3).length;", + "7-8-91", + ), + ("var r = Array.of().length;", "0"), + ( + "var r = Array.length + Array.name + Array.prototype.constructor.name;", + "1ArrayArray", + ), + ( + "var r = Array.prototype.push.length + Array.prototype.splice.length;", + "3", + ), + ("var r = Array.isArray(new Array(2));", "true"), + ]) +} + +#[test] +fn array_mutators() -> Result<(), String> { + check(&[ + ( + "var a = [1]; var n = a.push(2, 3); var r = n + ',' + a;", + "3,1,2,3", + ), + ( + "var a = [1, 2, 3]; var x = a.pop(); var r = x + ',' + a;", + "3,1,2", + ), + ("var a = []; var r = a.pop() + ',' + a.length;", "undefined,0"), + ( + "var a = [1, 2, 3]; var x = a.shift(); var r = x + ',' + a + ',' + a.length;", + "1,2,3,2", + ), + ( + "var a = [1, , 3]; a.shift(); var r = a.length + ',' + (0 in a) + ',' + a[1];", + "2,false,3", + ), + ( + "var a = [3]; var n = a.unshift(1, 2); var r = n + ',' + a;", + "3,1,2,3", + ), + ( + "var a = [1, 2, 3, 4, 5]; var d = a.splice(1, 2); var r = d + '|' + a;", + "2,3|1,4,5", + ), + ( + "var a = [1, 2, 3]; var d = a.splice(1, 0, 'x', 'y'); var r = d.length + '|' + a;", + "0|1,x,y,2,3", + ), + ( + "var a = [1, 2, 3]; var d = a.splice(1); var r = d + '|' + a;", + "2,3|1", + ), + ( + "var a = [1, 2, 3]; var d = a.splice(-1, 1, 9); var r = d + '|' + a;", + "3|1,2,9", + ), + ( + "var a = [1, 2, 3]; var d = a.splice(); var r = d.length + '|' + a;", + "0|1,2,3", + ), + ( + "var a = [1, 2, 3]; var d = a.splice(0, 3, 'a'); var r = d + '|' + a;", + "1,2,3|a", + ), + ("var a = [1, 2, 3]; a.reverse(); var r = a.join();", "3,2,1"), + ( + "var a = [1, 2, 3, 4]; a.reverse(); var r = a.join();", + "4,3,2,1", + ), + ( + "var a = [1, , 3]; a.reverse(); var r = a.join() + ',' + (1 in a);", + "3,,1,false", + ), + ( + "var a = [1, , 3, 4]; a.reverse(); var r = (2 in a) + ',' + a[3];", + "false,1", + ), + ( + "var a = [1, 2, 3, 4]; a.fill(0, 1, 3); var r = a.join();", + "1,0,0,4", + ), + ("var a = [1, 2, 3]; a.fill(7); var r = a.join();", "7,7,7"), + ( + "var a = [1, 2, 3]; a.fill(7, -1); var r = a.join();", + "1,2,7", + ), + // Generic: an array-like object. + ( + "var o = { length: 2, 0: 'a', 1: 'b' }; Array.prototype.push.call(o, 'c'); var r = o.length + o[2];", + "3c", + ), + ( + "var o = { length: 3, 0: 'a', 1: 'b', 2: 'c' }; Array.prototype.reverse.call(o); var r = o[0] + o[1] + o[2];", + "cba", + ), + ( + "var o = { length: 9007199254740991 }; var r; try { Array.prototype.push.call(o, 1); } catch (e) { r = e.name; }", + "TypeError", + ), + ]) +} + +#[test] +fn array_accessors() -> Result<(), String> { + check(&[ + ("var r = [1, 2, 3, 4].slice(1, 3).join();", "2,3"), + ("var r = [1, 2, 3, 4].slice(-2).join();", "3,4"), + ("var r = [1, 2, 3, 4].slice().join();", "1,2,3,4"), + ("var r = [1, 2, 3].slice(2, 1).length;", "0"), + ( + "var s = [1, , 3].slice(0); var r = s.length + ',' + (1 in s);", + "3,false", + ), + ("var r = [1, 2].concat([3, 4], 5, [[6]]).length;", "6"), + ("var r = [1].concat([2], [3, [4]]).join();", "1,2,3,4"), + ( + "var c = [1, , 3].concat([4]); var r = c.length + ',' + (1 in c);", + "4,false", + ), + ("var r = [1, 2, 3].join('-');", "1-2-3"), + ("var r = [1, null, undefined, 4].join();", "1,,,4"), + ("var r = [].join() + '|' + [5].join('x');", "|5"), + ("var r = [[1, 2], [3]].join(';');", "1,2;3"), + ("var r = String([1, [2, 3]]);", "1,2,3"), + ( + "var r = [1, 2, 3, 2].indexOf(2) + ',' + [1, 2, 3, 2].indexOf(2, 2) + ',' + [1].indexOf(5);", + "1,3,-1", + ), + ( + "var r = [1, 2, 3, 2].indexOf(2, -1) + ',' + [NaN].indexOf(NaN);", + "3,-1", + ), + ( + "var r = [1, 2, 3, 2].lastIndexOf(2) + ',' + [1, 2, 3, 2].lastIndexOf(2, 2) + ',' + [1].lastIndexOf(5);", + "3,1,-1", + ), + ("var r = [1, 2, 3].lastIndexOf(3, -2);", "-1"), + ( + "var r = [1, NaN].includes(NaN) + ',' + [1, 2].includes(3) + ',' + [1, 2].includes(1, 1);", + "true,false,false", + ), + ( + "var r = [, 1].includes(undefined) + ',' + [, 1].indexOf(undefined);", + "true,-1", + ), + ("var r = [0].includes(-0) + ',' + [-0].indexOf(0);", "true,0"), + ]) +} + +#[test] +fn array_callbacks() -> Result<(), String> { + check(&[ + ( + "var s = 0; [1, 2, 3].forEach(function (v) { s += v; }); var r = s;", + "6", + ), + ( + "var s = 0; [1, , 3].forEach(function (v) { s += 1; }); var r = s;", + "2", + ), + ( + "var o = {}; [1].forEach(function (v, i, a) { o.x = this === o && v === 1 && i === 0 && a.length === 1; }, o); var r = o.x;", + "true", + ), + ( + "var r = [1, 2, 3].map(function (v) { return v * 2; }).join();", + "2,4,6", + ), + ( + "var m = [1, , 3].map(function (v) { return v; }); var r = m.length + ',' + (1 in m);", + "3,false", + ), + ( + "var r = [1, 2, 3, 4].filter(function (v) { return v % 2 === 0; }).join();", + "2,4", + ), + ( + "var r = [1, 2, 3].some(function (v) { return v > 2; }) + ',' + [1, 2].some(function (v) { return v > 2; });", + "true,false", + ), + ( + "var r = [1, 2, 3].every(function (v) { return v > 0; }) + ',' + [1, 2].every(function (v) { return v > 1; }) + ',' + [].every(function () { return false; });", + "true,false,true", + ), + ( + "var r = [1, 2, 3].reduce(function (a, v) { return a + v; }) + ',' + [1, 2, 3].reduce(function (a, v) { return a + v; }, 10);", + "6,16", + ), + ( + "var r = ['a', 'b', 'c'].reduceRight(function (a, v) { return a + v; }) + ',' + [1].reduceRight(function (a, v) { return a + v; }, 5);", + "cba,6", + ), + ( + "var r; try { [].reduce(function () {}); } catch (e) { r = e.name; }", + "TypeError", + ), + ( + "var r; try { [1].map(3); } catch (e) { r = e.name; }", + "TypeError", + ), + ( + "var r = [1, 2, 3].find(function (v) { return v > 1; }) + ',' + [1, 2, 3].findIndex(function (v) { return v > 1; }) + ',' + [1].find(function (v) { return v > 1; }) + ',' + [1].findIndex(function (v) { return v > 1; });", + "2,1,undefined,-1", + ), + // find visits holes as undefined (no HasProperty). + ( + "var n = 0; [, ,].find(function (v) { n++; return false; }); var r = n;", + "2", + ), + // The length is read once: an element pushed during forEach is not visited. + ( + "var a = [1, 2]; var n = 0; a.forEach(function (v) { n++; a.push(9); }); var r = n + ',' + a.length;", + "2,4", + ), + ]) +} + +#[test] +fn array_sort() -> Result<(), String> { + check(&[ + ("var r = [3, 1, 2].sort().join();", "1,2,3"), + // The default order is by string: "10" < "9". + ("var r = [9, 10, 1].sort().join();", "1,10,9"), + ( + "var r = [3, 1, 2].sort(function (a, b) { return b - a; }).join();", + "3,2,1", + ), + // undefined last, holes after them. + ( + "var a = [3, undefined, 1, , 2]; a.sort(); var r = a.length + ',' + a.join() + ',' + (4 in a) + ',' + (3 in a);", + "5,1,2,3,,,false,true", + ), + // Stable. + ( + "var a = [{ k: 1, v: 'a' }, { k: 0, v: 'b' }, { k: 1, v: 'c' }, { k: 0, v: 'd' }]; a.sort(function (x, y) { return x.k - y.k; }); var r = a.map(function (e) { return e.v; }).join('');", + "bdac", + ), + ( + "var r; try { [1].sort(1); } catch (e) { r = e.name; }", + "TypeError", + ), + // An exception from the comparator ends the sort and propagates. + ( + "var r; try { [2, 1].sort(function () { throw 7; }); } catch (e) { r = e; }", + "7", + ), + ( + "var a = []; for (var i = 0; i < 50; i++) a.push((i * 37) % 50); a.sort(function (x, y) { return x - y; }); var ok = true; for (var j = 0; j < 50; j++) if (a[j] !== j) ok = false; var r = ok;", + "true", + ), + // NaN from the comparator is +0. + ( + "var r = [2, 1].sort(function () { return NaN; }).join();", + "2,1", + ), + ]) +} + +#[test] +fn array_species_and_recursion_bounds() -> Result<(), String> { + check(&[ + // A cyclic join recurses through natives until the bound, a RangeError. + ( + "var a = []; a[0] = a; var r; try { a.join(); } catch (e) { r = e.name; }", + "RangeError", + ), + // A `constructor` that is not a constructor is a TypeError + // (§10.4.2.3 step 6). + ( + "var a = [1]; a.constructor = 1; var r; try { a.map(function (v) { return v; }); } catch (e) { r = e.name; }", + "TypeError", + ), + ( + "var a = [1]; a.constructor = undefined; var r = a.map(function (v) { return v + 1; }).join();", + "2", + ), + ]) +} diff --git a/crates/clazel-js-vm/src/compile/misc.rs b/crates/clazel-js-vm/src/compile/misc.rs index 7f6aa4e8..a43f282b 100644 --- a/crates/clazel-js-vm/src/compile/misc.rs +++ b/crates/clazel-js-vm/src/compile/misc.rs @@ -481,6 +481,29 @@ impl<'a> Cg<'a> { )?; self.release(m); } + // Trailing elisions leave no element: ArrayAccumulation (§13.2.4.1†) + // for an Elision adds to the length only, so `length` is stored + // after the last element. + if let Some(&last) = nd.children.last() + && self.node(last)?.kind == NodeKind::Elision + { + let m = self.mark(); + let idx = self.alloc()?; + let imm = i32::try_from(len).map_err(|_| CompileError::TooLarge("array literal"))?; + self.load_int(idx, imm, sp)?; + let k = self.str_const("length")?; + let ic = self.ic(); + self.emit( + Instr::SetProp { + obj: d, + key: k, + val: idx, + ic, + }, + sp, + )?; + self.release(m); + } Ok(()) } diff --git a/crates/clazel-js-vm/src/handlers.rs b/crates/clazel-js-vm/src/handlers.rs index e321e829..77ed063d 100644 --- a/crates/clazel-js-vm/src/handlers.rs +++ b/crates/clazel-js-vm/src/handlers.rs @@ -346,7 +346,7 @@ impl Vm { } /// IsStrictlyEqual, §7.2.14. - pub(crate) fn strict_equals(&self, x: Value, y: Value) -> bool { + pub fn strict_equals(&self, x: Value, y: Value) -> bool { if let (Some(a), Some(b)) = (num(x), num(y)) { return numeric::equal(a, b); } @@ -442,7 +442,8 @@ impl Vm { let Some(o) = self.heap.obj_mut(base) else { return false; }; - if o.shape.0 != e.shape { + // An array's `length` is not an ordinary data property (§10.4.2.4†). + if o.shape.0 != e.shape || matches!(o.kind, ObjKind::Array) { return false; } let Some(slot) = usize::try_from(e.slot) @@ -648,8 +649,25 @@ impl Vm { } return Ok(()); } + let array_key = self.heap.is_array_object(base) + && (key == self.atoms.k_length || self.heap.key_index(key).is_some()); let ok = match self.heap.find(base, key)? { Some(f) if f.attrs.0 & Attrs::WRITABLE == 0 => false, + // OrdinarySetWithOwnDescriptor (§10.1.9.2†) step 2.c.ii: an + // existing own data property of an array is changed with + // `[[DefineOwnProperty]]` { [[Value]]: V }, which ArraySetLength + // (§10.4.2.4†) handles for `length`. + Some(f) if f.own && array_key && key == self.atoms.k_length => { + let d = crate::props::PropDesc { + value: Some(v), + ..crate::props::PropDesc::default() + }; + self.define_own_property(base, key, &d)? + } + // Step 2.d: no own property, so CreateDataProperty(Receiver, P, V), + // which for an array index may grow `length` (§10.4.2.1†). + None if array_key => self.create_data_property(base, key, v)?, + Some(f) if !f.own && array_key => self.create_data_property(base, key, v)?, Some(f) if f.own => { self.heap.set_slot(base, f.slot, v)?; if !self.heap.is_dictionary(f.shape) { diff --git a/crates/clazel-js-vm/src/heap.rs b/crates/clazel-js-vm/src/heap.rs index 463b4872..f706e8f7 100644 --- a/crates/clazel-js-vm/src/heap.rs +++ b/crates/clazel-js-vm/src/heap.rs @@ -281,6 +281,7 @@ impl Heap { if !props.iter().any(|(k, _, _)| keys.contains(k)) { return Ok(()); } + let old_slots = o.slots.clone(); let mut shape = ROOT; let mut slots: Vec = Vec::with_capacity(props.len()); for (k, slot, a) in props { @@ -289,7 +290,7 @@ impl Heap { } let v = usize::try_from(slot) .ok() - .and_then(|i| o.slots.get(i)) + .and_then(|i| old_slots.get(i)) .copied() .ok_or(HeapError::Corrupt)?; let (next, new_slot) = self.shapes.add_property(shape, k, a)?; diff --git a/crates/clazel-js-vm/src/interp.rs b/crates/clazel-js-vm/src/interp.rs index bb963451..bbdc1ddb 100644 --- a/crates/clazel-js-vm/src/interp.rs +++ b/crates/clazel-js-vm/src/interp.rs @@ -151,10 +151,15 @@ pub enum Intrinsic { StringPrototype, /// `%Array.prototype%`. ArrayPrototype, + /// `%Array%`. + ArrayConstructor, } +/// The most natives that may run one inside another. +const MAX_NATIVE_DEPTH: u32 = 150; + /// How many [`Intrinsic`]s there are. -const INTRINSICS: usize = 11; +const INTRINSICS: usize = 12; /// The hint of ToPrimitive (§7.1.1†). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -282,6 +287,9 @@ pub struct Vm { pub(crate) intrinsics: [Value; INTRINSICS], pub(crate) new_target: Value, pub(crate) active: Value, + /// How many natives are running, one inside another (each re-enters the + /// interpreter or another native on the host stack). + pub(crate) native_depth: u32, pub(crate) terminator: Terminator, pub(crate) budget: u64, pub(crate) atoms: Atoms, @@ -348,6 +356,7 @@ impl Vm { }), new_target: Value::UNDEFINED, active: Value::UNDEFINED, + native_depth: 0, terminator: Terminator::new(), budget: u64::MAX, atoms, @@ -522,9 +531,16 @@ impl Vm { new_target: Value, ) -> Result { let (f, _) = self.native(i)?; + // Natives nest on the host stack (`join` of an array that holds + // itself): a bound keeps that from overflowing it. + if self.native_depth >= MAX_NATIVE_DEPTH { + return Err(self.range_error("Maximum call stack size exceeded")); + } let saved = (self.active, self.new_target); (self.active, self.new_target) = (callee, new_target); + self.native_depth = self.native_depth.saturating_add(1); let r = f(self, this, args); + self.native_depth = self.native_depth.saturating_sub(1); (self.active, self.new_target) = saved; r } @@ -1030,15 +1046,42 @@ impl Vm { Instr::DefineProp { obj, key, val } => { let (o, v) = (self.r(obj)?, self.r(val)?); let key = self.key_const(key)?; - self.heap.define(o, key, v, Attrs::ALL)?; + if self.heap.is_array_object(o) { + self.create_data_property_or_throw(o, key, v)?; + } else { + self.heap.define(o, key, v, Attrs::ALL)?; + } } Instr::DefineElem { obj, idx, val } => { let (o, k, v) = (self.r(obj)?, self.r(idx)?, self.r(val)?); // An elision is the hole: no property. if v != Value::HOLE { let key = self.coerce_property_key(k)?; - self.heap.define(o, key, v, Attrs::ALL)?; + if self.heap.is_array_object(o) { + self.create_data_property_or_throw(o, key, v)?; + } else { + self.heap.define(o, key, v, Attrs::ALL)?; + } + } + } + // ArrayCreate(0), §10.4.2.2†: `len` is only a capacity hint (the + // elements are ordinary properties of the shape). + Instr::NewArray { dst, len: _ } => { + let a = self.array_create(0.0, None)?; + self.w(dst, a)?; + } + // `delete obj[idx]`, §13.5.1.2† step 5: ToObject(base), then + // `[[Delete]]`; false is a TypeError in strict code. + Instr::DeleteProp { dst, obj, idx } => { + let (base, k) = (self.r(obj)?, self.r(idx)?); + let o = self.to_object(base)?; + let key = self.coerce_property_key(k)?; + let ok = self.delete_property(o, key)?; + if !ok && self.strict() { + let name = self.key_text(key); + return Err(self.type_error(&format!("Cannot delete property '{name}'"))); } + self.w(dst, Value::boolean(ok))?; } Instr::SetLiteralProto { obj, val } => { let (o, v) = (self.r(obj)?, self.r(val)?); diff --git a/crates/clazel-js-vm/src/props.rs b/crates/clazel-js-vm/src/props.rs new file mode 100644 index 00000000..d209a631 --- /dev/null +++ b/crates/clazel-js-vm/src/props.rs @@ -0,0 +1,504 @@ +//! Property descriptors, `[[DefineOwnProperty]]`, `[[Delete]]` and Array +//! exotic objects (item 7.9, second group: arrays). +//! +//! The VM's objects hold data properties by shape (`crate::heap`); this module +//! is the standard's property-level operations over them: +//! +//! - [`PropDesc`], a Property Descriptor Specification Type (§6.2.6†) for data +//! properties (each field present or absent); +//! - [`Vm::define_own_property`]: `OrdinaryDefineOwnProperty` (§10.1.6.1†) with +//! `ValidateAndApplyPropertyDescriptor` (§10.1.6.3†), and the Array exotic +//! object's `[[DefineOwnProperty]]` (§10.4.2.1†) with `ArraySetLength` +//! (§10.4.2.4†); +//! - [`Vm::array_create`] (§10.4.2.2†) and [`Vm::create_array_from_list`] +//! (§7.3.18†); +//! - `CreateDataProperty` (§7.3.5†), `DefinePropertyOrThrow` (§7.3.8†), +//! `[[Delete]]` (§10.1.10.1†) and `DeletePropertyOrThrow` (§7.3.10†). +//! +//! Objects are always extensible in this slice (no `Object.preventExtensions` +//! yet) and have no accessor properties. + +use crate::heap::length_value; +use crate::interp::{Abrupt, Intrinsic, Vm}; +use crate::numeric::to_uint32; +use clazel_js_heap::shape::Attrs; +use clazel_js_heap::string::Key; +use clazel_js_heap::value::Value; + +/// A Property Descriptor (§6.2.6†) for a data property: each field is present +/// (`Some`) or absent (`None`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PropDesc { + /// `[[Value]]`. + pub value: Option, + /// `[[Writable]]`. + pub writable: Option, + /// `[[Enumerable]]`. + pub enumerable: Option, + /// `[[Configurable]]`. + pub configurable: Option, +} + +impl PropDesc { + /// A complete descriptor: `value` with the attributes `attrs`. + #[must_use] + pub fn data(value: Value, attrs: Attrs) -> Self { + Self { + value: Some(value), + writable: Some(attrs.0 & Attrs::WRITABLE != 0), + enumerable: Some(attrs.0 & Attrs::ENUMERABLE != 0), + configurable: Some(attrs.0 & Attrs::CONFIGURABLE != 0), + } + } + + /// `{ [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, + /// [[Configurable]]: true }`, the descriptor of `CreateDataProperty` + /// (§7.3.5† step 1). + #[must_use] + pub fn all(value: Value) -> Self { + Self::data(value, Attrs::ALL) + } +} + +impl Vm { + /// SameValue, §7.2.10†: Numbers by value with NaN equal to itself and `+0` + /// distinct from `-0`, Strings by code units, everything else by identity. + #[must_use] + pub fn same_value(&self, a: Value, b: Value) -> bool { + if let (Some(x), Some(y)) = (crate::numeric::num(a), crate::numeric::num(b)) { + let (x, y) = (x.to_f64(), y.to_f64()); + return if x.is_nan() || y.is_nan() { + x.is_nan() && y.is_nan() + } else { + x.to_bits() == y.to_bits() + }; + } + if let (Some(x), Some(y)) = (self.heap.string(a), self.heap.string(b)) { + return x == y; + } + a == b + } + + /// The own data property `key` of `obj` (`OrdinaryGetOwnProperty`, + /// §10.1.5.1†): its attributes and value. + /// + /// # Errors + /// [`Abrupt::Internal`] if the heap is corrupt. + pub fn get_own_property( + &self, + obj: Value, + key: Key, + ) -> Result, Abrupt> { + let Some(f) = self.heap.find(obj, key)?.filter(|f| f.own) else { + return Ok(None); + }; + let v = self + .heap + .slot(f.holder, f.slot) + .ok_or(Abrupt::Internal("property slot"))?; + Ok(Some((f.attrs, v))) + } + + /// `ValidateAndApplyPropertyDescriptor` (§10.1.6.3†) for an extensible + /// object and data properties, as `OrdinaryDefineOwnProperty` (§10.1.6.1†) + /// calls it: + /// 1. (Assert: key is a property key.) + /// 2. If current is undefined, then a. (extensible is true) b. create the + /// data property: each absent field is its default (`undefined`, + /// `false`). c. Return true. + /// 3. (Assert: current is a fully populated Property Descriptor.) + /// 4. If every field of Desc is absent, return true. + /// 5. If current.[[Configurable]] is false, then a. If Desc has + /// [[Configurable]] and it is true, return false. b. If Desc has + /// [[Enumerable]] and it differs from current's, return false. (c, d: + /// the generic and accessor cases, not reachable with data properties.) + /// e. If current.[[Writable]] is false, then i. If Desc has [[Writable]] + /// and it is true, return false. ii. If Desc has [[Value]] and + /// SameValue(Desc.[[Value]], current.[[Value]]) is false, return false. + /// 6. (Accessor/data conversion: not reachable.) The fields of Desc + /// replace those of the property. + /// 7. Return true. + fn ordinary_define_own_property( + &mut self, + obj: Value, + key: Key, + desc: &PropDesc, + ) -> Result { + let current = self.get_own_property(obj, key)?; + let Some((cur_attrs, cur_value)) = current else { + let mut bits = 0; + for (flag, bit) in [ + (desc.writable, Attrs::WRITABLE), + (desc.enumerable, Attrs::ENUMERABLE), + (desc.configurable, Attrs::CONFIGURABLE), + ] { + if flag == Some(true) { + bits |= bit; + } + } + let v = desc.value.unwrap_or(Value::UNDEFINED); + self.heap.define(obj, key, v, Attrs(bits))?; + return Ok(true); + }; + let flag = |bit: u8| cur_attrs.0 & bit != 0; + if !flag(Attrs::CONFIGURABLE) { + let bad = desc.configurable == Some(true) + || desc + .enumerable + .is_some_and(|e| e != flag(Attrs::ENUMERABLE)) + || (!flag(Attrs::WRITABLE) + && (desc.writable == Some(true) + || desc.value.is_some_and(|v| !self.same_value(v, cur_value)))); + if bad { + return Ok(false); + } + } + let mut bits = 0; + for (new, bit) in [ + (desc.writable, Attrs::WRITABLE), + (desc.enumerable, Attrs::ENUMERABLE), + (desc.configurable, Attrs::CONFIGURABLE), + ] { + if new.unwrap_or_else(|| flag(bit)) { + bits |= bit; + } + } + let v = desc.value.unwrap_or(cur_value); + self.heap.redefine(obj, key, v, Attrs(bits))?; + Ok(true) + } + + /// `[[DefineOwnProperty]]` (P, Desc) of an object: for an Array exotic + /// object §10.4.2.1†, else `OrdinaryDefineOwnProperty` (§10.1.6.1†). + /// 1. If P is "length", return ? ArraySetLength(A, Desc). + /// 2. Else if P is an array index, then + /// a. Let lengthDesc be OrdinaryGetOwnProperty(A, "length"). + /// b. (Assert: it is a data descriptor.) c. Let length be + /// lengthDesc.[[Value]]. d. Let index be ! ToUint32(P). + /// e. If index >= length and lengthDesc.[[Writable]] is false, return + /// false. + /// f. Let succeeded be ! OrdinaryDefineOwnProperty(A, P, Desc). + /// g. If succeeded is false, return false. + /// h. If index >= length, then i. Set lengthDesc.[[Value]] to index + + /// 1. ii. Set succeeded to ! OrdinaryDefineOwnProperty(A, "length", + /// lengthDesc). iii. (Assert: succeeded is true.) + /// i. Return true. + /// 3. Return ? OrdinaryDefineOwnProperty(A, P, Desc). + /// + /// # Errors + /// A `RangeError` (ArraySetLength step 5), the exceptions of ToNumber, or + /// [`Abrupt::OutOfMemory`]. + pub fn define_own_property( + &mut self, + obj: Value, + key: Key, + desc: &PropDesc, + ) -> Result { + if !self.heap.is_array_object(obj) { + return self.ordinary_define_own_property(obj, key, desc); + } + if key == self.atoms.k_length { + return self.array_set_length(obj, desc); + } + let Some(index) = self.heap.key_index(key) else { + return self.ordinary_define_own_property(obj, key, desc); + }; + let (length, writable) = self + .heap + .array_length(obj) + .ok_or(Abrupt::Internal("array length"))?; + if index >= length && !writable { + return Ok(false); + } + if !self.ordinary_define_own_property(obj, key, desc)? { + return Ok(false); + } + if index >= length { + let new_len = index.checked_add(1).ok_or(Abrupt::Internal("array index"))?; + self.heap.set_array_length(obj, new_len)?; + } + Ok(true) + } + + /// ArraySetLength ( A, Desc ), §10.4.2.4†: + /// 1. If Desc does not have a [[Value]] field, then a. Return ! + /// OrdinaryDefineOwnProperty(A, "length", Desc). + /// 2. Let newLenDesc be a copy of Desc. + /// 3. Let newLen be ? ToUint32(Desc.[[Value]]). + /// 4. Let numberLen be ? ToNumber(Desc.[[Value]]). + /// 5. If SameValueZero(newLen, numberLen) is false, throw a RangeError. + /// 6. Set newLenDesc.[[Value]] to newLen. + /// 7. Let oldLenDesc be OrdinaryGetOwnProperty(A, "length"). + /// 9. Let oldLen be oldLenDesc.[[Value]]. + /// 10. If newLen >= oldLen, then a. Return ! OrdinaryDefineOwnProperty(A, + /// "length", newLenDesc). + /// 11. If oldLenDesc.[[Writable]] is false, return false. + /// 12. If newLenDesc does not have a [[Writable]] field or + /// newLenDesc.[[Writable]] is true, let newWritable be true. + /// 13. Else, a. (Need to defer setting the [[Writable]] attribute to false + /// in case any elements cannot be deleted.) b. Let newWritable be + /// false. c. Set newLenDesc.[[Writable]] to true. + /// 14. Let succeeded be ! OrdinaryDefineOwnProperty(A, "length", + /// newLenDesc). + /// 15. If succeeded is false, return false. + /// 16. For each own property key P of A such that P is an array index and + /// ! ToUint32(P) >= newLen, in descending numeric index order, do + /// a. Let deleteSucceeded be ! A.[[Delete]](P). + /// b. If deleteSucceeded is false, then i. Set newLenDesc.[[Value]] to + /// ! ToUint32(P) + 1. ii. If newWritable is false, set + /// newLenDesc.[[Writable]] to false. iii. Perform ! + /// OrdinaryDefineOwnProperty(A, "length", newLenDesc). iv. Return + /// false. + /// 17. If newWritable is false, then a. Set succeeded to ! + /// OrdinaryDefineOwnProperty(A, "length", { [[Writable]]: false }). + /// 18. Return true. + fn array_set_length(&mut self, a: Value, desc: &PropDesc) -> Result { + let k_length = self.atoms.k_length; + let Some(v) = desc.value else { + return self.ordinary_define_own_property(a, k_length, desc); + }; + let mut new_len_desc = *desc; + let new_len = to_uint32(self.coerce_number(v)?); + let number_len = self.to_number(v)?; + if f64::from(new_len) != number_len { + return Err(self.range_error("Invalid array length")); + } + new_len_desc.value = Some(length_value(new_len)); + let (old_len, old_writable) = self + .heap + .array_length(a) + .ok_or(Abrupt::Internal("array length"))?; + if new_len >= old_len { + return self.ordinary_define_own_property(a, k_length, &new_len_desc); + } + if !old_writable { + return Ok(false); + } + let new_writable = new_len_desc.writable != Some(false); + if !new_writable { + new_len_desc.writable = Some(true); + } + if !self.ordinary_define_own_property(a, k_length, &new_len_desc)? { + return Ok(false); + } + // Step 16: the indices at or above newLen, in descending order. + let mut doomed: Vec<(u32, Key)> = self + .heap + .own_properties(a) + .into_iter() + .filter_map(|(k, _, _)| self.heap.key_index(k).map(|i| (i, k))) + .filter(|(i, _)| *i >= new_len) + .collect(); + doomed.sort_by(|x, y| y.0.cmp(&x.0)); + for (i, k) in &doomed { + let configurable = self + .get_own_property(a, *k)? + .is_some_and(|(at, _)| at.0 & Attrs::CONFIGURABLE != 0); + if !configurable { + // The properties above this one are already gone. + let keep = i.checked_add(1).ok_or(Abrupt::Internal("array index"))?; + new_len_desc.value = Some(length_value(keep)); + if !new_writable { + new_len_desc.writable = Some(false); + } + self.ordinary_define_own_property(a, k_length, &new_len_desc)?; + self.remove_doomed(a, &doomed, Some(*i))?; + return Ok(false); + } + } + self.remove_doomed(a, &doomed, None)?; + if !new_writable { + let w = PropDesc { + writable: Some(false), + ..PropDesc::default() + }; + self.ordinary_define_own_property(a, k_length, &w)?; + } + Ok(true) + } + + /// Removes the doomed indices above `stop` (all of them when `stop` is + /// `None`): the deletions of step 16.a that happened before the one that + /// failed. + fn remove_doomed( + &mut self, + a: Value, + doomed: &[(u32, Key)], + stop: Option, + ) -> Result<(), Abrupt> { + let keys: Vec = doomed + .iter() + .filter(|(i, _)| stop.is_none_or(|s| *i > s)) + .map(|(_, k)| *k) + .collect(); + Ok(self.heap.remove_properties(a, &keys)?) + } + + /// ArrayCreate ( length [ , proto ] ), §10.4.2.2†: + /// 1. If length > 2^32 - 1, throw a RangeError exception. + /// 2. If proto is not present, set proto to %Array.prototype%. + /// 3. Let A be MakeBasicObject(<<[[Prototype]], [[Extensible]]>>). + /// 4. Set A.[[Prototype]] to proto. + /// 5. Set A.[[DefineOwnProperty]] to the definition in §10.4.2.1†. + /// 6. Perform ! OrdinaryDefineOwnProperty(A, "length", { [[Value]]: length, + /// [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false + /// }). + /// 7. Return A. + /// + /// # Errors + /// A `RangeError`, [`Abrupt::OutOfMemory`]. + pub fn array_create(&mut self, length: f64, proto: Option) -> Result { + if length > 4_294_967_295.0 || length < 0.0 || length.is_nan() { + return Err(self.range_error("Invalid array length")); + } + let proto = match proto { + Some(p) => p, + None => self.array_prototype(), + }; + Ok(self.heap.new_array(proto, length as u32)?) + } + + /// `%Array.prototype%`, or `%Object.prototype%` while the realm has no + /// `Array` built-in. + #[must_use] + pub fn array_prototype(&self) -> Value { + let p = self.intrinsic(Intrinsic::ArrayPrototype); + if self.heap.is_object(p) { + p + } else { + self.atoms.object_proto + } + } + + /// CreateArrayFromList ( elements ), §7.3.18†: + /// 1. (Assert: each element is an ECMAScript language value.) + /// 2. Let array be ! ArrayCreate(0). + /// 3. Let n be 0. + /// 4. For each element e of elements, do a. Perform ! + /// CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), e). b. Set n to n + 1. + /// 5. Return array. + /// + /// # Errors + /// [`Abrupt::OutOfMemory`]. + pub fn create_array_from_list(&mut self, items: &[Value]) -> Result { + let a = self.array_create(0.0, None)?; + for (i, v) in items.iter().enumerate() { + let k = self.index_key(i as u64)?; + self.create_data_property(a, k, *v)?; + } + Ok(a) + } + + /// The interned key for the integer `i` (ToString of a Number that is an + /// integer, §6.1.6.1.20†). + /// + /// # Errors + /// [`Abrupt::OutOfMemory`]. + pub fn index_key(&mut self, i: u64) -> Result { + Ok(self.heap.intern_str(&i.to_string())?) + } + + /// Whether `v` is an Array exotic object (IsArray, §7.2.2† steps 1 to 3; + /// no Proxies). + #[must_use] + pub fn is_array(&self, v: Value) -> bool { + self.heap.is_array_object(v) + } + + /// CreateDataProperty ( O, P, V ), §7.3.5†: + /// 1. Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: + /// true, [[Enumerable]]: true, [[Configurable]]: true }. + /// 2. Return ? O.[[DefineOwnProperty]](P, newDesc). + /// + /// # Errors + /// As [`Vm::define_own_property`]. + pub fn create_data_property(&mut self, o: Value, k: Key, v: Value) -> Result { + self.define_own_property(o, k, &PropDesc::all(v)) + } + + /// CreateDataPropertyOrThrow ( O, P, V ), §7.3.7†: + /// 1. Let success be ? CreateDataProperty(O, P, V). + /// 2. If success is false, throw a TypeError exception. + /// 3. Return unused. + /// + /// # Errors + /// A `TypeError`, or as [`Vm::define_own_property`]. + pub fn create_data_property_or_throw( + &mut self, + o: Value, + k: Key, + v: Value, + ) -> Result<(), Abrupt> { + if self.create_data_property(o, k, v)? { + Ok(()) + } else { + let name = self.key_text(k); + Err(self.type_error(&format!("Cannot define property {name}"))) + } + } + + /// DefinePropertyOrThrow ( O, P, desc ), §7.3.8†: + /// 1. Let success be ? O.[[DefineOwnProperty]](P, desc). + /// 2. If success is false, throw a TypeError exception. + /// + /// # Errors + /// A `TypeError`, or as [`Vm::define_own_property`]. + pub fn define_property_or_throw( + &mut self, + o: Value, + k: Key, + desc: &PropDesc, + ) -> Result<(), Abrupt> { + if self.define_own_property(o, k, desc)? { + Ok(()) + } else { + let name = self.key_text(k); + Err(self.type_error(&format!("Cannot redefine property: {name}"))) + } + } + + /// `[[Delete]]` ( P ), OrdinaryDelete §10.1.10.1†: + /// 1. Let desc be ? O.[[GetOwnProperty]](P). + /// 2. If desc is undefined, return true. + /// 3. If desc.[[Configurable]] is true, then a. Remove the own property + /// with name P from O. b. Return true. + /// 4. Return false. + /// + /// The `length` of an array is not configurable, so it is never removed. + /// + /// # Errors + /// [`Abrupt::OutOfMemory`]. + pub fn delete_property(&mut self, o: Value, k: Key) -> Result { + let Some((attrs, _)) = self.get_own_property(o, k)? else { + return Ok(true); + }; + if attrs.0 & Attrs::CONFIGURABLE != 0 { + self.heap.remove_properties(o, &[k])?; + return Ok(true); + } + Ok(false) + } + + /// DeletePropertyOrThrow ( O, P ), §7.3.10†: + /// 1. Let success be ? O.[[Delete]](P). + /// 2. If success is false, throw a TypeError exception. + /// + /// # Errors + /// A `TypeError`, [`Abrupt::OutOfMemory`]. + pub fn delete_property_or_throw(&mut self, o: Value, k: Key) -> Result<(), Abrupt> { + if self.delete_property(o, k)? { + Ok(()) + } else { + let name = self.key_text(k); + Err(self.type_error(&format!("Cannot delete property '{name}'"))) + } + } + + /// The step budget's check, for a native's long loops: one unit per call. + /// + /// # Errors + /// [`Abrupt::Terminated`] when the budget is spent or the terminator set. + pub fn charge_step(&mut self) -> Result<(), Abrupt> { + self.charge() + } +} From d8917a95af0afe251e66d958e4b5357cd524824d Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sun, 22 Nov 2026 15:19:45 +0000 Subject: [PATCH 3/6] clazel-js-vm: trailing elisions of an array literal set the length; tests Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-builtins/tests/array.rs | 4 ++-- crates/clazel-js-vm/tests/interp.rs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/clazel-js-builtins/tests/array.rs b/crates/clazel-js-builtins/tests/array.rs index d54fad03..ada7c066 100644 --- a/crates/clazel-js-builtins/tests/array.rs +++ b/crates/clazel-js-builtins/tests/array.rs @@ -91,7 +91,7 @@ fn array_exotic_objects() -> Result<(), String> { // A non-configurable element stops the truncation (step 16.b). ( "var a = [1, 2]; Object.defineProperty(a, 2, { value: 5 }); a.length = 0; var r = a.length + ',' + a[0] + ',' + a[2];", - "3,undefined,5", + "3,1,5", ), // `length` is not enumerable, writable, not configurable. ( @@ -115,7 +115,7 @@ fn array_exotic_objects() -> Result<(), String> { "var r = Array.isArray({ length: 0 }) + ',' + Array.isArray([]);", "false,true", ), - ("var r = [] instanceof Object;", "true"), + ("var r = Object.getPrototypeOf([]) === Array.prototype;", "true"), // Object.keys returns an array now. ("var r = Array.isArray(Object.keys({ a: 1 }));", "true"), ( diff --git a/crates/clazel-js-vm/tests/interp.rs b/crates/clazel-js-vm/tests/interp.rs index 76e49826..164f7bdb 100644 --- a/crates/clazel-js-vm/tests/interp.rs +++ b/crates/clazel-js-vm/tests/interp.rs @@ -384,7 +384,8 @@ fn what_is_not_implemented_is_an_error_not_a_panic() -> Result<(), String> { Err(e) => return Err(format!("{src}: {e:?}")), } } - let (_, r) = run("var a = [1, 2];")?; + // Spread needs iterators (GetIterator), which are not implemented. + let (_, r) = run("var a = [...[1, 2]];")?; assert!(matches!(r, Err(Abrupt::NotYet(_))), "{r:?}"); Ok(()) } From 1dcf5d7c22997483d91ffc06e561ce95ebf555c5 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sun, 22 Nov 2026 15:25:23 +0000 Subject: [PATCH 4/6] clazel-js-builtins: JSON.parse and JSON.stringify over clazel-json Reviver (InternalizeJSONProperty), replacer function and array, space and gap, toJSON, wrapper objects, the cycle TypeError, and the nesting bound (a SyntaxError for parse, a RangeError past 128 levels for stringify). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/clazel-js-builtins/Cargo.toml | 3 +- crates/clazel-js-builtins/src/array.rs | 9 +- crates/clazel-js-builtins/src/json.rs | 583 +++++++++++++++++++++++ crates/clazel-js-builtins/src/lib.rs | 22 +- crates/clazel-js-builtins/tests/array.rs | 20 +- crates/clazel-js-builtins/tests/json.rs | 241 ++++++++++ crates/clazel-js-vm/src/heap.rs | 3 +- crates/clazel-js-vm/src/props.rs | 10 +- 9 files changed, 874 insertions(+), 18 deletions(-) create mode 100644 crates/clazel-js-builtins/src/json.rs create mode 100644 crates/clazel-js-builtins/tests/json.rs diff --git a/Cargo.lock b/Cargo.lock index c1ac1642..5baf0f14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -397,6 +397,7 @@ dependencies = [ "clazel-js-number", "clazel-js-syntax", "clazel-js-vm", + "clazel-json", ] [[package]] diff --git a/crates/clazel-js-builtins/Cargo.toml b/crates/clazel-js-builtins/Cargo.toml index 0061a457..10383368 100644 --- a/crates/clazel-js-builtins/Cargo.toml +++ b/crates/clazel-js-builtins/Cargo.toml @@ -4,12 +4,13 @@ version = "0.0.0" edition.workspace = true license.workspace = true publish.workspace = true -description = "The global object's built-ins (ECMA-262 clauses 19 to 28) for Clazel's JavaScript engine (phase-7.md item 7.9): the first group, Object, Function, the Error constructors, Boolean, Number, String, Math and the global functions." +description = "The global object's built-ins (ECMA-262 clauses 19 to 28) for Clazel's JavaScript engine (phase-7.md item 7.9): the first group, Object, Function, the Error constructors, Boolean, Number, String, Math and the global functions; the second group, Array and JSON." [dependencies] clazel-js-heap = { path = "../clazel-js-heap" } clazel-js-number = { path = "../clazel-js-number" } clazel-js-vm = { path = "../clazel-js-vm" } +clazel-json = { path = "../clazel-json" } [dev-dependencies] clazel-js-syntax = { path = "../clazel-js-syntax", version = "=0.0.0" } diff --git a/crates/clazel-js-builtins/src/array.rs b/crates/clazel-js-builtins/src/array.rs index f86c7516..9624b60f 100644 --- a/crates/clazel-js-builtins/src/array.rs +++ b/crates/clazel-js-builtins/src/array.rs @@ -882,7 +882,14 @@ fn includes(vm: &mut Vm, this: Value, args: &[Value]) -> Result { /// The callback of one element: `Call(callbackfn, thisArg, « kValue, 𝔽(k), O /// »)`. -fn call3(vm: &mut Vm, f: Value, this_arg: Value, v: Value, k: f64, o: Value) -> Result { +fn call3( + vm: &mut Vm, + f: Value, + this_arg: Value, + v: Value, + k: f64, + o: Value, +) -> Result { vm.call(f, this_arg, &[v, number(k), o]) } diff --git a/crates/clazel-js-builtins/src/json.rs b/crates/clazel-js-builtins/src/json.rs new file mode 100644 index 00000000..8d5011e1 --- /dev/null +++ b/crates/clazel-js-builtins/src/json.rs @@ -0,0 +1,583 @@ +//! `JSON` (§25.5†): `JSON.parse` and `JSON.stringify`, over `clazel-json`. +//! +//! `JSON.parse` reads the text with `clazel-json`'s parser (ECMA-404, and the +//! parse step of §25.5.1† `JSON.parse`, proven against the grammar there); +//! this module builds the values and runs the reviver. `JSON.stringify` quotes +//! strings with `clazel-json`'s `quote` (QuoteJSONString, §25.5.2.3†) and +//! implements §25.5.2† itself. +//! +//! Listed deviations: +//! +//! - **The nesting bound.** `clazel-json` reads at most 512 levels of arrays +//! and objects; deeper text is a `SyntaxError` (phase-7.md 7.11, listed). +//! `JSON.stringify` stops at 128 levels with a `RangeError`, where the +//! standard has no bound (it recurses on the host stack, which must not +//! overflow; an unoptimised frame is several KB, and tests run on 2 MB). +//! - No `BigInt` (`toJSON` is looked up on Objects only) and no Symbols (a +//! Symbol is never a value here), so those steps of the algorithms do not +//! exist yet. +//! - The reviver's third argument (the source text context of the JSON +//! parse-with-source proposal) is not passed. + +use crate::util::{arg, js_string, method, number, to_integer_or_infinity}; +use clazel_js_heap::shape::Attrs; +use clazel_js_heap::string::{JsString, Key}; +use clazel_js_heap::value::{Decoded, Value}; +use clazel_js_vm::heap::ObjKind; +use clazel_js_vm::interp::{Abrupt, Vm}; +use clazel_json::tree::Json; + +/// The deepest nesting `JSON.stringify` serializes. +const MAX_DEPTH: usize = 128; + +/// Installs `JSON`. +/// +/// # Errors +/// As [`crate::install`]. +pub fn install(vm: &mut Vm) -> Result<(), Abrupt> { + let json = vm.new_object()?; + method(vm, json, "parse", 2, parse)?; + method(vm, json, "stringify", 3, stringify)?; + // §25.5.3†: `JSON[@@toStringTag]` is "JSON" (no Symbols yet, so absent). + crate::util::global(vm, "JSON", json) +} + +fn units_of(vm: &mut Vm, v: Value) -> Result, Abrupt> { + Ok(vm.to_js_string(v)?.units().collect()) +} + +fn key_of(vm: &mut Vm, units: &[u16]) -> Result { + let s = JsString::from_units(units).map_err(|_| Abrupt::OutOfMemory)?; + Ok(vm.heap_mut().intern(&s)?) +} + +fn str_value(vm: &mut Vm, units: &[u16]) -> Result { + let s = JsString::from_units(units).map_err(|_| Abrupt::OutOfMemory)?; + js_string(vm, s) +} + +// --------------------------------------------------------------------- +// JSON.parse +// --------------------------------------------------------------------- + +/// `JSON.parse ( text [ , reviver ] )`, §25.5.1†: +/// 1. Let jsonString be ? ToString(text). +/// 2. Parse StringToCodePoints(jsonString) as a JSON text as specified in +/// ECMA-404. Throw a SyntaxError exception if it is not a valid JSON text +/// as defined in that specification. +/// 3. to 5. (The script-goal evaluation of the standard's text is replaced by +/// building the value of the JSON text directly: each JSON object member +/// is CreateDataProperty on a new ordinary object, a later duplicate name +/// replacing an earlier value; an array is ArrayCreate and +/// CreateDataProperty of each element; a number is StringToNumber of its +/// text; a string is its code units.) +/// 6. Let unfiltered be the result. +/// 7. If IsCallable(reviver) is true, then a. Let root be +/// OrdinaryObjectCreate(%Object.prototype%). b. Let rootName be the empty +/// String. c. Perform ! CreateDataPropertyOrThrow(root, rootName, +/// unfiltered). d. Return ? InternalizeJSONProperty(root, rootName, +/// reviver). +/// 8. Else, a. Return unfiltered. +fn parse(vm: &mut Vm, _this: Value, args: &[Value]) -> Result { + let text = units_of(vm, arg(args, 0))?; + let cps = code_points(&text); + let Some(tree) = clazel_json::parse::parse(&cps) else { + return Err(vm.syntax_error("Unexpected token in JSON, or nesting too deep")); + }; + let unfiltered = build(vm, &tree)?; + let reviver = arg(args, 1); + if vm.heap().is_callable(reviver) { + let root = vm.new_object()?; + let name = key_of(vm, &[])?; + vm.create_data_property_or_throw(root, name, unfiltered)?; + return internalize(vm, root, name, reviver); + } + Ok(unfiltered) +} + +/// StringToCodePoints (§6.1.4†): surrogate pairs join; a lone surrogate is +/// its own code point. +fn code_points(units: &[u16]) -> Vec { + let mut out = Vec::with_capacity(units.len()); + let mut i = 0usize; + while let Some(&u) = units.get(i) { + let next = units.get(i.saturating_add(1)).copied(); + match next { + Some(lo) if (0xD800..0xDC00).contains(&u) && (0xDC00..0xE000).contains(&lo) => { + let hi = u32::from(u).saturating_sub(0xD800); + let lo = u32::from(lo).saturating_sub(0xDC00); + out.push( + hi.saturating_mul(0x400) + .saturating_add(lo) + .saturating_add(0x10000), + ); + i = i.saturating_add(2); + } + _ => { + out.push(u32::from(u)); + i = i.saturating_add(1); + } + } + } + out +} + +/// The value of a parsed JSON text. +fn build(vm: &mut Vm, j: &Json) -> Result { + match j { + Json::Null => Ok(Value::NULL), + Json::Bool(b) => Ok(Value::boolean(*b)), + Json::Number(text) => { + let s: String = text.iter().filter_map(|c| char::from_u32(*c)).collect(); + Ok(number(clazel_js_number::string_to_number(&s))) + } + Json::String(u) => str_value(vm, u), + Json::Array(items) => { + let a = vm.array_create(0.0, None)?; + for (i, item) in items.iter().enumerate() { + let v = build(vm, item)?; + let k = vm.index_key(i as u64)?; + vm.create_data_property_or_throw(a, k, v)?; + } + Ok(a) + } + Json::Object(members) => { + let o = vm.new_object()?; + for m in members { + let v = build(vm, &m.value)?; + let k = key_of(vm, &m.key)?; + vm.create_data_property_or_throw(o, k, v)?; + } + Ok(o) + } + } +} + +/// EnumerableOwnProperties ( O, key ), §7.3.23†, as a list of keys. +fn enumerable_keys(vm: &Vm, o: Value) -> Vec { + vm.heap() + .own_properties(o) + .into_iter() + .filter(|(_, a, _)| a.0 & Attrs::ENUMERABLE != 0) + .map(|(k, _, _)| k) + .collect() +} + +/// InternalizeJSONProperty ( holder, name, reviver ), §25.5.1.1†: +/// 1. Let val be ? Get(holder, name). +/// 2. If val is an Object, then +/// a. Let isArray be ? IsArray(val). +/// b. If isArray is true, then i. Let len be ? LengthOfArrayLike(val). +/// ii. Let I be 0. iii. Repeat, while I < len, 1. Let prop be ! +/// ToString(𝔽(I)). 2. Let newElement be ? InternalizeJSONProperty(val, +/// prop, reviver). 3. If newElement is undefined, then a. Perform ? +/// val.[[Delete]](prop). 4. Else, a. Perform ? CreateDataProperty(val, +/// prop, newElement). 5. Set I to I + 1. +/// c. Else, i. Let keys be ? EnumerableOwnProperties(val, key). ii. For +/// each String P of keys, do 1. Let newElement be ? +/// InternalizeJSONProperty(val, P, reviver). 2. If newElement is +/// undefined, then a. Perform ? val.[[Delete]](P). 3. Else, a. Perform ? +/// CreateDataProperty(val, P, newElement). +/// 3. Return ? Call(reviver, holder, « name, val »). +fn internalize(vm: &mut Vm, holder: Value, name: Key, reviver: Value) -> Result { + vm.charge_step()?; + let val = vm.get_value(holder, name)?; + if vm.heap().is_object(val) { + let keys: Vec = if vm.is_array(val) { + let lk = key_of(vm, &"length".encode_utf16().collect::>())?; + let lv = vm.get_value(val, lk)?; + let len = to_integer_or_infinity(vm, lv)?.clamp(0.0, 9_007_199_254_740_991.0); + let mut ks = Vec::new(); + let mut i = 0.0f64; + while i < len { + vm.charge_step()?; + ks.push(vm.index_key(i as u64)?); + i += 1.0; + } + ks + } else { + enumerable_keys(vm, val) + }; + for p in keys { + let new_element = internalize(vm, val, p, reviver)?; + if new_element == Value::UNDEFINED { + vm.delete_property(val, p)?; + } else { + vm.create_data_property(val, p, new_element)?; + } + } + } + let name_v = { + let s = vm + .heap() + .key_string(name) + .cloned() + .ok_or(Abrupt::Internal("key"))?; + js_string(vm, s)? + }; + vm.call(reviver, holder, &[name_v, val]) +} + +// --------------------------------------------------------------------- +// JSON.stringify +// --------------------------------------------------------------------- + +/// The state of a stringify (§25.5.2†): the ReplacerFunction, the +/// PropertyList, the gap, the indent and the stack. +struct State { + replacer: Value, + property_list: Option>, + gap: Vec, + indent: Vec, + stack: Vec, +} + +/// The primitive inside a Boolean, Number or String wrapper object. +fn wrapped(vm: &Vm, v: Value) -> Option { + match vm.heap().obj(v).map(|o| o.kind) { + Some(ObjKind::Primitive(p)) => Some(p), + _ => None, + } +} + +/// `JSON.stringify ( value [ , replacer [ , space ] ] )`, §25.5.2†: +/// 1. Let stack be a new empty List. +/// 2. Let indent be the empty String. +/// 3. Let PropertyList be undefined. +/// 4. Let ReplacerFunction be undefined. +/// 5. If replacer is an Object, then +/// a. If IsCallable(replacer) is true, then i. Set ReplacerFunction to +/// replacer. +/// b. Else, i. Let isArray be ? IsArray(replacer). ii. If isArray is true, +/// then 1. Set PropertyList to a new empty List. 2. Let len be ? +/// LengthOfArrayLike(replacer). 3. Let k be 0. 4. Repeat, while k < len, a. +/// Let prop be ! ToString(𝔽(k)). b. Let v be ? Get(replacer, prop). c. Let +/// item be undefined. d. If v is a String, then i. Set item to v. e. Else +/// if v is a Number, then i. Set item to ! ToString(v). f. Else if v is an +/// Object, then i. If v has a [[StringData]] or [[NumberData]] internal +/// slot, set item to ? ToString(v). g. If item is not undefined and +/// PropertyList does not contain item, then i. Append item to +/// PropertyList. h. Set k to k + 1. +/// 6. If space is an Object, then a. If space has a [[NumberData]] internal +/// slot, then i. Set space to ? ToNumber(space). b. Else if space has a +/// [[StringData]] internal slot, then i. Set space to ? ToString(space). +/// 7. If space is a Number, then a. Let spaceMV be ! ToIntegerOrInfinity(space). +/// b. Set spaceMV to min(10, spaceMV). c. If spaceMV < 1, let gap be the +/// empty String; otherwise let gap be the String value containing spaceMV +/// occurrences of the code unit 0x0020 (SPACE). +/// 8. Else if space is a String, then a. If the length of space is 10 or less, +/// let gap be space; otherwise let gap be the substring of space from 0 to +/// 10. +/// 9. Else, a. Let gap be the empty String. +/// 10. Let wrapper be OrdinaryObjectCreate(%Object.prototype%). +/// 11. Perform ! CreateDataPropertyOrThrow(wrapper, the empty String, value). +/// 12. Let state be the JSON Serialization Record { [[ReplacerFunction]], +/// [[Stack]], [[Indent]], [[Gap]], [[PropertyList]] }. +/// 13. Return ? SerializeJSONProperty(state, the empty String, wrapper). +fn stringify(vm: &mut Vm, _this: Value, args: &[Value]) -> Result { + let (value, replacer, mut space) = (arg(args, 0), arg(args, 1), arg(args, 2)); + let mut state = State { + replacer: Value::UNDEFINED, + property_list: None, + gap: Vec::new(), + indent: Vec::new(), + stack: Vec::new(), + }; + if vm.heap().is_object(replacer) { + if vm.heap().is_callable(replacer) { + state.replacer = replacer; + } else if vm.is_array(replacer) { + let lk = key_of(vm, &"length".encode_utf16().collect::>())?; + let lv = vm.get_value(replacer, lk)?; + let len = to_integer_or_infinity(vm, lv)?.clamp(0.0, 9_007_199_254_740_991.0); + let mut list: Vec = Vec::new(); + let mut k = 0.0f64; + while k < len { + vm.charge_step()?; + let pk = vm.index_key(k as u64)?; + let v = vm.get_value(replacer, pk)?; + let item = if vm.heap().is_string(v) || crate::util::as_number(v).is_some() { + Some(units_of(vm, v)?) + } else if let Some(p) = wrapped(vm, v) + && !matches!(p.decode(), Decoded::Bool(_)) + { + Some(units_of(vm, v)?) + } else { + None + }; + if let Some(u) = item { + let key = key_of(vm, &u)?; + if !list.contains(&key) { + list.push(key); + } + } + k += 1.0; + } + state.property_list = Some(list); + } + } + if let Some(p) = wrapped(vm, space) { + if crate::util::as_number(p).is_some() { + let n = vm.to_number(space)?; + space = number(n); + } else if vm.heap().is_string(p) { + let s = vm.to_js_string(space)?; + space = js_string(vm, s)?; + } + } + if let Some(n) = crate::util::as_number(space) { + let mv = if n.is_nan() { 0.0 } else { n.trunc() }.min(10.0); + let count = if mv < 1.0 { 0 } else { mv as usize }; + state.gap = vec![0x20; count]; + } else if vm.heap().is_string(space) { + state.gap = units_of(vm, space)?.into_iter().take(10).collect(); + } + let wrapper = vm.new_object()?; + let empty = key_of(vm, &[])?; + vm.create_data_property_or_throw(wrapper, empty, value)?; + match serialize_property(vm, &mut state, empty, wrapper)? { + Some(units) => str_value(vm, &units), + None => Ok(Value::UNDEFINED), + } +} + +/// SerializeJSONProperty ( state, key, holder ), §25.5.2.2†: the text, or +/// `None` for undefined. +/// 1. Let value be ? Get(holder, key). +/// 2. If value is an Object, then a. Let toJSON be ? GetV(value, "toJSON"). +/// b. If IsCallable(toJSON) is true, then i. Set value to ? Call(toJSON, +/// value, « key »). +/// 3. If state.[[ReplacerFunction]] is not undefined, then a. Set value to ? +/// Call(state.[[ReplacerFunction]], holder, « key, value »). +/// 4. If value is an Object, then a. If value has a [[NumberData]] internal +/// slot, then i. Set value to ? ToNumber(value). b. Else if value has a +/// [[StringData]] internal slot, then i. Set value to ? ToString(value). +/// c. Else if value has a [[BooleanData]] internal slot, then i. Set value +/// to value.[[BooleanData]]. +/// 5. If value is null, return "null". +/// 6. If value is true, return "true". +/// 7. If value is false, return "false". +/// 8. If value is a String, return QuoteJSONString(value). +/// 9. If value is a Number, then a. If value is finite, return ! +/// ToString(value). b. Return "null". +/// 11. If value is an Object and IsCallable(value) is false, then a. Let +/// isArray be ? IsArray(value). b. If isArray is true, return ? +/// SerializeJSONArray(state, value). c. Return ? SerializeJSONObject(state, +/// value). +/// 12. Return undefined. +fn serialize_property( + vm: &mut Vm, + state: &mut State, + key: Key, + holder: Value, +) -> Result>, Abrupt> { + vm.charge_step()?; + let mut value = vm.get_value(holder, key)?; + let key_v = { + let s = vm + .heap() + .key_string(key) + .cloned() + .ok_or(Abrupt::Internal("key"))?; + js_string(vm, s)? + }; + if vm.heap().is_object(value) { + let to_json = vm.get_named(value, "toJSON")?; + if vm.heap().is_callable(to_json) { + value = vm.call(to_json, value, &[key_v])?; + } + } + if state.replacer != Value::UNDEFINED { + value = vm.call(state.replacer, holder, &[key_v, value])?; + } + if let Some(p) = wrapped(vm, value) { + value = match p.decode() { + Decoded::Bool(_) => p, + Decoded::Int32(_) | Decoded::Double(_) => number(vm.to_number(value)?), + _ => { + let s = vm.to_js_string(value)?; + js_string(vm, s)? + } + }; + } + if value == Value::NULL { + return Ok(Some("null".encode_utf16().collect())); + } + if value == Value::TRUE { + return Ok(Some("true".encode_utf16().collect())); + } + if value == Value::FALSE { + return Ok(Some("false".encode_utf16().collect())); + } + if let Some(s) = vm.heap().string(value) { + let units: Vec = s.units().collect(); + return Ok(Some(clazel_json::quote::quote(&units))); + } + if let Some(n) = crate::util::as_number(value) { + return Ok(Some(if n.is_finite() { + vm.to_js_string(value)?.units().collect() + } else { + "null".encode_utf16().collect() + })); + } + if vm.heap().is_object(value) && !vm.heap().is_callable(value) { + return if vm.is_array(value) { + serialize_array(vm, state, value).map(Some) + } else { + serialize_object(vm, state, value).map(Some) + }; + } + Ok(None) +} + +/// Pushes `value` on the stack, TypeError for a cycle (§25.5.2.4† step 1, +/// §25.5.2.5† step 1), RangeError past [`MAX_DEPTH`] (listed deviation). +fn enter(vm: &mut Vm, state: &mut State, value: Value) -> Result<(), Abrupt> { + if state.stack.contains(&value) { + return Err(vm.type_error("Converting circular structure to JSON")); + } + if state.stack.len() >= MAX_DEPTH { + return Err(vm.range_error("JSON.stringify: nesting too deep")); + } + state.stack.push(value); + Ok(()) +} + +/// SerializeJSONObject ( state, value ), §25.5.2.4†: +/// 1. If state.[[Stack]] contains value, throw a TypeError exception because +/// the structure is cyclical. +/// 2. Append value to state.[[Stack]]. +/// 3. Let stepback be state.[[Indent]]. +/// 4. Set state.[[Indent]] to the string-concatenation of state.[[Indent]] and +/// state.[[Gap]]. +/// 5. If state.[[PropertyList]] is not undefined, then a. Let K be +/// state.[[PropertyList]]. +/// 6. Else, a. Let K be ? EnumerableOwnProperties(value, key). +/// 7. Let partial be a new empty List. +/// 8. For each element P of K, do a. Let strP be ? SerializeJSONProperty(state, +/// P, value). b. If strP is not undefined, then i. Let member be +/// QuoteJSONString(P). ii. Set member to the string-concatenation of member +/// and ":". iii. If state.[[Gap]] is not the empty String, then 1. Set +/// member to the string-concatenation of member and the code unit 0x0020 +/// (SPACE). iv. Set member to the string-concatenation of member and strP. +/// v. Append member to partial. +/// 9. If partial is empty, then a. Let final be "{}". +/// 10. Else, a. If state.[[Gap]] is the empty String, then i. Let properties +/// be the String value formed by concatenating all the element Strings of +/// partial with each adjacent pair of Strings separated with the code unit +/// 0x002C (COMMA). ii. Let final be the string-concatenation of "{", +/// properties, and "}". b. Else, i. Let separator be the string-concatenation +/// of the code unit 0x002C (COMMA), the code unit 0x000A (LINE FEED), and +/// state.[[Indent]]. ii. Let properties be the String value formed by +/// concatenating all the element Strings of partial with each adjacent pair +/// separated with separator. iii. Let final be the string-concatenation of +/// "{", the code unit 0x000A (LINE FEED), state.[[Indent]], properties, the +/// code unit 0x000A (LINE FEED), stepback, and "}". +/// 11. Remove the last element of state.[[Stack]]. +/// 12. Set state.[[Indent]] to stepback. +/// 13. Return final. +fn serialize_object(vm: &mut Vm, state: &mut State, value: Value) -> Result, Abrupt> { + enter(vm, state, value)?; + let stepback = state.indent.clone(); + state.indent.extend_from_slice(&state.gap.clone()); + let keys: Vec = match &state.property_list { + Some(l) => l.clone(), + None => enumerable_keys(vm, value), + }; + let mut partial: Vec> = Vec::new(); + for p in keys { + if let Some(str_p) = serialize_property(vm, state, p, value)? { + let name: Vec = vm + .heap() + .key_string(p) + .map(|s| s.units().collect()) + .ok_or(Abrupt::Internal("key"))?; + let mut member = clazel_json::quote::quote(&name); + member.push(u16::from(b':')); + if !state.gap.is_empty() { + member.push(0x20); + } + member.extend(str_p); + partial.push(member); + } + } + let out = wrap(&partial, state, &stepback, b'{', b'}'); + state.stack.pop(); + state.indent = stepback; + Ok(out) +} + +/// Steps 9 and 10 of both serializers: `open`, the members and `close`. +fn wrap(partial: &[Vec], state: &State, stepback: &[u16], open: u8, close: u8) -> Vec { + let (open, close) = (u16::from(open), u16::from(close)); + if partial.is_empty() { + return vec![open, close]; + } + let mut out = vec![open]; + let sep: Vec = if state.gap.is_empty() { + vec![u16::from(b',')] + } else { + let mut s = vec![u16::from(b','), 0x0A]; + s.extend_from_slice(&state.indent); + s + }; + if !state.gap.is_empty() { + out.push(0x0A); + out.extend_from_slice(&state.indent); + } + for (i, m) in partial.iter().enumerate() { + if i > 0 { + out.extend_from_slice(&sep); + } + out.extend_from_slice(m); + } + if !state.gap.is_empty() { + out.push(0x0A); + out.extend_from_slice(stepback); + } + out.push(close); + out +} + +/// SerializeJSONArray ( state, value ), §25.5.2.6†: +/// 1. If state.[[Stack]] contains value, throw a TypeError exception because +/// the structure is cyclical. +/// 2. Append value to state.[[Stack]]. +/// 3. Let stepback be state.[[Indent]]. +/// 4. Set state.[[Indent]] to the string-concatenation of state.[[Indent]] and +/// state.[[Gap]]. +/// 5. Let partial be a new empty List. +/// 6. Let len be ? LengthOfArrayLike(value). +/// 7. Let index be 0. +/// 8. Repeat, while index < len, a. Let strP be ? SerializeJSONProperty(state, +/// ! ToString(𝔽(index)), value). b. If strP is undefined, then i. Append +/// "null" to partial. c. Else, i. Append strP to partial. d. Set index to +/// index + 1. +/// 9. If partial is empty, then a. Let final be "[]". +/// 10. Else, as step 10 of SerializeJSONObject with "[" and "]" and the +/// elements without names. +/// 11. Remove the last element of state.[[Stack]]. +/// 12. Set state.[[Indent]] to stepback. +/// 13. Return final. +fn serialize_array(vm: &mut Vm, state: &mut State, value: Value) -> Result, Abrupt> { + enter(vm, state, value)?; + let stepback = state.indent.clone(); + state.indent.extend_from_slice(&state.gap.clone()); + let lk = key_of(vm, &"length".encode_utf16().collect::>())?; + let lv = vm.get_value(value, lk)?; + let len = to_integer_or_infinity(vm, lv)?.clamp(0.0, 9_007_199_254_740_991.0); + let mut partial: Vec> = Vec::new(); + let mut index = 0.0f64; + while index < len { + let k = vm.index_key(index as u64)?; + match serialize_property(vm, state, k, value)? { + Some(s) => partial.push(s), + None => partial.push("null".encode_utf16().collect()), + } + index += 1.0; + } + let out = wrap(&partial, state, &stepback, b'[', b']'); + state.stack.pop(); + state.indent = stepback; + Ok(out) +} diff --git a/crates/clazel-js-builtins/src/lib.rs b/crates/clazel-js-builtins/src/lib.rs index 6480449c..2b2a5deb 100644 --- a/crates/clazel-js-builtins/src/lib.rs +++ b/crates/clazel-js-builtins/src/lib.rs @@ -15,17 +15,27 @@ //! `clazel-js-number`; //! - [`string`]: `String` (§22.1†) with `charAt`, `charCodeAt`, `indexOf`, //! `slice`, `substring`; +//! - [`array`]: `Array` (§23.1†), `Array.isArray`, `Array.of` and the core of +//! `Array.prototype` (`push`, `pop`, `shift`, `unshift`, `slice`, `splice`, +//! `concat`, `join`, `toString`, `indexOf`, `lastIndexOf`, `includes`, +//! `reverse`, `fill`, `forEach`, `map`, `filter`, `some`, `every`, `reduce`, +//! `reduceRight`, `find`, `findIndex`, `sort`); +//! - [`json`]: `JSON.parse` and `JSON.stringify` (§25.5†) over `clazel-json`; //! - [`math`]: the pure functions of `Math` (§21.3†); //! - [`global`]: `globalThis`, `isNaN`, `isFinite`, `parseInt`, `parseFloat` //! (§19†). //! //! # What this slice does not have, all listed //! -//! - **No arrays yet** (the heap's elements are an open pull request). -//! `Object.keys` returns an ordinary array-like object (`length` and index -//! properties, `%Object.prototype%` as prototype) through one function, -//! [`util::new_array_like`], which becomes `ArrayCreate` with arrays. It is -//! a deviation: `Array.isArray` of it would be false. +//! - **Array iteration is missing**: `Array.from`, `entries`, `keys`, +//! `values` and `@@iterator` wait for Symbols and iterators; so does array +//! spread (`GetIterator` is `NotYet`). `@@species` and +//! `@@isConcatSpreadable` are not consulted: `ArraySpeciesCreate` uses the +//! receiver's `constructor` itself. Not yet: `at`, `copyWithin`, `flat`, +//! `flatMap`, `findLast`, `findLastIndex`, `toLocaleString`, the change-by- +//! copy methods. Array elements are ordinary shape properties (the heap's +//! elements are an open pull request), so a huge sparse index or a long +//! `shift` is slow, not wrong. //! - **No Symbols**, so `@@toPrimitive`, `@@toStringTag` and `@@hasInstance` //! are not consulted; `Object.prototype.toString` tags by internal slot //! only. @@ -51,6 +61,7 @@ pub mod boolean; pub mod error; pub mod function; pub mod global; +pub mod json; pub mod math; pub mod number; pub mod object; @@ -73,5 +84,6 @@ pub fn install(vm: &mut Vm) -> Result<(), Abrupt> { number::install(vm)?; string::install(vm)?; math::install(vm)?; + json::install(vm)?; global::install(vm) } diff --git a/crates/clazel-js-builtins/tests/array.rs b/crates/clazel-js-builtins/tests/array.rs index ada7c066..a1d1a82e 100644 --- a/crates/clazel-js-builtins/tests/array.rs +++ b/crates/clazel-js-builtins/tests/array.rs @@ -56,7 +56,10 @@ fn array_exotic_objects() -> Result<(), String> { // §10.4.2.1 step 2.h: an index at or above `length` grows it. ("var a = []; a[4] = 1; var r = a.length;", "5"), ("var a = [1, 2, 3]; var r = a.length;", "3"), - ("var a = [1, , 3]; var r = a.length + ',' + (1 in a);", "3,false"), + ( + "var a = [1, , 3]; var r = a.length + ',' + (1 in a);", + "3,false", + ), ("var a = [1, 2, ,]; var r = a.length;", "3"), // A key that is not a canonical index does not. ("var a = []; a['01'] = 1; a.x = 2; var r = a.length;", "0"), @@ -115,7 +118,10 @@ fn array_exotic_objects() -> Result<(), String> { "var r = Array.isArray({ length: 0 }) + ',' + Array.isArray([]);", "false,true", ), - ("var r = Object.getPrototypeOf([]) === Array.prototype;", "true"), + ( + "var r = Object.getPrototypeOf([]) === Array.prototype;", + "true", + ), // Object.keys returns an array now. ("var r = Array.isArray(Object.keys({ a: 1 }));", "true"), ( @@ -172,7 +178,10 @@ fn array_mutators() -> Result<(), String> { "var a = [1, 2, 3]; var x = a.pop(); var r = x + ',' + a;", "3,1,2", ), - ("var a = []; var r = a.pop() + ',' + a.length;", "undefined,0"), + ( + "var a = []; var r = a.pop() + ',' + a.length;", + "undefined,0", + ), ( "var a = [1, 2, 3]; var x = a.shift(); var r = x + ',' + a + ',' + a.length;", "1,2,3,2", @@ -290,7 +299,10 @@ fn array_accessors() -> Result<(), String> { "var r = [, 1].includes(undefined) + ',' + [, 1].indexOf(undefined);", "true,-1", ), - ("var r = [0].includes(-0) + ',' + [-0].indexOf(0);", "true,0"), + ( + "var r = [0].includes(-0) + ',' + [-0].indexOf(0);", + "true,0", + ), ]) } diff --git a/crates/clazel-js-builtins/tests/json.rs b/crates/clazel-js-builtins/tests/json.rs new file mode 100644 index 00000000..ad1a64e0 --- /dev/null +++ b/crates/clazel-js-builtins/tests/json.rs @@ -0,0 +1,241 @@ +//! Tests of `JSON.parse` and `JSON.stringify`: scripts run with the built-ins +//! installed, each expectation what ECMA-262 §25.5† says, written by hand. +//! The result is the global `r` as its ToString. No files are read, so these +//! run under Miri too (every fourth case). + +use clazel_js_syntax::exec::parse; +use clazel_js_syntax::spec::SourceGoal; +use clazel_js_vm::compile::compile_script; +use clazel_js_vm::interp::{Config, Vm}; + +fn r_of(src: &str) -> Result { + let c: Vec = src.chars().map(u32::from).collect(); + let ast = parse(&c, SourceGoal::Script).map_err(|_| format!("does not parse: {src}"))?; + let p = compile_script(&ast, &c).map_err(|e| format!("{src}: {e}"))?; + let cfg = if cfg!(miri) { + Config { + region_slots: 1 << 12, + heap_cells: 1 << 14, + } + } else { + Config::default() + }; + let mut vm = Vm::new(cfg).map_err(|e| format!("{e:?}"))?; + clazel_js_builtins::install(&mut vm).map_err(|e| format!("install: {e:?}"))?; + let script = vm.load(&p).map_err(|e| format!("{e:?}"))?; + vm.set_budget(5_000_000); + vm.run(&script).map_err(|e| format!("{src}: {e:?}"))?; + let g = vm.global(); + let r = vm.get_named(g, "r").map_err(|e| format!("{e:?}"))?; + let s = vm.to_js_string(r).map_err(|e| format!("{src}: {e:?}"))?; + Ok(s.to_string_lossy()) +} + +fn check(cases: &[(&str, &str)]) -> Result<(), String> { + let stride = if cfg!(miri) { 4 } else { 1 }; + for (src, want) in cases.iter().step_by(stride) { + let got = r_of(src)?; + if got != *want { + return Err(format!("{src}: expected {want:?}, got {got:?}")); + } + } + Ok(()) +} + +#[test] +fn json_parse() -> Result<(), String> { + check(&[ + ("var r = JSON.parse('1') + JSON.parse(' 2.5e1 ');", "26"), + ("var r = JSON.parse('null') === null;", "true"), + ( + "var r = JSON.parse('true') && !JSON.parse('false');", + "true", + ), + ("var r = JSON.parse('\"a\\\\nb\"').length;", "3"), + ("var r = JSON.parse('\"\\\\u0041\"');", "A"), + ("var r = JSON.parse('[1,2,[3]]').join();", "1,2,3"), + ("var r = Array.isArray(JSON.parse('[]'));", "true"), + ( + "var o = JSON.parse('{\"a\":1,\"b\":{\"c\":2}}'); var r = o.a + o.b.c;", + "3", + ), + // A duplicate name takes the later value. + ("var r = JSON.parse('{\"a\":1,\"a\":2}').a;", "2"), + // Numbers: -0 and big exponents. + ("var r = 1 / JSON.parse('-0');", "-Infinity"), + ("var r = JSON.parse('1e400');", "Infinity"), + // SyntaxErrors. + ( + "var r; try { JSON.parse('{a:1}'); } catch (e) { r = e.name; }", + "SyntaxError", + ), + ( + "var r; try { JSON.parse(''); } catch (e) { r = e.name; }", + "SyntaxError", + ), + ( + "var r; try { JSON.parse('[1,]'); } catch (e) { r = e.name; }", + "SyntaxError", + ), + ( + "var r; try { JSON.parse('01'); } catch (e) { r = e.name; }", + "SyntaxError", + ), + ( + "var r; try { JSON.parse(\"'a'\"); } catch (e) { r = e.name; }", + "SyntaxError", + ), + ( + "var r; try { JSON.parse(undefined); } catch (e) { r = e.name; }", + "SyntaxError", + ), + // The nesting bound: 600 levels is a SyntaxError, 100 is fine. + ( + "var s = ''; for (var i = 0; i < 600; i++) s += '['; for (var i = 0; i < 600; i++) s += ']'; var r; try { JSON.parse(s); } catch (e) { r = e.name; }", + "SyntaxError", + ), + ( + "var s = ''; for (var i = 0; i < 100; i++) s += '['; for (var i = 0; i < 100; i++) s += ']'; var r = Array.isArray(JSON.parse(s));", + "true", + ), + // The deepest text the parser takes, revived. + ( + "var s = ''; for (var i = 0; i < 500; i++) s += '['; for (var i = 0; i < 500; i++) s += ']'; var n = 0; JSON.parse(s, function (k, v) { n++; return v; }); var r = n;", + "500", + ), + // The reviver, §25.5.1.1: bottom-up, holder as this, deletes on undefined. + ( + "var log = ''; JSON.parse('{\"a\":[1,2],\"b\":3}', function (k, v) { log += k + ';'; return v; }); var r = log;", + "0;1;a;b;;", + ), + ( + "var r = JSON.parse('[1,2,3]', function (k, v) { return typeof v === 'number' ? v * 2 : v; }).join();", + "2,4,6", + ), + ( + "var o = JSON.parse('{\"a\":1,\"b\":2}', function (k, v) { return k === 'a' ? undefined : v; }); var r = ('a' in o) + ',' + o.b;", + "false,2", + ), + ( + "var holder; JSON.parse('{\"x\":1}', function (k, v) { if (k === 'x') holder = this; return v; }); var r = holder.x;", + "1", + ), + ( + "var r = JSON.parse('5', function (k, v) { return k === '' ? v + 1 : v; });", + "6", + ), + ("var r = JSON.parse('[1]', 5).length;", "1"), + ]) +} + +#[test] +fn json_stringify() -> Result<(), String> { + check(&[ + ( + "var r = JSON.stringify(1) + JSON.stringify('a\"b') + JSON.stringify(null);", + "1\"a\\\"b\"null", + ), + ( + "var r = JSON.stringify(true) + JSON.stringify(false);", + "truefalse", + ), + ( + "var r = JSON.stringify(NaN) + JSON.stringify(Infinity) + JSON.stringify(-0);", + "nullnull0", + ), + ("var r = JSON.stringify(undefined);", "undefined"), + ("var r = JSON.stringify(function () {});", "undefined"), + ( + "var r = JSON.stringify([1, 'a', null, undefined, function () {}]);", + "[1,\"a\",null,null,null]", + ), + ( + "var r = JSON.stringify({ a: 1, b: undefined, c: function () {}, d: [2] });", + "{\"a\":1,\"d\":[2]}", + ), + ("var r = JSON.stringify({});", "{}"), + ("var r = JSON.stringify([]);", "[]"), + ( + "var r = JSON.stringify({ 2: 'x', 1: 'y', b: 0 });", + "{\"1\":\"y\",\"2\":\"x\",\"b\":0}", + ), + // Wrapper objects unwrap. + ( + "var r = JSON.stringify([new Number(3), new String('s'), new Boolean(false)]);", + "[3,\"s\",false]", + ), + // Quoting: control characters and lone surrogates. + ( + "var r = JSON.stringify('\\u0001\\n\\ud800');", + "\"\\u0001\\n\\ud800\"", + ), + // toJSON, §25.5.2.2 step 2. + ( + "var r = JSON.stringify({ toJSON: function (k) { return 'k=' + k; } });", + "\"k=\"", + ), + ( + "var r = JSON.stringify({ a: { toJSON: function (k) { return k + '!'; } } });", + "{\"a\":\"a!\"}", + ), + // The replacer function: holder as this, key and value. + ( + "var r = JSON.stringify({ a: 1, b: 2 }, function (k, v) { return k === 'a' ? undefined : v; });", + "{\"b\":2}", + ), + ( + "var r = JSON.stringify(1, function (k, v) { return k === '' ? v + 1 : v; });", + "2", + ), + // The replacer array: a property list, in its order, no duplicates. + ( + "var r = JSON.stringify({ a: 1, b: 2, c: 3 }, ['c', 'a', 'c', 5]);", + "{\"c\":3,\"a\":1}", + ), + ( + "var r = JSON.stringify({ 1: 'x', a: 'y' }, [1, new String('a')]);", + "{\"1\":\"x\",\"a\":\"y\"}", + ), + // The gap: a number (at most 10), a string (first 10 units), wrappers. + ( + "var r = JSON.stringify({ a: [1, { b: 2 }] }, null, 2);", + "{\n \"a\": [\n 1,\n {\n \"b\": 2\n }\n ]\n}", + ), + ("var r = JSON.stringify([1], null, '--');", "[\n--1\n]"), + ( + "var r = JSON.stringify([1], null, 'abcdefghijklmnop');", + "[\nabcdefghij1\n]", + ), + ("var r = JSON.stringify([1], null, 20).length;", "15"), + ("var r = JSON.stringify([1], null, 0.9);", "[1]"), + ( + "var r = JSON.stringify({ a: 1 }, null, new Number(1));", + "{\n \"a\": 1\n}", + ), + ( + "var r = JSON.stringify([], null, 2) + JSON.stringify({}, null, 2);", + "[]{}", + ), + // Cycles are a TypeError, §25.5.2.4 step 1. + ( + "var a = {}; a.self = a; var r; try { JSON.stringify(a); } catch (e) { r = e.name; }", + "TypeError", + ), + ( + "var a = []; a[0] = [a]; var r; try { JSON.stringify(a); } catch (e) { r = e.name; }", + "TypeError", + ), + // The same object twice (not a cycle) is fine. + ("var x = {}; var r = JSON.stringify([x, x]);", "[{},{}]"), + // Depth past the bound is a RangeError. + ( + "var a = []; for (var i = 0; i < 200; i++) a = [a]; var r; try { JSON.stringify(a); } catch (e) { r = e.name; }", + "RangeError", + ), + // Round trip. + ( + "var s = '{\"a\":[1,2,{\"b\":null}],\"c\":\"x\"}'; var r = JSON.stringify(JSON.parse(s)) === s;", + "true", + ), + ]) +} diff --git a/crates/clazel-js-vm/src/heap.rs b/crates/clazel-js-vm/src/heap.rs index f706e8f7..8e65b165 100644 --- a/crates/clazel-js-vm/src/heap.rs +++ b/crates/clazel-js-vm/src/heap.rs @@ -256,7 +256,8 @@ impl Heap { /// Whether a value is an Array exotic object. #[must_use] pub fn is_array_object(&self, v: Value) -> bool { - self.obj(v).is_some_and(|o| matches!(o.kind, ObjKind::Array)) + self.obj(v) + .is_some_and(|o| matches!(o.kind, ObjKind::Array)) } /// The array index a key names (§6.1.7†), if it names one. diff --git a/crates/clazel-js-vm/src/props.rs b/crates/clazel-js-vm/src/props.rs index d209a631..5e856161 100644 --- a/crates/clazel-js-vm/src/props.rs +++ b/crates/clazel-js-vm/src/props.rs @@ -84,11 +84,7 @@ impl Vm { /// /// # Errors /// [`Abrupt::Internal`] if the heap is corrupt. - pub fn get_own_property( - &self, - obj: Value, - key: Key, - ) -> Result, Abrupt> { + pub fn get_own_property(&self, obj: Value, key: Key) -> Result, Abrupt> { let Some(f) = self.heap.find(obj, key)?.filter(|f| f.own) else { return Ok(None); }; @@ -214,7 +210,9 @@ impl Vm { return Ok(false); } if index >= length { - let new_len = index.checked_add(1).ok_or(Abrupt::Internal("array index"))?; + let new_len = index + .checked_add(1) + .ok_or(Abrupt::Internal("array index"))?; self.heap.set_array_length(obj, new_len)?; } Ok(true) From 74629cbae90d00d925bf24ae5766332f8138437a Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sun, 22 Nov 2026 15:26:52 +0000 Subject: [PATCH 5/6] clazel-js-vm, clazel-js-builtins: clippy and doc fixes, Cargo.lock Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-builtins/src/array.rs | 4 ++-- crates/clazel-js-vm/src/props.rs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/clazel-js-builtins/src/array.rs b/crates/clazel-js-builtins/src/array.rs index 9624b60f..a5c864c5 100644 --- a/crates/clazel-js-builtins/src/array.rs +++ b/crates/clazel-js-builtins/src/array.rs @@ -432,8 +432,8 @@ fn unshift(vm: &mut Vm, this: Value, args: &[Value]) -> Result { /// exception. /// 12. Let A be ? ArraySpeciesCreate(O, actualDeleteCount). /// 13. Let k be 0. -/// 14. Repeat, while k < actualDeleteCount, a. Let from be ! ToString(𝔽(actualStart -/// + k)). b. If ? HasProperty(O, from) is true, then i. Let fromValue be ? +/// 14. Repeat, while k < actualDeleteCount, a. Let from be ! +/// ToString(𝔽(actualStart plus k)). b. If ? HasProperty(O, from) is true, then i. Let fromValue be ? /// Get(O, from). ii. Perform ? CreateDataPropertyOrThrow(A, ! ToString(𝔽(k)), /// fromValue). c. Set k to k + 1. /// 15. Perform ? Set(A, "length", 𝔽(actualDeleteCount), true). diff --git a/crates/clazel-js-vm/src/props.rs b/crates/clazel-js-vm/src/props.rs index 5e856161..50c91e54 100644 --- a/crates/clazel-js-vm/src/props.rs +++ b/crates/clazel-js-vm/src/props.rs @@ -175,10 +175,10 @@ impl Vm { /// false. /// f. Let succeeded be ! OrdinaryDefineOwnProperty(A, P, Desc). /// g. If succeeded is false, return false. - /// h. If index >= length, then i. Set lengthDesc.[[Value]] to index + - /// 1. ii. Set succeeded to ! OrdinaryDefineOwnProperty(A, "length", - /// lengthDesc). iii. (Assert: succeeded is true.) - /// i. Return true. + /// h. If index >= length, then i. Set lengthDesc.[[Value]] to + /// index + 1. ii. Set succeeded to ! OrdinaryDefineOwnProperty(A, + /// "length", lengthDesc). iii. (Assert: succeeded is true.) + /// j. Return true. /// 3. Return ? OrdinaryDefineOwnProperty(A, P, Desc). /// /// # Errors @@ -287,7 +287,7 @@ impl Vm { .filter_map(|(k, _, _)| self.heap.key_index(k).map(|i| (i, k))) .filter(|(i, _)| *i >= new_len) .collect(); - doomed.sort_by(|x, y| y.0.cmp(&x.0)); + doomed.sort_by_key(|x| std::cmp::Reverse(x.0)); for (i, k) in &doomed { let configurable = self .get_own_property(a, *k)? From 7d03d052e9d9518ae962a5cca2389c6f39c2b98f Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sun, 22 Nov 2026 15:49:21 +0000 Subject: [PATCH 6/6] clazel-js-builtins: every eighth array and JSON case under Miri Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js-builtins/tests/array.rs | 4 ++-- crates/clazel-js-builtins/tests/json.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/clazel-js-builtins/tests/array.rs b/crates/clazel-js-builtins/tests/array.rs index a1d1a82e..c6cf1c3c 100644 --- a/crates/clazel-js-builtins/tests/array.rs +++ b/crates/clazel-js-builtins/tests/array.rs @@ -2,7 +2,7 @@ //! built-in, as small scripts run with the built-ins installed. Each //! expectation is what ECMA-262 says, written by hand; the result is the //! global `r` as its ToString. No files are read, so these run under Miri -//! too (with every fourth case, as the other built-in tests do). +//! too (with every eighth case, as the other built-in tests do). use clazel_js_syntax::exec::parse; use clazel_js_syntax::spec::SourceGoal; @@ -40,7 +40,7 @@ fn r_of(src: &str) -> Result { } fn check(cases: &[(&str, &str)]) -> Result<(), String> { - let stride = if cfg!(miri) { 4 } else { 1 }; + let stride = if cfg!(miri) { 8 } else { 1 }; for (src, want) in cases.iter().step_by(stride) { let got = r_of(src)?; if got != *want { diff --git a/crates/clazel-js-builtins/tests/json.rs b/crates/clazel-js-builtins/tests/json.rs index ad1a64e0..27448c5c 100644 --- a/crates/clazel-js-builtins/tests/json.rs +++ b/crates/clazel-js-builtins/tests/json.rs @@ -1,7 +1,7 @@ //! Tests of `JSON.parse` and `JSON.stringify`: scripts run with the built-ins //! installed, each expectation what ECMA-262 §25.5† says, written by hand. //! The result is the global `r` as its ToString. No files are read, so these -//! run under Miri too (every fourth case). +//! run under Miri too (every eighth case). use clazel_js_syntax::exec::parse; use clazel_js_syntax::spec::SourceGoal; @@ -32,7 +32,7 @@ fn r_of(src: &str) -> Result { } fn check(cases: &[(&str, &str)]) -> Result<(), String> { - let stride = if cfg!(miri) { 4 } else { 1 }; + let stride = if cfg!(miri) { 8 } else { 1 }; for (src, want) in cases.iter().step_by(stride) { let got = r_of(src)?; if got != *want {