mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Merge pull request #10328 from dotCooCoo/fix/script-array-host-collections
Scripts: array methods visit every element of a host collection
This commit is contained in:
5 files changed
+77
-15
No files matched your search
@@ -314,8 +314,21 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<Value> {
|
||||
interp.get_from(o, &key_of(k), &Value::Object(o))
|
||||
}
|
||||
|
||||
fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<bool> {
|
||||
interp.has_property_indexed(o, &key_of(k))
|
||||
/// The element at `k` when the object or its prototypes have one: [[HasProperty]], then [[Get]].
|
||||
/// An object of a host class with an indexer answers an array index with one call of the indexer,
|
||||
/// made as `k in object` makes it, and has the element when the answer is not `undefined`.
|
||||
fn element_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<Option<Value>> {
|
||||
let key = key_of(k);
|
||||
if crate::value::array_index(&key).is_some()
|
||||
&& let Some(f) = interp.host_indexer(o)?
|
||||
{
|
||||
let v = interp.host_index(&f, o, crate::Data::Number(k), true)?;
|
||||
return Ok((!matches!(v, Value::Undefined)).then_some(v));
|
||||
}
|
||||
if !interp.has_property_indexed(o, &key)? {
|
||||
return Ok(None);
|
||||
}
|
||||
interp.get_from(o, &key, &Value::Object(o)).map(Some)
|
||||
}
|
||||
|
||||
/// The estimated bytes a new element adds.
|
||||
|
||||
@@ -5,11 +5,12 @@
|
||||
//! the range is much longer than the object has properties (a sparse array such as
|
||||
//! `new Array(4294967295)`), so a long empty range costs nothing and no index is allocated for
|
||||
//! it. The list of indices is made again whenever a script adds an index property to any object
|
||||
//! while the method runs. Every index visited takes a unit of fuel.
|
||||
//! while the method runs. An object of a host class with an indexer has every index of the range
|
||||
//! visited, since its elements are not properties. Every index visited takes a unit of fuel.
|
||||
|
||||
use super::{
|
||||
Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, get_at, has_at, length_of, method, native, new_array, object_to_string, put_at,
|
||||
require_callable, to_integer,
|
||||
Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, element_at, get_at, length_of, method, native, new_array, object_to_string,
|
||||
put_at, require_callable, to_integer,
|
||||
};
|
||||
use crate::heap::{Class, NativeKind, ObjId};
|
||||
use crate::interp::{Abrupt, Interp, JsResult, strict_eq};
|
||||
@@ -121,7 +122,9 @@ fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> {
|
||||
impl Indices {
|
||||
fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec<Map>) -> JsResult<Self> {
|
||||
let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None };
|
||||
if hi.saturating_sub(lo) > DENSE_SPAN {
|
||||
// An object of a host class with an indexer holds its elements in the host, not in
|
||||
// properties, so every index of the range is visited.
|
||||
if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() {
|
||||
let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add);
|
||||
if hi - lo > (present as u64).saturating_mul(8) {
|
||||
it.sparse = Some(it.gather(interp)?);
|
||||
@@ -206,11 +209,7 @@ impl Indices {
|
||||
|
||||
/// The element at `k` when the object or its prototypes have one.
|
||||
fn element(interp: &mut Interp, o: ObjId, k: u64) -> JsResult<Option<Value>> {
|
||||
let k = k as f64;
|
||||
if !has_at(interp, o, k)? {
|
||||
return Ok(None);
|
||||
}
|
||||
get_at(interp, o, k).map(Some)
|
||||
element_at(interp, o, k as f64)
|
||||
}
|
||||
|
||||
/// ToObject of `this`, kept reachable while `f` runs.
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
//! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the
|
||||
//! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what
|
||||
//! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as
|
||||
//! a third argument, and is true when it gives a value other than `undefined`.
|
||||
//! a third argument, and is true when it gives a value other than `undefined`. The `Array.prototype`
|
||||
//! methods that skip missing elements, such as `forEach` and `map`, read each index of such an
|
||||
//! object with that one call and take its answer as the element, so an indexer called with `true`
|
||||
//! gives the element itself, or `undefined` when there is none.
|
||||
//!
|
||||
//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each
|
||||
//! member of its class and of the classes it descends from, apart from the members that are not
|
||||
@@ -105,7 +108,10 @@ pub struct HostClass {
|
||||
/// What `reflect` tells of the members, each under the name of one of `members`. A member
|
||||
/// without an entry has the type `unknown` and nothing else.
|
||||
pub info: Vec<(String, MemberInfo)>,
|
||||
/// What `object[i]` gives for an array index `i`.
|
||||
/// What `object[i]` gives for an array index `i`. Called with `true` as a third argument, it
|
||||
/// gives the same element, or `undefined` when there is none. The `Array.prototype` methods that
|
||||
/// skip missing elements, such as `forEach` and `map`, make that call and use its answer as the
|
||||
/// element; reads without the third argument, such as those of `join`, are ordinary reads.
|
||||
pub index: Option<HostFunction>,
|
||||
/// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`.
|
||||
pub construct: Option<HostFunction>,
|
||||
@@ -365,7 +371,8 @@ impl Interp {
|
||||
|
||||
/// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an
|
||||
/// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer
|
||||
/// gets `true` as a third argument.
|
||||
/// gets `true` as a third argument and gives the element itself, or `undefined` when there is
|
||||
/// none, not a marker.
|
||||
pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult<Value> {
|
||||
self.use_fuel()?;
|
||||
if self.host_ref_size(id)?.is_none() {
|
||||
|
||||
@@ -1035,6 +1035,49 @@ fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() {
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
/// A realm with `it`, a host collection of `len` numbers whose element `i` is `i`, and the count
|
||||
/// of the indexer's calls.
|
||||
fn numbers(len: usize) -> (Realm, Rc<Cell<u32>>) {
|
||||
let mut r = realm(10_000_000);
|
||||
let calls: Rc<Cell<u32>> = Rc::default();
|
||||
let seen = calls.clone();
|
||||
let index: HostFunction = Rc::new(move |a| {
|
||||
seen.set(seen.get() + 1);
|
||||
match a.get(1) {
|
||||
Some(Data::Number(n)) if *n < len as f64 => Ok(Data::Number(*n)),
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
});
|
||||
let length: HostFunction = Rc::new(move |_| Ok(Data::Number(len as f64)));
|
||||
let class = HostClass {
|
||||
name: "Numbers".into(),
|
||||
parent: None,
|
||||
members: vec![("length".into(), HostMember::Get(length))],
|
||||
info: Vec::new(),
|
||||
index: Some(index),
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Numbers", &[1.0]))]).unwrap();
|
||||
(r, calls)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_methods_visit_every_element_of_a_long_host_collection() {
|
||||
let (mut r, _) = numbers(5000);
|
||||
let source = "var n = 0; Array.prototype.forEach.call(it, function () { n++; }); \
|
||||
var m = Array.prototype.map.call(it, function (x) { return x; }); \
|
||||
[n, m.length, m[4999], Array.prototype.lastIndexOf.call(it, 0), Array.prototype.indexOf.call(it, 4999)].join()";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("5000,5000,4999,0,4999".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_methods_call_the_indexer_once_for_each_element() {
|
||||
let (mut r, calls) = numbers(3);
|
||||
let source = "var s = 0; Array.prototype.forEach.call(it, function (x) { s += x; }); s";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Number(3.0));
|
||||
assert_eq!(calls.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_converted_function_reads_each_argument_as_its_list_says() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -1190,7 +1190,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`.
|
||||
- `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` 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. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `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. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. A typed array constructor given an object that is not a buffer or a typed array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator to the end before mapping it, and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1); a typed array constructor converts a first argument that is not an object to a length. 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,514 of 1,514 runs pass. 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`.
|
||||
|
||||
Reference in new issue
Block a user