JavaScript: a yield reserves only the heap its saved frame takes

A yield reserved room for every finally entry on the interpreter, those
of the frames under the generator's included, and for the result it
hands back, while the saved frame keeps only its own operands and
entries. Under deep callers in finally blocks a yield could stop at the
heap limit with enough room for its frame. It now reserves what the
saved frame keeps.

The tests check the value a throw raises in a generator that has not
started, and the fuel each call of a completed generator's next takes
against a native method that takes none.

docs/mcp.md and docs/target-app-parity.md say that an engine a .js
script makes has Symbol and the iterators, and that one a .jsx script or
a source string makes does not. The parity entry no longer says that
spread is missing or that scripts call next() themselves.
This commit is contained in:
dotCooCoo committed 2026-11-22 11:27:41 -08:00
1 parent 7ce4647ef0
commit d73d0c0f9b
4 files changed
+59 -12

No files matched your search

+6 -2
View File
@@ -200,8 +200,12 @@ impl Interp {
let result = iter_result(self, v, false)?;
self.replace(1, result)?;
}
let frame = self.frame()?;
let held = (self.stack.len().saturating_sub(frame.base)).saturating_add(self.finally_sites.len()).saturating_add(self.finally_marks.len());
// What `save_frame` keeps: the frame's operands without the result, popped below, and its
// own `finally` entries, not those of the frames under it.
let base = self.frame()?.base;
let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base));
let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count();
let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks);
let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held));
self.reserve_heap(bytes)?;
let result = self.pop()?;
+47 -6
View File
@@ -100,7 +100,9 @@ fn throw_goes_into_a_suspended_generator() {
e instanceof RangeError && it.next().done",
);
// A generator that has not started is completed by `throw`, which its body never sees.
truth("var ran = false; function* g() { ran = true; } var it = g(); try { it.throw(1); } catch (e) {} !ran && it.next().done");
truth(
"var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done",
);
throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end");
}
@@ -275,6 +277,40 @@ fn an_unreachable_suspended_generator_is_freed() {
assert!(freed + 1_000_000 < held, "held {held}, after {freed}");
}
/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`.
fn smallest_heap_limit(setup: &str, script: &str) -> usize {
let fits = |limit: usize| {
let mut realm = es2015(Limits::default());
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
realm.collect_garbage();
realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() });
realm.run(script).is_ok()
};
let (mut low, mut high) = (0, 64 << 20);
assert!(fits(high), "{script}");
while high - low > 256 {
let mid = low + (high - low) / 2;
if fits(mid) {
high = mid;
} else {
low = mid;
}
}
high
}
#[test]
fn a_yield_reserves_only_what_its_frame_keeps() {
// At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks
// that a throw entered. Their entries stay with those frames, so the yield needs no more room
// than the one in `before`, which comes before those frames are pushed.
let setup = "function* g() { yield 1; } var it = g(); 0";
let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0";
let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0";
let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before));
assert!(inside < before + 4096, "inside {inside}, before {before}");
}
#[test]
fn generators_stay_within_the_limits() {
let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() });
@@ -282,12 +318,17 @@ fn generators_stay_within_the_limits() {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
// Each resumption takes fuel even when the body does no work.
let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() });
match realm.run("var it = (function* () {})(); it.next(); while (true) it.next();") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
// Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next`
// take at least 1,000 more than the same calls of a native method that takes none.
let mut realm = es2015(Limits::default());
let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0";
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
let mut used = Vec::new();
for callee in ["control", "it"] {
assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0)));
used.push(Limits::default().fuel - realm.fuel_left());
}
assert!(used[1] >= used[0] + 1000, "{used:?}");
// A deep `yield*` chain stops at the frame limit, and the realm can run again.
let mut realm = es2015(Limits { frames: 200, ..Limits::default() });
match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") {
+5 -3
View File
@@ -2661,9 +2661,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot
- `vc.args` gives a read-only copy of the `args` object each time it is read.
- `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature.
A script does not have `Symbol` or the iterators of arrays, strings and `arguments` objects: `typeof Symbol` is
`"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. The JavaScript engine's ECMAScript
2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes.
An engine that a `.js` script makes runs in the JavaScript engine's ECMAScript 2015 mode (`Options::es2015` in
`vectorcraft-js`) and has `Symbol` and the iterators of arrays, strings and `arguments` objects, as
`docs/target-app-parity.md` describes. An engine that a `.jsx` script or a `source` string makes does not have them:
`typeof Symbol` is `"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. An engine that
`#targetengine` keeps holds the built-ins of the run that made it, whichever kind of script runs in it later.
Before any of the script runs, its preprocessor lines are read. The help page
https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and
+1 -1
View File
@@ -1083,7 +1083,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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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 `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 without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `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: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
- 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. `script.run` makes the realm for a `.js` script with the option; a realm made without it, as for a `.jsx` script or a `source` string, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. `yield*` reads an iterator through `Symbol.iterator`; spread does not, and reads values by the rule the entry on ECMAScript 2015 forms gives. The language does not have `for`-`of` or destructuring yet. `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: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals, `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 509 of 549 runs of 296 tests pass (94 of 96 runs of 50 tests passed before), and the 40 others expect a configurable function `length`, a function `name` property and the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
- Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`.
- With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`.