From 290da5bef2856ea52cd623bf8098f0cdb08d5303 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:38:31 -0800 Subject: [PATCH] JavaScript: scripts have the global Boolean constructor The engine built Boolean.prototype but defined no global Boolean, so Boolean(x), new Boolean(x), x instanceof Boolean and filter(Boolean) threw a ReferenceError. Boolean now converts a value when called and makes a Boolean object with new (ECMA-262 5.1 sections 15.6.1 and 15.6.2), with Boolean.prototype as its prototype. test262 no longer skips tests that name Boolean, so more of them run; docs/target-app-parity.md has the new counts. --- crates/js/src/builtins.rs | 16 ++++++++++++++-- crates/js/src/builtins_tests.rs | 15 +++++++++++++++ crates/js/src/lib.rs | 2 +- crates/js/tests/test262.rs | 2 +- docs/target-app-parity.md | 4 ++-- 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f2c02bdf4c..78d514f725 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -1,8 +1,8 @@ //! The built-in objects (ECMA-262 5.1 section 15): `Object` with `Object.prototype` and the //! ES5 statics, `Function` with `Function.prototype.call`, `apply`, `bind` and `toString`, //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex -//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with -//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in +//! 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. //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object @@ -129,6 +129,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, function_proto, "bind", function_bind, 1)?; method(interp, function_proto, "toString", function_to_string, 0)?; + let boolean = native(interp, "Boolean", boolean_ctor, 1, NativeKind::Plain, true)?; + constructor(interp, "Boolean", boolean, boolean_proto)?; method(interp, boolean_proto, "toString", boolean_to_string, 0)?; method(interp, boolean_proto, "valueOf", boolean_value_of, 0)?; @@ -390,6 +392,16 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Ok(Value::str(&format!("[object {class}]"))) } +/// `Boolean(value)` and `new Boolean(value)` (sections 15.6.1 and 15.6.2). +fn boolean_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + let b = args.first().is_some_and(Value::truthy); + if !construct { + return Ok(Value::Bool(b)); + } + let proto = interp.intrinsics.boolean_proto; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Boolean(b), Some(proto))))) +} + /// The Boolean a `Boolean.prototype` method was called on (sections 15.6.4.2 and 15.6.4.3): a /// primitive, or the primitive value of a Boolean object. fn this_boolean(interp: &mut Interp, this: &Value, name: &str) -> JsResult { diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 0a70e80433..14a0f8d542 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -407,6 +407,21 @@ fn boolean_prototype_converts_booleans() { throws("Object.getPrototypeOf(true).valueOf.call({})", "TypeError"); } +#[test] +fn the_boolean_constructor_converts_and_wraps() { + // Called as a function it gives ToBoolean of its argument (section 15.6.1). + truth("Boolean() === false && Boolean(0) === false && Boolean('') === false && Boolean(NaN) === false && Boolean(null) === false"); + truth("Boolean(1) === true && Boolean('false') === true && Boolean({}) === true && Boolean(new Boolean(false)) === true"); + truth("['', 'a', 0, 2].filter(Boolean).length === 2"); + // With new it makes a Boolean object (section 15.6.2), which is truthy whatever it holds. + truth("var b = new Boolean(0); typeof b === 'object' && b.valueOf() === false && !!b && b instanceof Boolean"); + assert_eq!(string("Object.prototype.toString.call(new Boolean(1)) + new Boolean('')"), "[object Boolean]false"); + // The constructor and Boolean.prototype are linked, and true and false look methods up there. + truth("Boolean.prototype === Object.getPrototypeOf(true) && Boolean.prototype.constructor === Boolean && true.constructor === Boolean"); + truth("Boolean.length === 1 && Object(false) instanceof Boolean"); + truth("!Object.getOwnPropertyDescriptor(this, 'Boolean').enumerable && !Object.getOwnPropertyDescriptor(Boolean, 'prototype').writable"); +} + #[test] fn array_methods_overwriting_elements_need_no_heap_for_new_ones() { // With the heap exactly at its limit, an array method's write over an existing element diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 84fce24714..f2b501d7ab 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -26,7 +26,7 @@ //! with loops. The realm provides the language (sections 10 to 14 of ECMA-262 5.1) and these //! built-ins: the global functions and constants (15.1, with Annex B's `escape` and `unescape`), //! `Object` (15.2), `Function` with `call`, `apply` and `bind` (15.3), `Array` (15.4), `String` -//! (15.5), `Boolean.prototype`'s `toString` and `valueOf` (15.6.4), `Number` (15.7), `Math` (15.8), +//! (15.5), `Boolean` (15.6), `Number` (15.7), `Math` (15.8), //! `Date` (15.9), `RegExp` (15.10), the error types (15.11) and `JSON` (15.12). The array methods //! visit only the indices an array or array-like object has, so a sparse array of length 2^32-1 //! costs as much as its elements, and `JSON.parse`, `JSON.stringify` and the reviver walk use no diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index ec3c4dd255..d548e96c27 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -354,7 +354,7 @@ fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> { /// Globals and method names the interpreter does not provide yet: a test that names one, in its /// own source or in a harness file it includes, is skipped. -const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ +const MISSING_BUILTINS: &str = "String Number Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array charAt charCodeAt fromCharCode substring substr split replace \ match search exec test toUpperCase toLowerCase trim toFixed toPrecision toExponential now"; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d40a4216cd..622c55f580 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1090,8 +1090,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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` 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`. + - `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`. - 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 ]` 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`.