Merge pull request #9072 from dotCooCoo/feat/js-es2015-collections-typed-arrays

JavaScript: ES2015 realms have Map, Set, WeakMap, WeakSet and typed arrays
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-27 23:55:19 -08:00
commit bbefa3c8e3
13 files changed
+3004 -31

No files matched your search

+16 -3
View File
@@ -4,14 +4,17 @@
//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and
//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in
//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`),
//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator
//! objects' prototypes with `GeneratorFunction` (in `generator`).
//! the iterators of arrays, strings and `arguments` objects (in `iterator`), the generator
//! objects' prototypes with `GeneratorFunction` (in `generator`), `Map`, `Set`, `WeakMap` and
//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`).
//!
//! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object
//! or property it makes is checked against the heap limit before it is made, so no built-in can
//! run past [`crate::Limits`].
mod array;
pub(crate) mod binary;
pub(crate) mod collections;
pub(crate) mod extensions;
mod generator;
mod global;
@@ -270,6 +273,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
}
if interp.options.es2015 {
promise::install(interp)?;
collections::install(interp)?;
binary::install(interp)?;
}
Ok(())
}
@@ -291,8 +296,16 @@ fn key_of(n: f64) -> Key {
number_to_str(n).flat()
}
/// ToUint32 of an object's `length`.
/// ToUint32 of an object's `length`. While a `%TypedArray%.prototype` method runs the array
/// method it shares, the typed array's length is its element count, whatever its `length`
/// property says (ECMA-262 6.0 section 22.2.3).
fn length_of(interp: &mut Interp, o: ObjId) -> JsResult<u32> {
if interp.typed_length == Some(o) {
interp.typed_length = None;
if let Some(Class::TypedArray(view)) = interp.heap.object(o).map(|obj| &obj.class) {
return Ok(u32::try_from(view.length).unwrap_or(u32::MAX));
}
}
let len = interp.get_from(o, &key("length"), &Value::Object(o))?;
Ok(to_uint32(interp.to_number(&len)?))
}
+44 -17
View File
@@ -96,15 +96,23 @@ fn numeric_index(k: &[u16]) -> Option<u64> {
Some(n)
}
/// The objects of the prototype chain from `obj`, with how many properties (and String object
/// indices) each holds.
/// The indices a String object or a typed array holds without properties for them.
fn index_count(class: &Class) -> usize {
match class {
Class::String(s) => s.len(),
Class::TypedArray(view) => view.length,
_ => 0,
}
}
/// The objects of the prototype chain from `obj`, with how many properties (and String object or
/// typed array indices) each holds.
fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> {
let mut out = Vec::new();
let mut cur = Some(obj);
while let Some(id) = cur {
let Some(o) = interp.heap.object(id) else { break };
let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 };
out.push((id, o.props.len().saturating_add(string_len)));
out.push((id, o.props.len().saturating_add(index_count(&o.class))));
cur = o.proto;
}
out
@@ -141,8 +149,7 @@ impl Indices {
}
interp.reserve_heap(n.saturating_mul(8).saturating_mul(self.maps.len() + 1))?;
let Some(o) = interp.heap.object(id) else { continue };
let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 };
let present = (0..string_len as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k)));
let present = (0..index_count(&o.class) as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k)));
for p in present {
for map in &self.maps {
let p = p as i64;
@@ -324,18 +331,32 @@ fn join_item(interp: &mut Interp, v: Value) -> JsResult<Option<Str>> {
/// An element as `toLocaleString` writes it (section 15.4.4.3).
fn locale_item(interp: &mut Interp, v: Value) -> JsResult<Option<Str>> {
locale_call(interp, v, false)
}
/// An element as `%TypedArray%.prototype.toLocaleString` writes it (ECMA-262 6.0 section
/// 22.2.3.27): the method is called on the element's value, not on its object.
fn typed_locale_item(interp: &mut Interp, v: Value) -> JsResult<Option<Str>> {
locale_call(interp, v, true)
}
/// Calls the element's `toLocaleString`, looked up on its object. With `on_value`, the value
/// itself is `this` for the lookup's getter and for the call (Invoke, section 7.3.18); otherwise
/// the object is.
fn locale_call(interp: &mut Interp, v: Value, on_value: bool) -> JsResult<Option<Str>> {
if v.is_nullish() {
return Ok(None);
}
let e = interp.to_object(&v)?;
let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &Value::Object(e))?;
let this = if on_value { v } else { Value::Object(e) };
let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &this)?;
require_callable(interp, &f, "an element's toLocaleString")?;
let s = interp.call(&f, &Value::Object(e), &[])?;
let s = interp.call(&f, &this, &[])?;
interp.to_str(&s).map(Some)
}
/// `Array.prototype.join` (section 15.4.4.5).
fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let separator = arg(args, 0);
with_this(interp, &this, |interp, o| join_with(interp, o, &separator, join_item))
}
@@ -345,6 +366,12 @@ fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J
with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item))
}
/// `%TypedArray%.prototype.toLocaleString` (ECMA-262 6.0 section 22.2.3.27), the array method
/// with each element's method called on the element's value.
pub(super) fn typed_to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, typed_locale_item))
}
// ---- methods that change the object ----
/// `Array.prototype.concat` (section 15.4.4.4).
@@ -413,7 +440,7 @@ fn push(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<V
}
/// `Array.prototype.reverse` (section 15.4.4.8).
fn reverse(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn reverse(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
with_this(interp, &this, |interp, o| {
let len = u64::from(length_of(interp, o)?);
let middle = len / 2;
@@ -692,7 +719,7 @@ fn sort_elements(interp: &mut Interp, o: ObjId, len: u64, compare: &Value) -> Js
// ---- searching ----
/// `Array.prototype.indexOf` (section 15.4.4.14).
fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
with_this(interp, &this, |interp, o| {
let len = f64::from(length_of(interp, o)?);
if len == 0.0 {
@@ -717,7 +744,7 @@ fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu
}
/// `Array.prototype.lastIndexOf` (section 15.4.4.15).
fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
with_this(interp, &this, |interp, o| {
let len = f64::from(length_of(interp, o)?);
if len == 0.0 {
@@ -794,15 +821,15 @@ fn iterate(interp: &mut Interp, this: Value, args: &[Value], kind: Each) -> JsRe
})
}
fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
iterate(interp, this, args, Each::Every)
}
fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
iterate(interp, this, args, Each::Some)
}
fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
iterate(interp, this, args, Each::Visit)
}
@@ -852,10 +879,10 @@ fn fold(interp: &mut Interp, this: Value, args: &[Value], right: bool) -> JsResu
})
}
fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
fold(interp, this, args, false)
}
fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
pub(super) fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
fold(interp, this, args, true)
}
File diff suppressed because it is too large. Load diff
+697
View File
@@ -0,0 +1,697 @@
//! `Map`, `Set`, `WeakMap` and `WeakSet` (ECMA-262 6.0 sections 23.1 to 23.4), and the iterator
//! objects that `keys`, `values` and `entries` give for Maps, Sets and typed arrays (sections
//! 23.1.5, 23.2.5 and 22.1.5). A realm has them with [`crate::Options::es2015`].
//!
//! Keys compare with SameValueZero, and a key of `-0` is stored as `+0`. Entries keep the order
//! they were added in; deleting one leaves a hole, so `forEach` and an iterator visit the entries
//! added while they run and skip the ones deleted before they reach them. WeakMap and WeakSet
//! entries hold their key weakly: the collector removes an entry once its key is reachable only
//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed.
//!
//! The language has no iterators yet, so the constructors read their argument by index: an
//! array or an object with a `length`, or a string by code point. Every entry added is checked
//! against the heap limit before it is added, and every entry visited takes a unit of fuel.
use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable};
use crate::heap::{
COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object,
PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes,
};
use crate::interp::{Abrupt, Interp, JsResult};
use crate::string_builtins::flat_charged;
use crate::value::{Str, Value};
/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does
/// to the globals.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Es2015 {
pub(crate) map_proto: ObjId,
pub(crate) set_proto: ObjId,
pub(crate) weak_map_proto: ObjId,
pub(crate) weak_set_proto: ObjId,
pub(crate) map_iter_proto: ObjId,
pub(crate) set_iter_proto: ObjId,
pub(crate) array_iter_proto: ObjId,
pub(crate) array_buffer_proto: ObjId,
pub(crate) data_view_proto: ObjId,
/// `%TypedArray%` and its prototype (section 22.2.1).
pub(crate) typed_array_ctor: ObjId,
pub(crate) typed_array_proto: ObjId,
/// The typed array constructors and prototypes, in the order of [`crate::heap::Elem::ALL`].
pub(crate) typed_ctors: [ObjId; 9],
pub(crate) typed_protos: [ObjId; 9],
}
impl Es2015 {
pub(crate) fn placeholder() -> Self {
let o = ObjId(0);
Self {
map_proto: o,
set_proto: o,
weak_map_proto: o,
weak_set_proto: o,
map_iter_proto: o,
set_iter_proto: o,
array_iter_proto: o,
array_buffer_proto: o,
data_view_proto: o,
typed_array_ctor: o,
typed_array_proto: o,
typed_ctors: [o; 9],
typed_protos: [o; 9],
}
}
pub(crate) fn all(&self) -> Vec<ObjId> {
let mut v = vec![
self.map_proto,
self.set_proto,
self.weak_map_proto,
self.weak_set_proto,
self.map_iter_proto,
self.set_iter_proto,
self.array_iter_proto,
self.array_buffer_proto,
self.data_view_proto,
self.typed_array_ctor,
self.typed_array_proto,
];
v.extend(self.typed_ctors);
v.extend(self.typed_protos);
v
}
}
/// A new ordinary object with `proto`, for a prototype.
pub(crate) fn new_proto(interp: &mut Interp, proto: ObjId) -> ObjId {
interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))
}
/// Defines a getter `name` on `on`, configurable and not enumerable, as the prototype accessors
/// of ECMAScript 2015 are.
pub(crate) fn getter(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn) -> JsResult<()> {
let g = native(interp, name, f, 0, NativeKind::Plain, false)?;
let prop_name = name.strip_prefix("get ").unwrap_or(name);
interp.define(on, key(prop_name), Prop::Accessor { get: Some(g), set: None, flags: CONFIGURABLE })
}
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
let object_proto = interp.intrinsics.object_proto;
let map_proto = new_proto(interp, object_proto);
interp.intrinsics.es2015.map_proto = map_proto;
let map = native(interp, "Map", map_ctor, 0, NativeKind::Plain, true)?;
constructor(interp, "Map", map, map_proto)?;
let map_methods: [(&'static str, NativeFn, u32); 9] = [
("get", map_get, 1),
("set", map_set, 2),
("has", map_has, 1),
("delete", map_delete, 1),
("clear", map_clear, 0),
("forEach", map_for_each, 1),
("keys", map_keys, 0),
("values", map_values, 0),
("entries", map_entries, 0),
];
for (name, f, length) in map_methods {
method(interp, map_proto, name, f, length)?;
}
getter(interp, map_proto, "get size", map_size)?;
let set_proto = new_proto(interp, object_proto);
interp.intrinsics.es2015.set_proto = set_proto;
let set = native(interp, "Set", set_ctor, 0, NativeKind::Plain, true)?;
constructor(interp, "Set", set, set_proto)?;
let set_methods: [(&'static str, NativeFn, u32); 7] = [
("has", set_has, 1),
("add", set_add, 1),
("delete", set_delete, 1),
("clear", set_clear, 0),
("entries", set_entries, 0),
("forEach", set_for_each, 1),
("values", set_values, 0),
];
for (name, f, length) in set_methods {
method(interp, set_proto, name, f, length)?;
}
getter(interp, set_proto, "get size", set_size)?;
// `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8).
let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?;
interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?;
let weak_map_proto = new_proto(interp, object_proto);
interp.intrinsics.es2015.weak_map_proto = weak_map_proto;
let weak_map = native(interp, "WeakMap", weak_map_ctor, 0, NativeKind::Plain, true)?;
constructor(interp, "WeakMap", weak_map, weak_map_proto)?;
let weak_map_methods: [(&'static str, NativeFn, u32); 4] =
[("delete", weak_map_delete, 1), ("get", weak_map_get, 1), ("has", weak_map_has, 1), ("set", weak_map_set, 2)];
for (name, f, length) in weak_map_methods {
method(interp, weak_map_proto, name, f, length)?;
}
let weak_set_proto = new_proto(interp, object_proto);
interp.intrinsics.es2015.weak_set_proto = weak_set_proto;
let weak_set = native(interp, "WeakSet", weak_set_ctor, 0, NativeKind::Plain, true)?;
constructor(interp, "WeakSet", weak_set, weak_set_proto)?;
let weak_set_methods: [(&'static str, NativeFn, u32); 3] = [("add", weak_set_add, 1), ("delete", weak_set_delete, 1), ("has", weak_set_has, 1)];
for (name, f, length) in weak_set_methods {
method(interp, weak_set_proto, name, f, length)?;
}
for source in [IterSource::Map, IterSource::Set, IterSource::Array] {
let proto = new_proto(interp, object_proto);
let next: NativeFn = match source {
IterSource::Map => map_iterator_next,
IterSource::Set => set_iterator_next,
IterSource::Array => array_iterator_next,
};
method(interp, proto, "next", next, 0)?;
match source {
IterSource::Map => interp.intrinsics.es2015.map_iter_proto = proto,
IterSource::Set => interp.intrinsics.es2015.set_iter_proto = proto,
IterSource::Array => interp.intrinsics.es2015.array_iter_proto = proto,
}
}
Ok(())
}
// ---- keys ----
/// The SameValueZero key of `v`. A string is flattened, its copy charged to the heap.
fn coll_key(interp: &mut Interp, v: &Value) -> JsResult<CollKey> {
Ok(match v {
Value::Undefined => CollKey::Undefined,
Value::Null => CollKey::Null,
Value::Bool(b) => CollKey::Bool(*b),
Value::Number(n) => CollKey::number(*n),
Value::String(s) => CollKey::String(flat_charged(interp, s)?),
Value::Symbol(s) => CollKey::Symbol(s.clone()),
Value::Object(o) => CollKey::Object(o.0),
})
}
/// `v`, with `-0` made `+0`, as Map and Set store a key (sections 23.1.3.9 and 23.2.3.1).
fn stored_key(v: Value) -> Value {
match v {
// `-0 + 0` is `+0`, and every other number is unchanged by adding `+0`.
Value::Number(n) => Value::Number(n + 0.0),
v => v,
}
}
// ---- reading a list ----
/// ToLength (section 7.1.15) of an object's `length`.
pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult<u64> {
let len = interp.get_from(o, &key("length"), &Value::Object(o))?;
let n = super::to_integer(interp, &len)?;
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 })
}
/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`,
/// or a string's code points. Any other value is a `TypeError`, and so is an object without a
/// `length` when `need_length` is true. Each item takes a unit of fuel.
pub(crate) fn for_each_item(
interp: &mut Interp,
list: &Value,
need_length: bool,
mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>,
) -> JsResult<()> {
match list {
Value::Object(o) => {
if need_length && !interp.has_property(*o, &key("length"))? {
return Err(interp.type_error("the value is not an array, a string or an object with a length"));
}
let len = length_of(interp, *o)?;
let mut i = 0u64;
while i < len {
interp.use_fuel()?;
#[allow(clippy::cast_precision_loss)]
let item = interp.get_from(*o, &key_of(i as f64), list)?;
f(interp, item)?;
i += 1;
}
Ok(())
}
Value::String(s) => {
let units = flat_charged(interp, s)?;
let mut i = 0;
while i < units.len() {
interp.use_fuel()?;
let width = match (units.get(i), units.get(i + 1)) {
(Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2,
_ => 1,
};
let piece = units.get(i..i + width).unwrap_or_default().to_vec();
let bytes = string_bytes(piece.len());
interp.reserve_heap(bytes)?;
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
f(interp, Value::String(Str::from_units(piece)))?;
i += width;
}
Ok(())
}
_ => Err(interp.type_error("the value is not an array, a string or an object with a length")),
}
}
/// Adds the items of `list` to the new collection `target` with its `adder` method, as the
/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item
/// as a `[key, value]` entry.
fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> {
if list.is_nullish() {
return Ok(());
}
let this = Value::Object(target);
interp.rooted(&[this.clone(), list.clone()], |interp| {
let add = interp.get_from(target, &key(adder), &this)?;
require_callable(interp, &add, adder)?;
interp.rooted(std::slice::from_ref(&add), |interp| {
for_each_item(interp, list, true, |interp, item| {
if !pairs {
return interp.call(&add, &this, &[item]).map(drop);
}
let Value::Object(entry) = item else { return Err(interp.type_error("an entry is not an object")) };
let k = interp.get_from(entry, &key("0"), &item)?;
let v = interp.rooted(std::slice::from_ref(&k), |interp| interp.get_from(entry, &key("1"), &item))?;
interp.call(&add, &this, &[k, v]).map(drop)
})
})
})
}
/// A new collection object of `class` with `proto`, filled from `args[0]`.
fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult<Value> {
if !constructing {
return Err(interp.type_error(&format!("{name} must be called with new")));
}
interp.reserve_heap(OBJECT_BYTES)?;
let o = interp.heap.alloc_object(Object::new(class, Some(proto)));
let (adder, pairs) = match name {
"Map" | "WeakMap" => ("set", true),
_ => ("add", false),
};
fill(interp, o, &arg(args, 0), adder, pairs)?;
Ok(Value::Object(o))
}
fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult<Value> {
let proto = interp.intrinsics.es2015.map_proto;
construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto)
}
fn set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult<Value> {
let proto = interp.intrinsics.es2015.set_proto;
construct(interp, args, constructing, "Set", Class::Set(Box::default()), proto)
}
fn weak_map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult<Value> {
let proto = interp.intrinsics.es2015.weak_map_proto;
construct(interp, args, constructing, "WeakMap", Class::WeakMap(Box::default()), proto)
}
fn weak_set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult<Value> {
let proto = interp.intrinsics.es2015.weak_set_proto;
construct(interp, args, constructing, "WeakSet", Class::WeakSet(Box::default()), proto)
}
// ---- Map and Set ----
/// The Map (or with `set`, the Set) a method was called on.
fn this_coll(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult<ObjId> {
if let Value::Object(o) = this
&& let Some(obj) = interp.heap.object(*o)
&& matches!((&obj.class, set), (Class::Map(_), false) | (Class::Set(_), true))
{
return Ok(*o);
}
let name = if set { "Set" } else { "Map" };
Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}")))
}
fn coll(interp: &Interp, o: ObjId) -> JsResult<&Coll> {
match &interp.object(o)?.class {
Class::Map(c) | Class::Set(c) => Ok(c),
_ => Err(Abrupt::Internal("not a Map or a Set".into())),
}
}
fn coll_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut Coll> {
match &mut interp.object_mut(o)?.class {
Class::Map(c) | Class::Set(c) => Ok(c),
_ => Err(Abrupt::Internal("not a Map or a Set".into())),
}
}
/// Adds or replaces the entry of `k`, reserving the heap for a new one first.
fn coll_put(interp: &mut Interp, o: ObjId, k: Value, v: Value) -> JsResult<()> {
let ck = coll_key(interp, &k)?;
if !coll(interp, o)?.has(&ck) {
interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(COLL_ENTRY_BYTES))?;
interp.heap.bytes = interp.heap.bytes.saturating_add(COLL_ENTRY_BYTES);
}
coll_mut(interp, o)?.set(ck, stored_key(k), v);
Ok(())
}
fn map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = this_coll(interp, &this, false, "get")?;
let k = coll_key(interp, &arg(args, 0))?;
Ok(coll(interp, o)?.get(&k).cloned().unwrap_or(Value::Undefined))
}
fn map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = this_coll(interp, &this, false, "set")?;
coll_put(interp, o, arg(args, 0), arg(args, 1))?;
Ok(this)
}
fn has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult<Value> {
let o = this_coll(interp, this, set, "has")?;
let k = coll_key(interp, &arg(args, 0))?;
Ok(Value::Bool(coll(interp, o)?.has(&k)))
}
fn delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult<Value> {
let o = this_coll(interp, this, set, "delete")?;
let k = coll_key(interp, &arg(args, 0))?;
Ok(Value::Bool(coll_mut(interp, o)?.delete(&k)))
}
fn clear(interp: &mut Interp, this: &Value, set: bool) -> JsResult<Value> {
let o = this_coll(interp, this, set, "clear")?;
let slots = coll(interp, o)?.slots();
// Clearing visits every position, and each takes a unit of fuel.
for _ in 0..slots {
interp.use_fuel()?;
}
coll_mut(interp, o)?.clear();
Ok(Value::Undefined)
}
fn size(interp: &mut Interp, this: &Value, set: bool) -> JsResult<Value> {
let o = this_coll(interp, this, set, "size")?;
#[allow(clippy::cast_precision_loss)]
Ok(Value::Number(coll(interp, o)?.len() as f64))
}
fn map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
has(interp, &this, args, false)
}
fn map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
delete(interp, &this, args, false)
}
fn map_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
clear(interp, &this, false)
}
fn map_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
size(interp, &this, false)
}
fn set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = this_coll(interp, &this, true, "add")?;
coll_put(interp, o, arg(args, 0), Value::Undefined)?;
Ok(this)
}
fn set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
has(interp, &this, args, true)
}
fn set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
delete(interp, &this, args, true)
}
fn set_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
clear(interp, &this, true)
}
fn set_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
size(interp, &this, true)
}
/// `forEach` (sections 23.1.3.5 and 23.2.3.6): calls `f` with each entry's value, its key (for a
/// Set, the value again) and the collection, in order, visiting entries added while it runs. The
/// position is kept in an iterator object, so a collection that removes holes moves it.
fn for_each(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult<Value> {
let o = this_coll(interp, this, set, "forEach")?;
let f = arg(args, 0);
require_callable(interp, &f, "the callback")?;
let this_arg = arg(args, 1);
let source = if set { IterSource::Set } else { IterSource::Map };
let it = new_iter(interp, o, source, IterKind::Entries, None)?;
interp.rooted(&[Value::Object(it), f.clone(), this_arg.clone()], |interp| {
while let Some((k, v)) = advance(interp, it)? {
let v = if set { k.clone() } else { v };
interp.call(&f, &this_arg, &[v, k, Value::Object(o)])?;
}
Ok(Value::Undefined)
})
}
fn map_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
for_each(interp, &this, args, false)
}
fn set_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
for_each(interp, &this, args, true)
}
// ---- iterators ----
/// A new iterator over `target`, with `proto` (by default the prototype for `source`).
pub(crate) fn new_iter(interp: &mut Interp, target: ObjId, source: IterSource, kind: IterKind, proto: Option<ObjId>) -> JsResult<ObjId> {
interp.rooted(&[Value::Object(target)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?;
let proto = proto.unwrap_or(match source {
IterSource::Map => interp.intrinsics.es2015.map_iter_proto,
IterSource::Set => interp.intrinsics.es2015.set_iter_proto,
IterSource::Array => interp.intrinsics.es2015.array_iter_proto,
});
let state = IterState { source, kind, target: Some(target), pos: 0 };
let it = interp.heap.alloc_object(Object::new(Class::Iter(Box::new(state)), Some(proto)));
interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES);
Ok(it)
}
/// The next entry of a Map or Set iterator, or `None` when it has finished. Each position
/// passed takes a unit of fuel.
fn advance(interp: &mut Interp, it: ObjId) -> JsResult<Option<(Value, Value)>> {
loop {
interp.use_fuel()?;
let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) };
let (Some(target), pos) = (state.target, state.pos) else { return Ok(None) };
let c = coll(interp, target)?;
let found = (pos < c.slots()).then(|| c.entry(pos).cloned());
let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) };
match found {
None => {
state.target = None;
return Ok(None);
}
Some(entry) => {
state.pos = pos + 1;
if let Some(entry) = entry {
return Ok(Some(entry));
}
}
}
}
}
/// An iterator result object `{ value, done }` (section 7.4.7).
pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult<Value> {
interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * (PROP_BYTES + string_bytes(5))))?;
let o = interp.new_object();
interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?;
interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?;
Ok(Value::Object(o))
}
/// A new array `[a, b]`.
pub(crate) fn pair(interp: &mut Interp, a: Value, b: Value) -> JsResult<Value> {
interp.rooted(&[a.clone(), b.clone()], |interp| {
let arr = new_array(interp, 0)?;
interp.rooted(&[Value::Object(arr)], |interp| {
create_at(interp, arr, 0.0, a.clone())?;
create_at(interp, arr, 1.0, b.clone())?;
Ok(Value::Object(arr))
})
})
}
/// The iterator a `next` method was called on, when it goes through `source`.
fn this_iter(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult<(ObjId, IterKind)> {
if let Value::Object(o) = this
&& let Some(Class::Iter(state)) = interp.heap.object(*o).map(|o| &o.class)
&& state.source == source
{
return Ok((*o, state.kind));
}
Err(interp.type_error(&format!("{name} Iterator.prototype.next was called on a value that is not a {name} Iterator")))
}
fn coll_next(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult<Value> {
let (it, kind) = this_iter(interp, this, source, name)?;
let Some((k, v)) = advance(interp, it)? else { return iter_result(interp, Value::Undefined, true) };
let value = match (kind, source) {
(IterKind::Keys, _) | (IterKind::Values, IterSource::Set) => k,
(IterKind::Values, _) => v,
(IterKind::Entries, IterSource::Set) => pair(interp, k.clone(), k)?,
(IterKind::Entries, _) => pair(interp, k, v)?,
};
iter_result(interp, value, false)
}
fn map_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
coll_next(interp, &this, IterSource::Map, "Map")
}
fn set_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
coll_next(interp, &this, IterSource::Set, "Set")
}
/// `%ArrayIteratorPrototype%.next` (section 22.1.5.2.1) for the iterators of typed arrays.
fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
let (it, kind) = this_iter(interp, &this, IterSource::Array, "Array")?;
interp.use_fuel()?;
let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) };
let (target, pos) = (state.target, state.pos);
let element = match target {
Some(t) => match &interp.object(t)?.class {
Class::TypedArray(view) => super::binary::element(interp, view, pos as f64),
_ => None,
},
None => None,
};
let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) };
let Some(element) = element else {
state.target = None;
return iter_result(interp, Value::Undefined, true);
};
state.pos = pos + 1;
#[allow(clippy::cast_precision_loss)]
let index = Value::Number(pos as f64);
let value = match kind {
IterKind::Keys => index,
IterKind::Values => Value::Number(element),
IterKind::Entries => pair(interp, index, Value::Number(element))?,
};
iter_result(interp, value, false)
}
fn iter_method(interp: &mut Interp, this: &Value, set: bool, kind: IterKind, name: &str) -> JsResult<Value> {
let o = this_coll(interp, this, set, name)?;
let source = if set { IterSource::Set } else { IterSource::Map };
new_iter(interp, o, source, kind, None).map(Value::Object)
}
fn map_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
iter_method(interp, &this, false, IterKind::Keys, "keys")
}
fn map_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
iter_method(interp, &this, false, IterKind::Values, "values")
}
fn map_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
iter_method(interp, &this, false, IterKind::Entries, "entries")
}
fn set_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
iter_method(interp, &this, true, IterKind::Values, "values")
}
fn set_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
iter_method(interp, &this, true, IterKind::Entries, "entries")
}
// ---- WeakMap and WeakSet ----
fn this_weak(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult<ObjId> {
if let Value::Object(o) = this
&& let Some(obj) = interp.heap.object(*o)
&& matches!((&obj.class, set), (Class::WeakMap(_), false) | (Class::WeakSet(_), true))
{
return Ok(*o);
}
let name = if set { "WeakSet" } else { "WeakMap" };
Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}")))
}
fn weak(interp: &Interp, o: ObjId) -> JsResult<&WeakColl> {
match &interp.object(o)?.class {
Class::WeakMap(w) | Class::WeakSet(w) => Ok(w),
_ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())),
}
}
fn weak_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut WeakColl> {
match &mut interp.object_mut(o)?.class {
Class::WeakMap(w) | Class::WeakSet(w) => Ok(w),
_ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())),
}
}
/// Adds or replaces the entry of the object `k`; a key that is not an object is a `TypeError`.
fn weak_put(interp: &mut Interp, o: ObjId, k: &Value, v: Value, set: bool) -> JsResult<()> {
let Value::Object(key_obj) = k else {
let what = if set { "a WeakSet value" } else { "a WeakMap key" };
return Err(interp.type_error(&format!("{what} must be an object")));
};
if !weak(interp, o)?.entries.contains_key(&key_obj.0) {
interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(WEAK_ENTRY_BYTES))?;
interp.heap.bytes = interp.heap.bytes.saturating_add(WEAK_ENTRY_BYTES);
}
weak_mut(interp, o)?.entries.insert(key_obj.0, v);
Ok(())
}
fn weak_map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = this_weak(interp, &this, false, "get")?;
let Value::Object(k) = arg(args, 0) else { return Ok(Value::Undefined) };
Ok(weak(interp, o)?.entries.get(&k.0).cloned().unwrap_or(Value::Undefined))
}
fn weak_map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = this_weak(interp, &this, false, "set")?;
weak_put(interp, o, &arg(args, 0), arg(args, 1), false)?;
Ok(this)
}
fn weak_has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult<Value> {
let o = this_weak(interp, this, set, "has")?;
let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) };
Ok(Value::Bool(weak(interp, o)?.entries.contains_key(&k.0)))
}
fn weak_delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult<Value> {
let o = this_weak(interp, this, set, "delete")?;
let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) };
Ok(Value::Bool(weak_mut(interp, o)?.entries.remove(&k.0).is_some()))
}
fn weak_map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
weak_has(interp, &this, args, false)
}
fn weak_map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
weak_delete(interp, &this, args, false)
}
fn weak_set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = this_weak(interp, &this, true, "add")?;
weak_put(interp, o, &arg(args, 0), Value::Undefined, true)?;
Ok(this)
}
fn weak_set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
weak_has(interp, &this, args, true)
}
fn weak_set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
weak_delete(interp, &this, args, true)
}
+510
View File
@@ -0,0 +1,510 @@
use crate::heap::{Class, key};
use crate::value::Value;
use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind};
fn es2015() -> Options {
Options { es2015: true, ..Options::default() }
}
fn realm() -> Realm {
Realm::with_options(es2015(), Limits::default())
}
fn run(src: &str) -> JsValue {
match realm().run(src) {
Ok(v) => v,
Err(e) => panic!("{src}\n{e:?}"),
}
}
fn truth(src: &str) {
assert_eq!(run(src), JsValue::Bool(true), "{src}");
}
fn string(src: &str) -> String {
match run(src) {
JsValue::String(s) => s,
other => panic!("{src}: {other:?}"),
}
}
/// The run throws an error whose message starts with `name`.
fn throws(src: &str, name: &str) {
match realm().run(src) {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"),
other => panic!("{src}: {other:?}"),
}
}
fn limit(limits: &Limits, src: &str) -> LimitKind {
match Realm::with_options(es2015(), limits.clone()).run(src) {
Err(RunError { kind: RunErrorKind::Limit(k), .. }) => k,
other => panic!("{src}: {other:?}"),
}
}
/// The object a global variable holds.
fn global_object(realm: &mut Realm, name: &str) -> crate::heap::ObjId {
let interp = realm.interp();
let global = interp.global;
match interp.heap.object(global).and_then(|g| g.props.get(&key(name))) {
Some(crate::heap::Prop::Data { value: Value::Object(o), .. }) => *o,
_ => panic!("{name} is not an object"),
}
}
// ---- realms ----
#[test]
fn realms_without_the_option_keep_the_es5_globals() {
for options in [Options::default(), Options { e4x: true, ..Options::default() }] {
let mut realm = Realm::with_options(options, Limits::default());
let names = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array \
Uint32Array Float32Array Float64Array";
for name in names.split_whitespace() {
assert_eq!(realm.run(&format!("typeof {name}")).unwrap(), JsValue::String("undefined".into()), "{name}");
}
}
truth("typeof Map === 'function' && typeof Float64Array === 'function' && typeof TypedArray === 'undefined'");
}
// ---- Map and Set ----
#[test]
fn keys_compare_with_same_value_zero() {
truth("var m = new Map(); m.set(NaN, 1); m.get(NaN) === 1 && m.has(0 / 0) && m.size === 1");
truth("var m = new Map(); m.set(-0, 'a'); m.get(0) === 'a' && m.has(-0) && 1 / m.keys().next().value === Infinity");
truth("var s = new Set([0, -0, NaN, NaN]); s.size === 2 && 1 / s.values().next().value === Infinity");
truth("var m = new Map(); m.set('1', 'string').set(1, 'number'); m.size === 2 && m.get('1') === 'string' && m.get(1) === 'number'");
truth("var a = {}, b = {}; var m = new Map([[a, 1], [b, 2]]); m.get(a) === 1 && m.get(b) === 2 && m.get({}) === undefined");
truth("var m = new Map(); m.set('ab' + 'c', 1); m.get('abc') === 1");
}
#[test]
fn symbol_keys_compare_by_identity() {
truth(
"var a = Symbol('k'), b = Symbol('k'); var m = new Map([[a, 1], [b, 2]]); \
m.size === 2 && m.get(a) === 1 && m.get(b) === 2 && m.get(Symbol('k')) === undefined && m.keys().next().value === a",
);
truth("var r = Symbol.for('k'); var s = new Set([r, Symbol.for('k')]); s.size === 1 && s.has(r) && s.delete(r) && s.size === 0");
}
#[test]
fn entries_keep_the_order_they_were_added_in() {
assert_eq!(
string(
"var m = new Map([['a', 1], ['b', 2], ['c', 3]]); m.set('a', 9); m.delete('b'); m.set('b', 4); \
var out = []; m.forEach(function (v, k, map) { out.push(k + v + (map === m)); }); out.join()"
),
"a9true,c3true,b4true"
);
assert_eq!(string("var s = new Set(['x', 'y']); var out = []; s.forEach(function (v, k) { out.push(v + k); }); out.join()"), "xx,yy");
}
#[test]
fn for_each_skips_deleted_entries_and_visits_added_ones() {
assert_eq!(
string(
"var m = new Map([[1, 'a'], [2, 'b'], [3, 'c']]); var out = []; \
m.forEach(function (v, k) { out.push(v); if (k === 1) { m.delete(2); m.set(4, 'd'); } }); out.join()"
),
"a,c,d"
);
assert_eq!(
string("var s = new Set([1, 2]); var out = []; s.forEach(function (v) { out.push(v); if (v < 4) s.add(v + 2); }); out.join()"),
"1,2,3,4,5"
);
assert_eq!(string("var s = new Set([1, 2, 3]); var out = []; s.forEach(function (v) { out.push(v); s.clear(); }); out.join()"), "1");
}
#[test]
fn iterators_step_through_live_entries() {
truth(
"var m = new Map([['a', 1], ['b', 2], ['c', 3]]); var it = m.entries(); var first = it.next(); m.delete('b'); m.set('d', 4); \
var second = it.next(), third = it.next(), last = it.next(); \
first.value.join() === 'a,1' && !first.done && second.value.join() === 'c,3' && third.value.join() === 'd,4' && \
last.done && last.value === undefined && it.next().done",
);
truth("var s = new Set(['p']); var e = s.entries().next().value; e[0] === 'p' && e[1] === 'p' && s.keys === s.values");
truth("Object.prototype.toString.call(new Map().keys()) === '[object Map Iterator]'");
throws("var it = new Map().keys(); it.next.call(new Set().values());", "TypeError");
}
#[test]
fn constructors_read_arrays_strings_and_array_likes() {
truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'");
truth("new Set('ab\u{1F600}b').size === 3");
truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2");
truth("new Map(null).size === 0 && new Set(undefined).size === 0");
truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'");
throws("Map()", "TypeError");
throws("Set([])", "TypeError");
throws("new Map([1])", "TypeError");
throws("new Set(5)", "TypeError");
throws("new Map({})", "TypeError");
throws("new WeakSet({})", "TypeError");
truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3");
// `from` reads each element of an array-like source just before mapping it (section 22.2.2.1).
truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'");
truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'");
truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'");
throws("Map.prototype.get.call({}, 1)", "TypeError");
throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError");
// The constructor adds through the prototype's method, as section 23.1.1.1 says.
truth(
"var calls = 0; var set = Map.prototype.set; Map.prototype.set = function (k, v) { calls++; return set.call(this, k, v); }; \
new Map([[1, 1], [2, 2]]); Map.prototype.set = set; calls === 2",
);
truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'");
}
// ---- WeakMap and WeakSet ----
#[test]
fn weak_collections_take_object_keys_only() {
truth("var k = {}; var w = new WeakMap([[k, 1]]); w.get(k) === 1 && w.has(k) && w.delete(k) && !w.has(k)");
truth("var w = new WeakMap(); w.get(1) === undefined && !w.has('a') && !w.delete(null)");
truth("var s = new WeakSet(); var o = {}; s.add(o) === s && s.has(o) && !s.has(1) && !s.delete(1)");
throws("new WeakMap().set(1, 2)", "TypeError");
throws("new WeakSet().add('x')", "TypeError");
throws("new WeakMap([[1, 2]])", "TypeError");
truth("new WeakMap().size === undefined && typeof WeakMap.prototype.forEach === 'undefined'");
}
#[test]
fn a_weak_map_entry_does_not_keep_its_key_alive() {
let mut realm = realm();
realm
.run(
"var wm = new WeakMap(), ws = new WeakSet(), kept = {};
(function () { for (var i = 0; i < 50; i++) { var k = {}; wm.set(k, {back: k}); ws.add(k); } })();
wm.set(kept, {back: kept}); ws.add(kept);",
)
.unwrap();
let wm = global_object(&mut realm, "wm");
let ws = global_object(&mut realm, "ws");
let before = realm.interp().heap.live_cells();
realm.interp().collect_garbage();
let after = realm.interp().heap.live_cells();
let count = |realm: &mut Realm, o| match realm.interp().heap.object(o).map(|o| &o.class) {
Some(Class::WeakMap(w) | Class::WeakSet(w)) => w.entries.len(),
_ => panic!("not a weak collection"),
};
assert_eq!(count(&mut realm, wm), 1);
assert_eq!(count(&mut realm, ws), 1);
// Each dropped key and its value were freed.
assert!(before - after >= 100, "{before} -> {after}");
assert_eq!(realm.run("wm.get(kept).back === kept && ws.has(kept)").unwrap(), JsValue::Bool(true));
}
#[test]
fn a_weak_map_value_reachable_through_another_key_is_kept() {
let mut realm = realm();
realm.run("var wm = new WeakMap(), a = {}; (function () { var b = {}; wm.set(a, b); wm.set(b, {n: 7}); })();").unwrap();
realm.interp().collect_garbage();
assert_eq!(realm.run("wm.get(wm.get(a)).n").unwrap(), JsValue::Number(7.0));
}
#[test]
fn weak_maps_of_dropped_keys_stay_within_the_heap() {
let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() };
let mut realm = Realm::with_options(es2015(), limits);
let r = realm.run("var wm = new WeakMap(); for (var i = 0; i < 100000; i++) wm.set({}, i); 'done'");
assert_eq!(r.unwrap(), JsValue::String("done".into()));
assert!(realm.interp().heap.collections > 0);
}
#[test]
fn collections_of_millions_end_at_the_limits() {
let heap = Limits { heap_bytes: 4 << 20, ..Limits::default() };
assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap);
assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap);
let fuel = Limits { fuel: 100_000, ..Limits::default() };
assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel);
let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });";
assert_eq!(limit(&fuel, m), LimitKind::Fuel);
}
#[test]
fn a_collection_removes_holes_and_moves_live_iterators() {
let mut realm = realm();
realm
.run(
"var m = new Map(); for (var i = 0; i < 100; i++) m.set(i, i * 2);
var it = m.values(); it.next(); it.next();
for (var j = 0; j < 90; j++) m.delete(j);",
)
.unwrap();
let m = global_object(&mut realm, "m");
realm.interp().collect_garbage();
match realm.interp().heap.object(m).map(|o| &o.class) {
Some(Class::Map(c)) => assert_eq!((c.len(), c.slots()), (10, 10)),
_ => panic!("not a Map"),
}
let rest = realm.run("var out = []; for (var r = it.next(); !r.done; r = it.next()) out.push(r.value); out.join()").unwrap();
assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into()));
}
#[test]
fn a_collection_releases_the_storage_of_removed_entries() {
let mut realm = realm();
realm
.run(
"var m = new Map(), wm = new WeakMap(), kept = {};
for (var i = 0; i < 1000; i++) m.set(i, i);
m.clear(); m.set('a', 1);
(function () { for (var i = 0; i < 1000; i++) wm.set({}, i); })();
wm.set(kept, 1);",
)
.unwrap();
let m = global_object(&mut realm, "m");
let wm = global_object(&mut realm, "wm");
realm.interp().collect_garbage();
match realm.interp().heap.object(m).map(|o| &o.class) {
Some(Class::Map(c)) => {
let (entries, index) = c.capacity();
assert_eq!(c.slots(), 1);
assert!(entries < 64 && index < 64, "{entries} {index}");
}
_ => panic!("not a Map"),
}
match realm.interp().heap.object(wm).map(|o| &o.class) {
Some(Class::WeakMap(w)) => assert!(w.entries.len() == 1 && w.entries.capacity() < 64, "{}", w.entries.capacity()),
_ => panic!("not a WeakMap"),
}
assert_eq!(realm.run("m.get('a') + wm.get(kept)").unwrap(), JsValue::Number(2.0));
}
// ---- ArrayBuffer ----
#[test]
fn array_buffers_are_zeroed_and_sliced() {
truth("var b = new ArrayBuffer(8); b.byteLength === 8 && new Uint8Array(b)[7] === 0");
truth("var u = new Uint8Array([1, 2, 3, 4]); var s = u.buffer.slice(1, -1); s.byteLength === 2 && new Uint8Array(s).join() === '2,3'");
truth("ArrayBuffer.isView(new DataView(new ArrayBuffer(1))) && ArrayBuffer.isView(new Int8Array(1)) && !ArrayBuffer.isView(new ArrayBuffer(1))");
truth("new ArrayBuffer().byteLength === 0 && new ArrayBuffer(2.9).byteLength === 2");
throws("ArrayBuffer(1)", "TypeError");
throws("new ArrayBuffer(-1)", "RangeError");
}
#[test]
fn a_huge_array_buffer_is_refused_before_it_is_allocated() {
throws("new ArrayBuffer(1e15)", "RangeError");
throws("new ArrayBuffer(Math.pow(2, 53))", "RangeError");
throws("new Float64Array(Math.pow(2, 40))", "RangeError");
truth("var caught; try { new Uint8Array(1e12); } catch (e) { caught = e instanceof RangeError; } caught");
// Larger than the realm's heap limit: a catchable RangeError, not an allocation.
let mut small = Realm::with_options(es2015(), Limits { heap_bytes: 8 << 20, ..Limits::default() });
assert_eq!(small.run("try { new ArrayBuffer(16 << 20); 'made' } catch (e) { e.name }").unwrap(), JsValue::String("RangeError".into()));
// Within the limit but not within what is left of it: the heap limit.
assert_eq!(
limit(&Limits { heap_bytes: 8 << 20, ..Limits::default() }, "var keep = []; for (;;) keep.push(new ArrayBuffer(1 << 20));"),
LimitKind::Heap
);
}
// ---- DataView ----
#[test]
fn data_views_read_and_write_both_byte_orders() {
truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234); v.getUint8(0) === 0x12 && v.getUint8(1) === 0x34");
truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234, true); v.getUint8(0) === 0x34 && v.getUint16(0, true) === 0x1234");
truth("var v = new DataView(new ArrayBuffer(4)); v.setInt32(0, -2); v.getInt32(0) === -2 && v.getUint32(0) === 4294967294");
truth("var v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, Math.PI); v.getFloat64(0) === Math.PI && v.getUint8(0) === 0x40");
truth("var v = new DataView(new ArrayBuffer(4)); v.setFloat32(0, 1.5, true); v.getFloat32(0, true) === 1.5 && v.getUint8(3) === 0x3f");
truth("var v = new DataView(new ArrayBuffer(4)); v.setInt8(0, 200); v.getInt8(0) === -56 && v.getUint8(0) === 200");
truth("var b = new ArrayBuffer(8); var v = new DataView(b, 2, 4); v.byteOffset === 2 && v.byteLength === 4 && v.buffer === b");
throws("new DataView(new ArrayBuffer(4)).getUint32(1)", "RangeError");
throws("new DataView(new ArrayBuffer(4)).getInt8(-1)", "RangeError");
throws("new DataView(new ArrayBuffer(4), 5)", "RangeError");
throws("new DataView(new ArrayBuffer(4), 2, 3)", "RangeError");
throws("new DataView({})", "TypeError");
throws("DataView(new ArrayBuffer(1))", "TypeError");
}
// ---- typed arrays ----
#[test]
fn uint8_clamped_rounds_half_to_even() {
assert_eq!(string("new Uint8ClampedArray([300, -5, 1.5, 2.5, 0.5, NaN, 254.5, 254.6, Infinity]).join()"), "255,0,2,2,0,0,254,255,255");
assert_eq!(string("var u = new Uint8ClampedArray(1); u[0] = 3.5; u[0] + ',' + new Uint8Array([300])[0]"), "4,44");
}
#[test]
fn element_types_convert_their_values() {
assert_eq!(string("new Int8Array([127, 128, -129, 1.9]).join()"), "127,-128,127,1");
assert_eq!(string("new Uint16Array([-1, 65536]).join()"), "65535,0");
assert_eq!(string("new Int32Array([4294967295]).join()"), "-1");
assert_eq!(string("new Uint32Array([-1]).join()"), "4294967295");
assert_eq!(string("new Float32Array([0.1])[0].toFixed(8)"), "0.10000000");
assert_eq!(string("new Float64Array([0.1, NaN]).join()"), "0.1,NaN");
truth("Int16Array.BYTES_PER_ELEMENT === 2 && new Float64Array(1).BYTES_PER_ELEMENT === 8");
truth("Object.prototype.toString.call(new Uint8Array(1)) === '[object Uint8Array]'");
}
#[test]
fn views_share_their_buffer_little_endian() {
truth("var b = new ArrayBuffer(8); var u8 = new Uint8Array(b), u32 = new Uint32Array(b); u32[0] = 0x01020304; u8[0] === 4 && u8[3] === 1");
truth("var a = new Uint8Array([1, 2, 3, 4]); var s = a.subarray(1, 3); s[0] = 9; a[1] === 9 && s.length === 2 && s.byteOffset === 1");
truth("var b = new ArrayBuffer(8); var a = new Int16Array(b, 2, 2); a.length === 2 && a.byteOffset === 2 && a.byteLength === 4");
throws("new Int32Array(new ArrayBuffer(8), 2)", "RangeError");
throws("new Int32Array(new ArrayBuffer(6))", "RangeError");
throws("new Int16Array(new ArrayBuffer(8), 4, 4)", "RangeError");
}
#[test]
fn numeric_names_are_elements_or_nothing() {
truth("var a = new Int8Array(2); a[5] = 1; a[5] === undefined && !('5' in a) && Object.keys(a).join() === '0,1'");
truth(
"var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2",
);
truth("Int8Array.prototype[3] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[3]; r");
truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2");
// The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it.
truth(
"var n = 0; var a = new Int8Array(1); a[5] = {valueOf: function () { n++; return 1; }}; a['-0'] = {valueOf: function () { n++; }}; n === 2",
);
truth("var a = new Int8Array([200]); a[0] === -56 && delete a[1] && !delete a[0]");
throws("'use strict'; var a = new Int8Array(1); delete a[0];", "TypeError");
// An out-of-range write is ignored without an error in strict mode too, as later editions define [[Set]].
truth("'use strict'; var a = new Uint8Array(1); a[2] = 7; a['-1'] = 7; a[0.5] = 7; a.length === 1 && a[2] === undefined");
truth("var d = Object.getOwnPropertyDescriptor(new Uint8Array([7]), '0'); d.value === 7 && d.writable && d.enumerable && d.configurable");
truth("var a = new Uint8Array(1); Object.defineProperty(a, '0', {value: 5}); a[0] === 5");
throws("Object.defineProperty(new Uint8Array(1), '0', {value: 5, configurable: false})", "TypeError");
throws("Object.defineProperty(new Uint8Array(1), '3', {value: 5})", "TypeError");
throws("Object.freeze(new Uint8Array(1))", "TypeError");
truth("var keys = []; for (var k in new Uint8Array(3)) keys.push(k); keys.join() === '0,1,2'");
truth("JSON.stringify(new Uint8Array([1, 2])) === '{\"0\":1,\"1\":2}'");
}
#[test]
fn array_methods_visit_every_element_of_a_long_typed_array() {
truth("Array.prototype.join.call(new Uint8Array(5000)).length === 9999");
truth("var a = new Uint8Array(10000); a[9999] = 1; Array.prototype.indexOf.call(a, 1) === 9999");
// The element count, not a `length` property defined on the array, bounds the methods.
truth(
"var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 0}); var n = 0; \
a.forEach(function () { n++; }); n === 3 && a.join() === '1,2,3' && a.every(function (v) { return v > 0; }) && !a.every(function (v) { return v > 1; })",
);
// A generic array method called on the typed array reads its `length` property.
truth(
"var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 1}); \
Array.prototype.join.call(a) === '1' && a.join() === '1,2,3' && Array.prototype.join.call(new Uint8Array([4, 5])) === '4,5'",
);
}
#[test]
fn typed_array_methods() {
assert_eq!(string("new Float64Array([3, NaN, -0, 0, -1, 2]).sort().join()"), "-1,0,0,2,3,NaN");
truth("var a = new Float64Array([0, -0]).sort(); 1 / a[0] === -Infinity && 1 / a[1] === Infinity");
assert_eq!(string("new Int8Array([1, 2, 3]).sort(function (a, b) { return b - a; }).join()"), "3,2,1");
assert_eq!(string("new Int8Array([1, 2, 3, 4]).map(function (v) { return v * 100; }).join()"), "100,-56,44,-112");
assert_eq!(string("new Int8Array([1, 2, 3, 4]).filter(function (v) { return v % 2; }).join()"), "1,3");
assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(0, 3), 2); a.join()"), "1,2,1,2,3");
assert_eq!(string("var a = new Uint8Array(4); a.set([7, '8'], 1); a.join()"), "0,7,8,0");
throws("new Uint8Array(2).set([1, 2, 3])", "RangeError");
throws("new Uint8Array(2).set([1], -1)", "RangeError");
assert_eq!(string("new Uint8Array([1, 2, 3, 4, 5]).copyWithin(0, 3).join()"), "4,5,3,4,5");
assert_eq!(string("new Uint8Array(4).fill(7, 1, -1).join()"), "0,7,7,0");
assert_eq!(string("new Int8Array([5, 6, 7]).slice(-2).join()"), "6,7");
truth("var a = new Int8Array([5, 6, 7]); a.find(function (v) { return v > 5; }) === 6 && a.findIndex(function (v) { return v > 9; }) === -1");
truth("new Int8Array([1, 2, 1]).indexOf(1, 1) === 2 && new Int8Array([1, 2, 1]).lastIndexOf(2) === 1");
truth("new Int8Array([1, 2, 3]).reduce(function (s, v) { return s + v; }) === 6 && new Int8Array([1, 2]).reverse().join() === '2,1'");
truth(
"var it = new Int8Array([4, 5]).entries(); var e = it.next().value; e[0] === 0 && e[1] === 4 && it.next().value[1] === 5 && it.next().done",
);
truth("new Int8Array([9]).keys().next().value === 0 && new Int8Array([9]).values().next().value === 9");
truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'");
truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'");
truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'");
// A typed array calls each element's toLocaleString on the number (section 22.2.3.27); an array
// calls it on the element's object (section 15.4.4.3).
assert_eq!(
string(
"Number.prototype.toLocaleString = function () { 'use strict'; return typeof this; }; new Uint8Array([7, 8]).toLocaleString() + ';' + [7].toLocaleString()"
),
"number,number;object"
);
// A getter for the method gets the number as `this` too (Invoke, section 7.3.18).
assert_eq!(
string(
"Object.defineProperty(Number.prototype, 'toLocaleString', {get: function () { 'use strict'; var t = typeof this; \
return function () { return t; }; }}); new Uint8Array([7]).toLocaleString() + ';' + [7].toLocaleString()"
),
"number;object"
);
truth(
"Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype",
);
throws("Object.getPrototypeOf(Int8Array)()", "TypeError");
throws("Int8Array(1)", "TypeError");
throws("Object.getPrototypeOf(Int8Array.prototype).fill.call([1], 0)", "TypeError");
throws("Int8Array.from.call(Object, [1])", "TypeError");
throws("Int8Array.from.call({}, [1])", "TypeError");
// The source's length is read before the constructor is checked to be a typed array's.
throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError");
// A receiver that is not a constructor is refused before the source is read (section 22.2.2.1 step 2).
throws("Int8Array.from.call(ArrayBuffer.isView, {get length() { throw new RangeError('first'); }})", "TypeError");
// A constructor that is not a typed array's is refused (AllocateTypedArray, section 22.2.1.2.1),
// a function that returns a typed array and a bound typed array constructor included.
throws("Int8Array.from.call(function () { return new Int8Array(2); }, [1, 2])", "TypeError");
throws("Int8Array.of.call(Int8Array.bind(null), 1)", "TypeError");
truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'");
// A copy to the same element type keeps every bit, a signaling NaN's included.
truth(
"var f = new Float32Array(2); new DataView(f.buffer).setUint32(4, 0x7f800001, true); \
function bits(t) { return new DataView(t.buffer, t.byteOffset).getUint32(4, true); } \
var g = new Float32Array(3); g.set(f, 1); var h = new Float32Array(2); h.set(f); \
bits(f.slice()) === 0x7f800001 && bits(new Float32Array(f)) === 0x7f800001 && bits(h) === 0x7f800001 && \
new DataView(g.buffer).getUint32(8, true) === 0x7f800001",
);
assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5");
assert_eq!(
string("var b = new ArrayBuffer(4); var a = new Int8Array(b); a.set([1, 2]); new Uint16Array(b).set(a.subarray(0, 2)); a.join()"),
"1,0,2,0"
);
assert_eq!(string("var a = new Int8Array(3); a.set(new Uint8Array([200, 1]), 1); a.join()"), "0,-56,1");
}
#[test]
fn derived_buffers_and_typed_arrays_read_the_constructor_first() {
// SpeciesConstructor (section 7.3.20) reads `constructor` before the result is made, and
// before filter's callback runs.
for call in ["a.slice()", "a.subarray(0)", "a.map(function (v) { return v; })", "a.filter(function () { n++; })", "a.buffer.slice(0)"] {
let getter = format!(
"var n = 0; var a = new Int8Array([1, 2]); var g = {{get: function () {{ throw new RangeError('c'); }}}}; \
Object.defineProperty(a, 'constructor', g); Object.defineProperty(a.buffer, 'constructor', g); {call}"
);
throws(&getter, "RangeError");
throws(&format!("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; a.buffer.constructor = null; {call}"), "TypeError");
}
truth("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; try { a.filter(function () { n++; }); } catch (e) {} n === 0");
truth(
"var a = new Int8Array([1, 2]); a.constructor = undefined; a.buffer.constructor = undefined; a.slice().join() === '1,2' && a.subarray(1)[0] === 2 && a.buffer.slice(1).byteLength === 1",
);
truth("var a = new Int8Array([1, 2]); a.constructor = Array; a.map(function (v) { return v; }) instanceof Int8Array");
}
#[test]
fn typed_array_work_takes_fuel() {
let fuel = Limits { fuel: 50_000, ..Limits::default() };
assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).fill(1)"), LimitKind::Fuel);
assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).copyWithin(0, 1)"), LimitKind::Fuel);
assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).slice()"), LimitKind::Fuel);
assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel);
assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel);
assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel);
// A sort of 2^16 equal elements makes 2^19 comparisons, and reading and writing back its
// elements takes 2^17 units more.
let sort = "new Uint8Array(1 << 16).sort(); 'sorted'";
assert_eq!(limit(&Limits { fuel: 600_000, ..Limits::default() }, sort), LimitKind::Fuel);
let mut enough = Realm::with_options(es2015(), Limits { fuel: 700_000, ..Limits::default() });
assert_eq!(enough.run(sort).unwrap(), JsValue::String("sorted".into()));
}
#[test]
fn a_copy_between_buffers_holds_no_snapshot() {
let mut realm = Realm::with_options(es2015(), Limits { heap_bytes: 6 << 20, ..Limits::default() });
let r = realm.run("var a = new Uint8Array(1 << 20), b = new Int8Array(1 << 20); a[5] = 200; b.set(a); b[5]");
assert_eq!(r.unwrap(), JsValue::Number(-56.0));
}
+342 -1
View File
@@ -280,6 +280,241 @@ pub(crate) enum Class {
Promise(Box<crate::builtins::promise::PromiseData>),
/// The state that the functions a promise operation makes share; scripts never see it.
PromiseRecord(Box<crate::builtins::promise::Record>),
/// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added.
Map(Box<Coll>),
/// A `Set` (section 23.2): its values in the order they were added, each with `undefined`.
Set(Box<Coll>),
/// A `WeakMap` (section 23.3): values keyed by object. An entry does not keep its key
/// reachable, and its value is reachable only while its key is.
WeakMap(Box<WeakColl>),
/// A `WeakSet` (section 23.4): objects that it does not keep reachable.
WeakSet(Box<WeakColl>),
/// An iterator over a Map, a Set or a typed array (sections 23.1.5, 23.2.5 and 22.1.5).
Iter(Box<IterState>),
/// An `ArrayBuffer` (section 24.1) and its bytes, which never change length.
ArrayBuffer(Box<[u8]>),
/// A `DataView` (section 24.2): a range of a buffer's bytes.
DataView(Box<View>),
/// A typed array (section 22.2): elements of one type in a range of a buffer's bytes.
TypedArray(Box<View>),
}
/// A Map or Set key compared with SameValueZero (section 7.2.10): `NaN` equals `NaN`, `-0`
/// equals `+0`, strings compare by their code units, and Symbols and objects by identity.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum CollKey {
Undefined,
Null,
Bool(bool),
/// The bits of the number, with every `NaN` as one value and `-0` as `+0`.
Number(u64),
String(Rc<[u16]>),
Symbol(crate::symbol::Sym),
Object(u32),
}
impl CollKey {
/// The key of a number.
pub(crate) fn number(n: f64) -> Self {
CollKey::Number(if n.is_nan() {
f64::NAN.to_bits()
} else if n == 0.0 {
0
} else {
n.to_bits()
})
}
}
/// The entries of a Map or a Set in the order they were added. Deleting an entry leaves a hole,
/// so the position an iterator or a `forEach` loop has reached stays valid; a collection removes
/// the holes of a collection with more holes than entries and moves its live iterators with them.
#[derive(Clone, Default)]
pub(crate) struct Coll {
entries: Vec<Option<(Value, Value)>>,
index: HashMap<CollKey, usize>,
}
impl Coll {
/// The number of entries.
pub(crate) fn len(&self) -> usize {
self.index.len()
}
/// The number of positions, holes included.
pub(crate) fn slots(&self) -> usize {
self.entries.len()
}
pub(crate) fn get(&self, k: &CollKey) -> Option<&Value> {
let i = *self.index.get(k)?;
self.entries.get(i)?.as_ref().map(|(_, v)| v)
}
pub(crate) fn has(&self, k: &CollKey) -> bool {
self.index.contains_key(k)
}
/// Sets the value under `k`, keeping its position when it is there already. Returns whether
/// a new entry was added.
pub(crate) fn set(&mut self, k: CollKey, key: Value, value: Value) -> bool {
if let Some(&i) = self.index.get(&k)
&& let Some(Some((_, v))) = self.entries.get_mut(i)
{
*v = value;
return false;
}
self.index.insert(k, self.entries.len());
self.entries.push(Some((key, value)));
true
}
/// Deletes the entry under `k`; returns whether there was one.
pub(crate) fn delete(&mut self, k: &CollKey) -> bool {
let Some(i) = self.index.remove(k) else { return false };
if let Some(slot) = self.entries.get_mut(i) {
*slot = None;
}
true
}
/// Deletes every entry, leaving the positions in place.
pub(crate) fn clear(&mut self) {
self.index.clear();
self.entries.iter_mut().for_each(|e| *e = None);
}
/// The entry at position `i`, or `None` for a hole or a position past the end.
pub(crate) fn entry(&self, i: usize) -> Option<&(Value, Value)> {
self.entries.get(i)?.as_ref()
}
fn values(&self) -> impl Iterator<Item = &Value> {
self.entries.iter().flatten().flat_map(|(k, v)| [k, v])
}
fn should_compact(&self) -> bool {
let holes = self.entries.len() - self.index.len();
holes > 16 && holes > self.index.len()
}
/// Removes the holes. Returns, for each old position and the position past the end, the new
/// position of the first entry at or after it.
fn compact(&mut self) -> Vec<usize> {
let mut moved = Vec::with_capacity(self.entries.len() + 1);
let mut live = 0usize;
for e in &self.entries {
moved.push(live);
live += usize::from(e.is_some());
}
moved.push(live);
self.entries.retain(Option::is_some);
// The storage the holes held is released along with their charge.
self.entries.shrink_to_fit();
self.index.shrink_to_fit();
for slot in self.index.values_mut() {
*slot = moved.get(*slot).copied().unwrap_or(*slot);
}
moved
}
/// The positions the entries and the index have room for, for tests.
#[cfg(test)]
pub(crate) fn capacity(&self) -> (usize, usize) {
(self.entries.capacity(), self.index.capacity())
}
}
/// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are
/// `undefined`.
#[derive(Clone, Default)]
pub(crate) struct WeakColl {
pub(crate) entries: HashMap<u32, Value>,
}
/// What an iterator object goes through.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum IterSource {
Map,
Set,
/// A typed array, by index.
Array,
}
/// What each step of an iterator gives: the key, the value or a `[key, value]` array.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum IterKind {
Keys,
Values,
Entries,
}
/// An iterator's state. `target` is `None` once the iterator has finished.
#[derive(Clone, Debug)]
pub(crate) struct IterState {
pub(crate) source: IterSource,
pub(crate) kind: IterKind,
pub(crate) target: Option<ObjId>,
pub(crate) pos: usize,
}
/// The element type of a typed array (section 22.2, table 50).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Elem {
Int8,
Uint8,
Uint8Clamped,
Int16,
Uint16,
Int32,
Uint32,
Float32,
Float64,
}
impl Elem {
pub(crate) const ALL: [Elem; 9] =
[Elem::Int8, Elem::Uint8, Elem::Uint8Clamped, Elem::Int16, Elem::Uint16, Elem::Int32, Elem::Uint32, Elem::Float32, Elem::Float64];
/// The bytes of one element.
pub(crate) fn size(self) -> usize {
match self {
Elem::Int8 | Elem::Uint8 | Elem::Uint8Clamped => 1,
Elem::Int16 | Elem::Uint16 => 2,
Elem::Int32 | Elem::Uint32 | Elem::Float32 => 4,
Elem::Float64 => 8,
}
}
/// The name of the constructor.
pub(crate) fn name(self) -> &'static str {
match self {
Elem::Int8 => "Int8Array",
Elem::Uint8 => "Uint8Array",
Elem::Uint8Clamped => "Uint8ClampedArray",
Elem::Int16 => "Int16Array",
Elem::Uint16 => "Uint16Array",
Elem::Int32 => "Int32Array",
Elem::Uint32 => "Uint32Array",
Elem::Float32 => "Float32Array",
Elem::Float64 => "Float64Array",
}
}
/// The position of the type in [`Elem::ALL`].
pub(crate) fn index(self) -> usize {
Elem::ALL.iter().position(|e| *e == self).unwrap_or(0)
}
}
/// A typed array or a `DataView`: `length` elements of `elem` (bytes, for a `DataView`) starting
/// `offset` bytes into `buffer`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct View {
pub(crate) buffer: ObjId,
pub(crate) offset: usize,
pub(crate) length: usize,
pub(crate) elem: Elem,
}
/// What an XML value is.
@@ -364,6 +599,18 @@ impl Class {
Class::RegExp(_) => "RegExp",
Class::Date(_) => "Date",
Class::UnitValue(_) => "UnitValue",
Class::Map(_) => "Map",
Class::Set(_) => "Set",
Class::WeakMap(_) => "WeakMap",
Class::WeakSet(_) => "WeakSet",
Class::Iter(state) => match state.source {
IterSource::Map => "Map Iterator",
IterSource::Set => "Set Iterator",
IterSource::Array => "Array Iterator",
},
Class::ArrayBuffer(_) => "ArrayBuffer",
Class::DataView(_) => "DataView",
Class::TypedArray(view) => view.elem.name(),
}
}
}
@@ -465,6 +712,12 @@ pub(crate) const SYMBOL_BYTES: usize = 48;
pub(crate) const UNIT_VALUE_BYTES: usize = 32;
/// The estimated bytes of a piece of code without its instructions, tables and strings.
const CODE_BYTES: usize = 384;
/// The estimated bytes of a Map or Set position, with its entry in the hash index.
pub(crate) const COLL_ENTRY_BYTES: usize = 96;
/// The estimated bytes of a WeakMap or WeakSet entry.
pub(crate) const WEAK_ENTRY_BYTES: usize = 64;
/// The estimated bytes of the state of an iterator, a typed array or a `DataView`.
pub(crate) const VIEW_BYTES: usize = 48;
pub(crate) fn string_bytes(len: usize) -> usize {
32 + 2 * len
@@ -560,11 +813,18 @@ impl Heap {
/// Marks everything reachable from `roots` and frees the rest. Afterwards [`Heap::bytes`] is
/// the estimated size of what is left, strings reachable from it included.
///
/// A WeakMap's entry marks its value only once its key is marked by another path, and the
/// entries of WeakMaps and WeakSets whose keys stay unmarked are removed before the sweep, so
/// a value that refers back to its own key does not keep it alive. Values waiting for their
/// key are kept by key, so the marking stays linear in the number of entries.
pub(crate) fn collect(&mut self, roots: &Roots<'_>) {
let mut marks = vec![false; self.cells.len()];
let mut work: Vec<u32> = Vec::new();
let mut strings = StringSizes::default();
let mut live = 0usize;
let mut pending: HashMap<u32, Vec<Value>> = HashMap::new();
let mut weak: Vec<u32> = Vec::new();
for v in &roots.values {
mark_value(v, &mut work, &mut strings);
}
@@ -579,21 +839,85 @@ impl Heap {
continue;
}
*mark = true;
if let Some(values) = pending.remove(&i) {
for v in &values {
mark_value(v, &mut work, &mut strings);
}
}
match self.cells.get(i as usize) {
Some(Cell::Object(o)) => live += trace_object(o, &mut work, &mut strings),
Some(Cell::Object(o)) => {
live += trace_object(o, &mut work, &mut strings);
match &o.class {
Class::WeakMap(w) => {
weak.push(i);
for (k, v) in &w.entries {
if marks.get(*k as usize).copied().unwrap_or(false) {
mark_value(v, &mut work, &mut strings);
} else if matches!(v, Value::Object(_) | Value::String(_)) {
pending.entry(*k).or_default().push(v.clone());
}
}
}
Class::WeakSet(_) => weak.push(i),
_ => {}
}
}
Some(Cell::Env(e)) => live += trace_env(e, &mut work, &mut strings),
_ => {}
}
}
for i in weak {
if let Some(Cell::Object(o)) = self.cells.get_mut(i as usize)
&& let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class
{
w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false));
// Only the entries left are charged, and a table with far more room than entries
// releases the extra room.
if w.entries.capacity() > 2 * w.entries.len() + 16 {
w.entries.shrink_to_fit();
}
live += WEAK_ENTRY_BYTES * w.entries.len();
}
}
for (i, (cell, marked)) in self.cells.iter_mut().zip(&marks).enumerate() {
if !marked && !matches!(cell, Cell::Free) {
*cell = Cell::Free;
self.free.push(u32::try_from(i).unwrap_or(u32::MAX));
}
}
live = live.saturating_sub(self.compact_collections());
self.bytes = live + strings.bytes;
self.collections += 1;
}
/// Removes the holes of the Maps and Sets that have more holes than entries, and moves the
/// positions of their iterators with them. Returns the bytes the holes held.
fn compact_collections(&mut self) -> usize {
let mut moved: HashMap<u32, Vec<usize>> = HashMap::new();
let mut freed = 0usize;
for (i, cell) in self.cells.iter_mut().enumerate() {
if let Cell::Object(o) = cell
&& let Class::Map(c) | Class::Set(c) = &mut o.class
&& c.should_compact()
{
freed += COLL_ENTRY_BYTES * (c.slots() - c.len());
moved.insert(u32::try_from(i).unwrap_or(u32::MAX), c.compact());
}
}
if moved.is_empty() {
return 0;
}
for cell in &mut self.cells {
if let Cell::Object(o) = cell
&& let Class::Iter(state) = &mut o.class
&& state.source != IterSource::Array
&& let Some(map) = state.target.and_then(|t| moved.get(&t.0))
{
state.pos = map.get(state.pos).or(map.last()).copied().unwrap_or(0);
}
}
freed
}
}
/// What the collector starts from.
@@ -825,6 +1149,23 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
work.extend(state.input.iter().chain(&state.kept).map(|o| o.0));
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
}
Class::Map(c) | Class::Set(c) => {
for v in c.values() {
mark_value(v, work, strings);
}
extra = COLL_ENTRY_BYTES * c.slots();
}
// Their entries are marked and counted by the collector's weak pass.
Class::WeakMap(_) | Class::WeakSet(_) => {}
Class::Iter(state) => {
work.extend(state.target.iter().map(|o| o.0));
extra = VIEW_BYTES;
}
Class::ArrayBuffer(bytes) => extra = bytes.len(),
Class::DataView(view) | Class::TypedArray(view) => {
work.push(view.buffer.0);
extra = VIEW_BYTES;
}
Class::Xmp(meta) => extra = meta.heap_bytes(),
Class::XmpFile(fields) => {
for (name, value) in fields.iter() {
+62 -4
View File
@@ -135,6 +135,8 @@ pub(crate) struct Intrinsics {
pub(crate) xml_list_proto: ObjId,
pub(crate) namespace_proto: ObjId,
pub(crate) qname_proto: ObjId,
/// The ECMAScript 2015 collections and binary data ([`crate::Options::es2015`]).
pub(crate) es2015: crate::builtins::collections::Es2015,
}
impl Intrinsics {
@@ -157,6 +159,7 @@ impl Intrinsics {
xml_list_proto: o,
namespace_proto: o,
qname_proto: o,
es2015: crate::builtins::collections::Es2015::placeholder(),
}
}
@@ -192,6 +195,7 @@ impl Intrinsics {
self.qname_proto,
];
v.extend(self.error_protos);
v.extend(self.es2015.all());
v
}
}
@@ -306,6 +310,9 @@ pub(crate) struct Interp {
pub(crate) held_bytes: usize,
/// Why installing the built-ins failed; a realm with this set runs no script.
pub(crate) install_error: Option<String>,
/// The typed array whose element count the next array method reads as its length, set while a
/// `%TypedArray%.prototype` method runs the array method it shares and cleared once it is read.
pub(crate) typed_length: Option<ObjId>,
/// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]).
pub(crate) files: Option<crate::file_classes::Classes>,
/// `ExternalObject` and the XMP classes it loads, once a host has added them
@@ -631,6 +638,7 @@ impl Interp {
join_stack: Vec::new(),
held_bytes: 0,
install_error: None,
typed_length: None,
files: None,
xmp: None,
host_classes: Vec::new(),
@@ -1629,6 +1637,12 @@ impl Interp {
return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags }));
}
}
// A numeric name of a typed array is an element or nothing (section 9.4.5.1).
Class::TypedArray(view) => {
if let Some(n) = crate::builtins::binary::canonical_index(k) {
return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN }));
}
}
_ => {}
}
Ok(o.props.get(k).cloned())
@@ -1642,6 +1656,10 @@ impl Interp {
if let Some(p) = self.get_own_property(o, k)? {
return Ok(Some(p));
}
// A typed array's prototypes are not searched for a numeric name (section 9.4.5.4).
if crate::builtins::binary::typed_key(self, o, k).is_some() {
return Ok(None);
}
cur = self.object(o)?.proto;
steps += 1;
if steps > 1_000_000 {
@@ -1762,6 +1780,9 @@ impl Interp {
}
self.define_ordinary(id, k, desc, throw)
}
Class::TypedArray(_) if crate::builtins::binary::canonical_index(&k).is_some() => {
crate::builtins::binary::define_element(self, id, &k, desc, throw)
}
Class::Arguments(map) => {
let mapped = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref).cloned();
if !self.define_ordinary(id, k.clone(), desc, false)? {
@@ -1914,7 +1935,12 @@ impl Interp {
/// list is checked first.
pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult<Vec<Key>> {
let o = self.object(id)?;
let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 };
// A typed array's indices come first, as a String object's do (section 9.4.5.6).
let string_len = match &o.class {
Class::String(s) => s.len(),
Class::TypedArray(view) => view.length,
_ => 0,
};
let is_string = matches!(o.class, Class::String(_));
let is_array = matches!(o.class, Class::Array { .. });
let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array));
@@ -1956,6 +1982,9 @@ impl Interp {
/// [[Put]] (section 8.12.5).
pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> {
if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) {
return crate::builtins::binary::set_element(self, id, n, &v);
}
match self.get_own_property(id, &k)? {
Some(Prop::Data { flags, .. }) => {
if flags & WRITABLE == 0 {
@@ -2040,6 +2069,18 @@ impl Interp {
/// [[Delete]] (section 8.12.7).
pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult<bool> {
// A typed array's element cannot be deleted, and a numeric name it has no element for
// is not a property it can hold (section 9.4.5.6 of later editions).
if crate::builtins::binary::typed_key(self, id, k).is_some() {
if self.get_own_property(id, k)?.is_none() {
return Ok(true);
}
if throw {
let key = String::from_utf16_lossy(k);
return Err(self.type_error(&format!("cannot delete property '{key}' of a typed array")));
}
return Ok(false);
}
match self.get_own_property(id, k)? {
None => Ok(true),
Some(p) if p.configurable() => {
@@ -2769,8 +2810,12 @@ impl Interp {
let mut cur = Some(id);
while let Some(o) = cur {
let obj = self.object(o)?;
let string_len = if let Class::String(s) = &obj.class { Some(s.len()) } else { None };
let is_array = matches!(obj.class, Class::Array { .. });
let string_len = match &obj.class {
Class::String(s) => Some(s.len()),
Class::TypedArray(view) => Some(view.length),
_ => None,
};
let is_array = matches!(obj.class, Class::Array { .. } | Class::String(_));
if let Some(len) = string_len {
self.reserve_heap(index_keys_bytes(len))?;
for i in 0..len {
@@ -2780,7 +2825,6 @@ impl Interp {
out.push(k);
}
}
seen.insert(key("length"));
}
if is_array {
seen.insert(key("length"));
@@ -2843,6 +2887,20 @@ impl Interp {
v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Function(_)))
}
/// Whether `new` can construct with `v` (section 7.2.4): a function written in JavaScript, a
/// built-in constructor, or a bound function whose target is one, as `op_new` accepts.
pub(crate) fn is_constructor(&self, v: &Value) -> bool {
let mut f = v.as_object();
while let Some(o) = f {
match self.heap.object(o).map(|o| &o.class) {
Some(Class::Function(Func::Closure { .. } | Func::Native { constructor: true, .. })) => return true,
Some(Class::Function(Func::Bound { target, .. })) => f = Some(*target),
_ => return false,
}
}
false
}
fn func_of(&self, v: &Value) -> Option<Func> {
match &self.heap.object(v.as_object()?)?.class {
Class::Function(f) => Some(f.clone()),
+17 -2
View File
@@ -95,6 +95,18 @@
//! limits; a promise still rejected with no handler at the end is reported by
//! [`Realm::unhandled_rejections`]. [`Realm::add_es2015`] gives a realm made without the option
//! `Promise` for its next runs.
//!
//! With [`Options::es2015`], the realm also provides these ECMAScript 2015 built-ins
//! (<https://262.ecma-international.org/6.0/>): `Map` and `Set` (sections 23.1 and 23.2), whose
//! keys compare with SameValueZero and keep the order they were added in, with `forEach` visiting
//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the
//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine
//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with
//! a `next` method. Until the language has iterators, the collection constructors and
//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by
//! index. A typed array constructor reads an array or an object with a `length` the same way, and
//! converts a first argument that is not an object to a length. A buffer longer than the heap
//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated.
#![forbid(unsafe_code)]
pub mod ast;
@@ -168,8 +180,9 @@ pub struct Options {
/// `f?.()`) and `??`. Off, they are syntax errors and the language is ES5.1's. Code a
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
/// A realm made with it on also has the later editions' built-ins this engine has: `Symbol`
/// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, and
/// `Promise` with its job queue. A realm made with it off has the ES5.1 built-ins only, as the
/// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects,
/// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`
/// and the typed arrays. A realm made with it off has the ES5.1 built-ins only, as the
/// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option
/// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does
/// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it.
@@ -278,6 +291,8 @@ impl LineTable {
#[cfg(test)]
mod builtins_tests;
#[cfg(test)]
mod collections_tests;
#[cfg(test)]
mod es2015_object_tests;
#[cfg(test)]
mod es2015_tests;
+108
View File
@@ -33,6 +33,12 @@
//! chains and `??`) without and with that option, and
//! prints both counts; its failures with the option go to `es2015-failures.txt`.
//!
//! A sixth test runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names (`Map`, `Set`,
//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in
//! realms with [`Options::es2015`], each test whose feature tags are all in
//! [`ES2015_COLLECTION_FEATURES`]; its failures go to `es2015-builtins-failures.txt`. It fails when
//! the interpreter panics.
//!
//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every
//! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset
//! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the
@@ -629,6 +635,108 @@ fn run_text_builtins(dir: &Path) {
assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display());
}
/// The directories under `test/built-ins/` that hold the tests of the ECMAScript 2015 collections
/// and binary data, which run in a realm with [`Options::es2015`].
const ES2015_COLLECTION_BUILT_INS: &[&str] = &["Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "TypedArray", "TypedArrayConstructors"];
/// The names in [`MISSING_BUILTINS`] that a realm with [`Options::es2015`] provides.
const ES2015_BUILTINS: &str = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array";
/// The feature tags a test under [`ES2015_COLLECTION_BUILT_INS`] may have and still run: the built-ins
/// themselves and the stable typed array sort. A tag starting `DataView.prototype.` names one of
/// the `DataView` methods. Tests with any other tag (symbols, `Reflect`, classes, resizable or
/// detached buffers, `BigInt` and later additions) are counted as skipped.
const ES2015_COLLECTION_FEATURES: &[&str] = &[
"Map",
"Set",
"WeakMap",
"WeakSet",
"ArrayBuffer",
"DataView",
"TypedArray",
"Int8Array",
"Uint8Array",
"Float64Array",
"stable-typedarray-sort",
];
#[test]
fn es2015_collections_and_binary_data_run() {
let Some(dir) = suite_dir() else {
println!("test262 ECMAScript 2015 built-ins: SKIPPED (no suite; run cargo xtask test262)");
return;
};
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015_built_ins(&dir)).unwrap();
handle.join().unwrap();
}
/// Runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names in realms with
/// [`Options::es2015`], prints each folder's counts and writes the failures to
/// `es2015-builtins-failures.txt` beside the suite.
fn run_es2015_built_ins(dir: &Path) {
let missing = missing_builtins(&[TEXT_BUILTINS, ES2015_BUILTINS]);
let mut report = String::new();
let mut panicked = 0;
for name in ES2015_COLLECTION_BUILT_INS {
let root = or_fail(inside(dir, &format!("test/built-ins/{name}")));
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
let counts = run_es2015_tests(dir, &root, &missing);
println!("test262 built-ins/{name} in an ECMAScript 2015 realm: {}.", counts.summary());
report.push_str(&format!("# built-ins/{name}\n{}\n", counts.failures));
panicked += counts.panicked;
}
let path = dir.join("es2015-builtins-failures.txt");
if let Err(e) = std::fs::write(&path, &report) {
println!("could not write {}: {e}", path.display());
}
println!("test262 ECMAScript 2015 built-ins failures: {}", path.display());
assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display());
}
/// Runs the tests under `root` whose feature tags are all in [`ES2015_COLLECTION_FEATURES`], as
/// [`run_tests`] runs the ES5 tests, each in a new realm with [`Options::es2015`].
fn run_es2015_tests(dir: &Path, root: &Path, missing: &HashSet<&str>) -> RunCounts {
// A harness file is named by the test's `includes:`, so it is read only inside `harness/`.
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
let mut counts = RunCounts::default();
for path in or_fail(test_files(root)) {
let source = or_fail(read_source(&path));
let meta = meta(&source);
if matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) || meta.flags.iter().any(|f| f == "module") {
continue;
}
let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
let known = meta.features.iter().all(|f| ES2015_COLLECTION_FEATURES.contains(&f.as_str()) || f.starts_with("DataView.prototype."));
if !known || meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) {
counts.skipped += 1;
continue;
}
counts.tests += 1;
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
for &strict in modes(&meta) {
let mode = if strict { "strict" } else { "sloppy" };
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
match std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), &Options { es2015: true, ..Options::default() })) {
Ok(Ok(())) => counts.passed += 1,
Ok(Err(why)) => {
counts.failed += 1;
counts.failures.push_str(&format!("{rel} ({mode}): {why}\n"));
}
Err(_) => {
counts.failed += 1;
counts.panicked += 1;
counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n"));
}
}
}
}
counts
}
/// Runs the tests under `root` that have no feature tag and are not module, asynchronous or
/// negative parse tests, each in a new realm after the harness. Returns the counts for the tests
/// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out).
+18 -2
View File
@@ -92,8 +92,9 @@ pub(crate) const APP_METHODS: &[&str] = &["executeMenuCommand", "doScript", "loa
/// Text an action set written out at run time holds.
pub(crate) const ACTION_TEXT: &str = "/actionCount";
/// Constructors of the language (ECMA-262 3rd edition, section 15) and of E4X (ECMA-357 2nd edition,
/// section 13), and the platform's own: `new` of these is no document-model type.
/// Constructors of the language (ECMA-262 3rd edition, section 15, and the collections and binary
/// data of the 6th edition, sections 22.2 to 24.2) and of E4X (ECMA-357 2nd edition, section 13), and
/// the platform's own: `new` of these is no document-model type.
pub(crate) const CONSTRUCTORS: &[&str] = &[
"Object",
"Function",
@@ -110,6 +111,21 @@ pub(crate) const CONSTRUCTORS: &[&str] = &[
"SyntaxError",
"TypeError",
"URIError",
"Map",
"Set",
"WeakMap",
"WeakSet",
"ArrayBuffer",
"DataView",
"Int8Array",
"Uint8Array",
"Uint8ClampedArray",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array",
"Namespace",
"QName",
"XML",
+11
View File
@@ -1615,6 +1615,17 @@ fn type_names_compared_or_created_are_listed() {
assert_eq!(r.needs, [Need::Dom]);
}
#[test]
fn collections_and_typed_arrays_are_not_type_names() {
let r = report(concat!(
"var m = new Map(), s = new Set(), wm = new WeakMap(), ws = new WeakSet();\n",
"var b = new ArrayBuffer(8), v = new DataView(b), u = new Uint8Array(b), c = new Uint8ClampedArray(2);\n",
"var i = [new Int8Array(1), new Int16Array(1), new Uint16Array(1), new Int32Array(1), new Uint32Array(1)];\n",
"var f = [new Float32Array(1), new Float64Array(1)];\n",
));
assert!(r.types.is_empty(), "{:?}", r.types.iter().map(|t| t.name.as_str()).collect::<Vec<_>>());
}
#[test]
fn menu_commands_are_counted_with_their_lines() {
let r = report(concat!(
+4 -2
View File
@@ -2750,8 +2750,10 @@ https://ecma-international.org/publications-and-standards/standards/ecma-357/):
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file also has
`Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a named engine
(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps
its globals. The script reaches the app through the global object `vc`, and writes to the Script Console and runs
other files through `$`:
its globals. An ES5.1 script does not have `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` or the
typed arrays; the JavaScript engine's ECMAScript 2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as
`docs/target-app-parity.md` describes. The script reaches the app through the global object `vc`, and writes to the
Script Console and runs other files through `$`:
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
catch. The documents and the session state the command changed, preferences included, go back, and any file it
+1
View File
@@ -1158,6 +1158,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. Until the language has iterators, the collection constructors and `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by index, and a typed array constructor reads an array or an object with a `length` the same way and converts a first argument that is not an object to a length; these rules are VectorCraft's own. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`.
- Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`).
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.