From ab12c44ebd68a318df3962d4e88896d62c9fff94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:59:26 -0800 Subject: [PATCH 1/8] JavaScript: .js scripts run async functions and await A .js script now reads async function declarations and expressions, async arrow functions and async methods in object literals, as ECMA-262 2017 section 25.5 defines them. A call returns a Promise that the function's return resolves and an uncaught exception rejects. await suspends the function's frame until its operand settles; a promise job resumes it with the value, or throws the rejection at the await, so try, catch and finally work around it. - Options::es2017 turns the syntax on and implies Options::es2015; script.run sets it for .js files. .jsx scripts and source strings keep async and await as plain names. - A suspended frame is a heap object the collector traces, reached only from its promise reactions, so a function waiting on a promise that nothing can settle is freed. Each resume is a job and takes fuel. - AsyncFunction and its prototype exist without a global binding; async functions are not constructors and have no prototype property. - The test262 runner reads the async-function, await and async-arrow folders and counts runs with and without the option; an async test with a runtime negative now has to throw. --- crates/engine/src/script/include.rs | 5 +- crates/engine/src/script/mod.rs | 4 +- crates/engine/src/tests/script_run.rs | 23 +++ crates/js/src/ast.rs | 4 + crates/js/src/async_tests.rs | 159 +++++++++++++++ crates/js/src/builtins.rs | 19 +- crates/js/src/builtins/async_function.rs | 41 ++++ crates/js/src/builtins/promise.rs | 145 +++++++++++++- crates/js/src/bytecode.rs | 7 +- crates/js/src/compiler.rs | 14 +- crates/js/src/heap.rs | 14 +- crates/js/src/interp.rs | 109 ++++++++++- crates/js/src/interp/async_function.rs | 153 +++++++++++++++ crates/js/src/interp_tests.rs | 1 + crates/js/src/lib.rs | 26 ++- crates/js/src/parser.rs | 234 ++++++++++++++++++++--- crates/js/src/realm.rs | 8 + crates/js/tests/test262.rs | 134 ++++++++++++- docs/mcp.md | 12 ++ docs/target-app-parity.md | 1 + 20 files changed, 1047 insertions(+), 66 deletions(-) create mode 100644 crates/js/src/async_tests.rs create mode 100644 crates/js/src/builtins/async_function.rs create mode 100644 crates/js/src/interp/async_function.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index a024949a35..f380c6cbd7 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -221,7 +221,8 @@ pub(crate) struct Files { es2015: bool, } -/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] and +/// [`vectorcraft_js::Options::es2017`] when its file name ends in /// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as /// ECMAScript 5.1 with the ExtendScript extensions. pub(crate) fn es2015_script(path: Option<&str>) -> bool { @@ -326,7 +327,7 @@ impl Files { /// The options a file of this run is parsed with, preprocessor lines aside. pub(crate) fn options(&self) -> Options { - Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, es2017: self.es2015, ..Options::default() } } /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index a9c828532e..af62a9c5e6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1979,13 +1979,15 @@ impl Session { // A `.js` script's realm has the later editions' built-ins (`Promise`). A kept realm gets // them at the first `.js` run that names it, and keeps them as it keeps its globals. let es2015 = include::es2015_script(request.file.as_deref()); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; + // It also reads async functions and `await` (ECMAScript 2017). + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, es2017: es2015, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + realm.set_es2017(es2015); if es2015 { realm.add_es2015(); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..3d08a4f64d 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -331,6 +331,29 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("es2017"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let src = "async function twice(p) { return 2 * await p; }\nvar half = async x => x / 2;\n\ + twice(Promise.resolve(3)).then(function (v) { vc.log(v); });\n\ + (async function () { try { await Promise.reject(new Error('no')); } catch (e) { vc.log(await half(8) + e.message); } })();\n\ + vc.log('sync');\n"; + let r = s.execute("script.run", &path(&write("async.js", src))).unwrap(); + assert_eq!(r["log"], json!(["sync", 6, "4no"]), "{r}"); + for (name, text) in [("async.jsx", "async function f() {}"), ("arrow.jsx", "var f = async x => x;")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..6fa32e6253 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -218,6 +218,8 @@ pub enum Expr { /// `...expression` in an array literal or an argument list, and as the last of an arrow /// function's parenthesized parameters while they are read. Spread(ExprId), + /// `await operand`, in an async function's body. + Await(ExprId), } /// A piece of a template literal's text between its substitutions. @@ -393,6 +395,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// An async function (ECMAScript 2017): a call returns a promise, and its body may `await`. + pub is_async: bool, pub span: Span, } diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs new file mode 100644 index 0000000000..46656f1205 --- /dev/null +++ b/crates/js/src/async_tests.rs @@ -0,0 +1,159 @@ +//! Async functions and `await` in realms with [`Options::es2017`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2017: true, ..Options::default() }, Limits::default()) +} + +/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran. +fn log(src: &str) -> String { + let mut r = realm(); + if let Err(e) = r.run(&format!("var log = [];\n{src}")) { + panic!("{src}\n{e:?}"); + } + match r.run("log.join(' ')") { + Ok(JsValue::String(s)) => s, + other => panic!("{src}: {other:?}"), + } +} + +fn syntax_error(r: &mut Realm, src: &str) { + match r.run(src) { + Err(e) if e.kind == RunErrorKind::Syntax => {} + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn awaits_resume_in_the_job_order_promise_reactions_have() { + let src = "async function f() { log.push('f1'); await null; log.push('f2'); await null; log.push('f3'); }\n\ + f();\n\ + Promise.resolve().then(function () { log.push('t1'); }).then(function () { log.push('t2'); });\n\ + log.push('sync');"; + assert_eq!(log(src), "f1 sync f2 t1 f3 t2"); +} + +#[test] +fn the_function_returns_a_promise_its_return_resolves_and_its_throw_rejects() { + let src = "async function ok(x) { return x + 1; }\n\ + async function bad() { throw new TypeError('no'); }\n\ + var p = ok(1); log.push(p instanceof Promise);\n\ + p.then(function (v) { log.push('ok ' + v); });\n\ + bad().then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true ok 2 true"); +} + +#[test] +fn a_rejected_await_throws_where_it_stands_and_finally_runs_after_an_await() { + let src = "async function f() {\n\ + try { await Promise.reject('r'); log.push('not here'); }\n\ + catch (e) { log.push('caught ' + e); }\n\ + finally { await 1; log.push('finally'); }\n\ + return 'end';\n\ + }\n\ + f().then(function (v) { log.push(v); });"; + assert_eq!(log(src), "caught r finally end"); + let rethrow = "async function g() { try { await Promise.reject(new Error('x')); } finally { log.push('cleanup'); } }\n\ + g().catch(function (e) { log.push('rejected ' + e.message); });"; + assert_eq!(log(rethrow), "cleanup rejected x"); +} + +#[test] +fn arrows_expressions_and_methods_can_be_async() { + let src = "var a = async x => (await x) * 2;\n\ + var b = async (x, y) => { return await x + y; };\n\ + var c = async function named() { return typeof named; };\n\ + var o = { async m(v) { return this.k + await v; }, k: 'k' };\n\ + Promise.all([a(2), b(Promise.resolve(1), 2), c(), o.m('v')]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "4,3,function,kv"); +} + +#[test] +fn async_functions_are_not_constructors_and_have_no_prototype() { + let src = "async function f() {}\n\ + log.push(f.hasOwnProperty('prototype'));\n\ + try { new f(); } catch (e) { log.push(e instanceof TypeError); }\n\ + var AF = Object.getPrototypeOf(f).constructor;\n\ + log.push(AF !== Function, typeof AF, Object.getPrototypeOf(AF) === Function);\n\ + log.push(typeof this.AsyncFunction);\n\ + var g = AF('a', 'return await a;');\n\ + log.push(Object.getPrototypeOf(g) === Object.getPrototypeOf(f));\n\ + g(5).then(function (v) { log.push(v); });\n\ + log.push(String(async function h() { await 0; }));"; + assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5"); +} + +#[test] +fn await_is_an_identifier_outside_async_functions() { + let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\ + var async = function (x) { return x; }; log.push(async(1));\n\ + async\nfunction g() {}\n\ + log.push(typeof g);"; + assert_eq!(log(src), "3 1 function"); + // A function in an async arrow function's parameters reads `await` as its own body does, + // and an async function declared in a script may be named `await`. + let nested = "var g = async (x = function () { return await; }) => x;\n\ + var h = async (x = async function () { await 0; }) => x;\n\ + async function await() { return 1; }\n\ + log.push(typeof g, typeof h, typeof await);"; + assert_eq!(log(nested), "function function function"); + let mut r = realm(); + syntax_error(&mut r, "async function f() { var await; }"); + syntax_error(&mut r, "async function f(await) {}"); + syntax_error(&mut r, "async function f(x = await 1) {}"); + syntax_error(&mut r, "function f() { await 1; }"); + syntax_error(&mut r, "if (1) async function f() {}"); + syntax_error(&mut r, "async (x = await 1) => x"); + syntax_error(&mut r, "async\n(x) => x"); + syntax_error(&mut r, "async (a = (...await) => {}) => {}"); +} + +#[test] +fn a_suspended_function_survives_a_collection_and_an_unreachable_one_is_freed() { + let mut r = realm(); + r.run( + "var resume; var gate = new Promise(function (res) { resume = res; });\n\ + var out = [];\n\ + async function f() { var local = { n: 41 }; var v = await gate; out.push(local.n + v); }\n\ + f();", + ) + .unwrap(); + r.interp().collect_garbage(); + r.run("resume(1);").unwrap(); + assert_eq!(r.run("out.join()").unwrap(), JsValue::String("42".into())); + // A function waiting on a promise nothing can settle is collected with it. + r.interp().collect_garbage(); + let before = r.interp().heap.live_cells(); + r.run("(function () { async function w() { var big = []; for (var i = 0; i < 200; i++) big.push({ i: i }); await new Promise(function () {}); } w(); })();") + .unwrap(); + r.interp().collect_garbage(); + let after = r.interp().heap.live_cells(); + assert!(after < before + 50, "{before} {after}"); +} + +#[test] +fn a_run_that_ends_with_awaits_pending_ends_cleanly() { + let mut r = realm(); + let v = r.run("async function f() { await new Promise(function () {}); return 1; } f(); 'done'").unwrap(); + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); + assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn each_resume_takes_fuel() { + let mut r = realm(); + r.set_limits(Limits { fuel: 20_000, ..Limits::default() }); + let e = r.run("async function f() { for (;;) await 0; } f();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); +} + +#[test] +fn es5_and_extendscript_realms_do_not_read_async_functions() { + let mut es2015 = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()); + syntax_error(&mut es2015, "async function f() {}"); + assert_eq!(es2015.run("var async = 1, await = 2; async + await").unwrap(), JsValue::Number(3.0)); + syntax_error(&mut Realm::with_options(Options::default(), Limits::default()), "async function f() {}"); + syntax_error(&mut Realm::new(), "var f = async () => 1;"); +} diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 26b351e14a..09cb089e5b 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -10,6 +10,7 @@ //! run past [`crate::Limits`]. mod array; +mod async_function; pub(crate) mod extensions; mod global; mod json; @@ -464,7 +465,16 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + dynamic_function(interp, args, false) +} + +/// The function `Function(p1, …, body)` makes, or with `is_async` the async function that +/// `AsyncFunction(p1, …, body)` makes from `(async function anonymous(p1,…\n) {\nbody\n})` +/// (ECMA-262 2017 section 25.5.1.1). An async function's source is read with +/// [`crate::Options::es2017`] whatever the realm reads scripts with, since only an async function +/// leads a script to `AsyncFunction`. +pub(crate) fn dynamic_function(interp: &mut Interp, args: &[Value], is_async: bool) -> JsResult { + let head: &str = if is_async { "(async function anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -476,12 +486,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -494,7 +504,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.observe_code(&units); interp.source_units = interp.source_units.saturating_add(units.len()); let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len())); - let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() }; + let es2017 = interp.options.es2017 || is_async; + let options = crate::Options { strict: false, max_source_units: remaining, es2017, ..interp.options.clone() }; let program = match crate::parse_utf16(&units, &options) { Ok(p) => p, Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)), diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs new file mode 100644 index 0000000000..43eea77b2a --- /dev/null +++ b/crates/js/src/builtins/async_function.rs @@ -0,0 +1,41 @@ +//! `AsyncFunction` and its prototype (ECMA-262 2017 section 25.5, +//! ), in realms with +//! [`crate::Options::es2015`]: the prototype of every async function, and the constructor a script +//! reaches through it. `AsyncFunction` is not a global. + +use super::{data, dynamic_function, native}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, ObjId, Object}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +/// Creates `AsyncFunction` and `AsyncFunction.prototype`, keeping the prototype for the async +/// functions the realm makes. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let function_proto = interp.intrinsics.function_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + interp.promises.async_function_proto = Some(proto); + let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?; + interp.promises.async_function_ctor = Some(ctor); + // `Function` is the constructor's prototype (section 25.5.2). + let function_ctor = constructor_of(interp, function_proto); + if let Some(o) = interp.heap.object_mut(ctor) { + o.proto = function_ctor.or(o.proto); + } + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary + // built-in prototypes. + data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) +} + +/// The `constructor` property `proto` has from the built-ins, when it is an object. +fn constructor_of(interp: &Interp, proto: ObjId) -> Option { + match interp.get_own_property(proto, &crate::heap::key("constructor")) { + Ok(Some(crate::heap::Prop::Data { value: Value::Object(o), .. })) => Some(o), + _ => None, + } +} + +/// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). +fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index d960fac60b..53d08f6f06 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -142,6 +142,8 @@ enum Then { Settle(ObjId), /// An exception rejects through this resolving record. Reject(ObjId), + /// An async function goes on after `await`; its own promise takes its result. + Resume, } /// The built-in functions a promise operation's functions call, with their record. @@ -156,9 +158,11 @@ enum Kind { CatchFinally, ValueThunk, Thrower, + AwaitFulfilled, + AwaitRejected, } -const KINDS: [(Kind, NativeFn); 9] = [ +const KINDS: [(Kind, NativeFn); 11] = [ (Kind::Resolve, resolve_function), (Kind::Reject, reject_function), (Kind::AllElement, all_element), @@ -168,6 +172,8 @@ const KINDS: [(Kind, NativeFn); 9] = [ (Kind::CatchFinally, catch_finally), (Kind::ValueThunk, value_thunk), (Kind::Thrower, thrower), + (Kind::AwaitFulfilled, await_continuation), + (Kind::AwaitRejected, await_continuation), ]; /// `Promise`'s objects and the run's job queue. @@ -186,11 +192,17 @@ pub(crate) struct Promises { rejected: Vec, /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). pub(crate) max_jobs: usize, + /// `AsyncFunction.prototype` (ECMA-262 2017 section 25.5.3), the prototype of async functions. + pub(crate) async_function_proto: Option, + /// `AsyncFunction` (section 25.5.1), which is not a global. + pub(crate) async_function_ctor: Option, } impl Default for Promises { fn default() -> Self { Self { + async_function_proto: None, + async_function_ctor: None, proto: None, ctor: None, natives: Vec::new(), @@ -208,10 +220,11 @@ impl Promises { /// Adds what the queue and the promise objects hold to the collector's roots. pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); + roots.objects.extend(self.async_function_proto.iter().chain(&self.async_function_ctor)); roots.values.extend(self.completion.iter()); match &self.running { Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), - None => {} + Some(Then::Resume) | None => {} } for job in &self.queue { match job { @@ -259,7 +272,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { let n = native(interp, "", f, 1, NativeKind::Plain, false)?; interp.promises.natives.push(n); } - Ok(()) + super::async_function::install(interp) } /// Turns on [`crate::Options::es2015`] in a realm made without it and creates `Promise` there, @@ -552,6 +565,120 @@ fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult }) } +// ---- async functions ---- + +/// The built-in a suspended async function's reactions are bound to. The job queue resumes the +/// function instead of calling it, and scripts cannot reach it. +fn await_continuation(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(Abrupt::Internal("an await continuation was called".into())) +} + +impl Interp { + /// Settles the promise of an async function whose frame ends: its return value resolves it, + /// and the exception that leaves it rejects it. + pub(crate) fn settle_async(&mut self, p: ObjId, r: Result) -> JsResult<()> { + match r { + Ok(v) => resolve_promise(self, p, v), + Err(e) => { + let site = caught(self); + reject_promise(self, p, e, site) + } + } + } + + /// A new pending promise for the async function call whose frame is on top. + pub(crate) fn new_async_promise(&mut self) -> JsResult { + new_promise(self) + } + + /// `await v` in the async function the top frame runs (Await, ECMA-262 2017 section 6.2.3.1, + /// with PromiseResolve as later editions have it): `v` becomes a built-in promise, the frame + /// is suspended until it settles, and the function's call gives its promise, `Some` when the + /// frame was the boundary frame. Throws at the `await` when reading `v`'s `constructor` throws. + pub(crate) fn await_value(&mut self, v: Value) -> JsResult> { + if self.async_promise().is_none() { + return Err(Abrupt::Internal("await outside an async function".into())); + } + let ctor = self.promises.ctor.map_or(Value::Undefined, Value::Object); + scoped(self, |interp| { + let p = promise_resolve(interp, &ctor, v)?; + root(interp, &p); + let Value::Object(p) = p else { return Err(Abrupt::Internal("PromiseResolve gave a value that is not a promise".into())) }; + let bytes = interp.suspend_bytes(); + interp.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let act = interp.heap.alloc_object(Object::new(Class::Activation(None), None)); + root(interp, &Value::Object(act)); + let on_fulfilled = record_function(interp, Kind::AwaitFulfilled, act, 1)?; + root(interp, &on_fulfilled); + let on_rejected = record_function(interp, Kind::AwaitRejected, act, 1)?; + root(interp, &on_rejected); + // The reactions settle no promise of their own; this one stays pending and unseen. + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + promise_data(interp, derived)?.handled = true; + perform_then(interp, p, on_fulfilled, on_rejected, derived)?; + let (a, boundary) = interp.suspend_frame()?; + let promise = a.promise; + let held = a.bytes(); + if let Some(o) = interp.heap.object_mut(act) { + o.class = Class::Activation(Some(Box::new(a))); + } + interp.heap.bytes = interp.heap.bytes.saturating_add(held); + if boundary { + return Ok(Some(Value::Object(promise))); + } + interp.push(Value::Object(promise))?; + Ok(None) + }) + } + + /// The activation `handler` resumes when it is a suspended async function's reaction, and + /// whether it is the rejection's. + fn await_activation(&self, handler: &Value) -> Option<(ObjId, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let reject = if self.promises.natives.get(Kind::AwaitFulfilled as usize) == Some(target) { + false + } else if self.promises.natives.get(Kind::AwaitRejected as usize) == Some(target) { + true + } else { + return None; + }; + match args.first() { + Some(Value::Object(act)) => Some((*act, reject)), + _ => None, + } + } + + /// Resumes the async function `handler` belongs to with the settled value: its frame goes back + /// on top as a boundary frame the caller runs, and a rejection is thrown at its `await`. A job + /// that finds the frame already resumed does nothing. + fn resume_async(&mut self, handler: &Value, argument: Value, reject: bool, site: Option) -> JsResult<()> { + let Some((act, _)) = self.await_activation(handler) else { return Err(Abrupt::Internal("not an await reaction".into())) }; + let taken = match self.heap.object_mut(act).map(|o| &mut o.class) { + Some(Class::Activation(slot)) => slot.take(), + _ => return Err(Abrupt::Internal("an await reaction lost its activation".into())), + }; + let Some(a) = taken else { return Ok(()) }; + self.heap.bytes = self.heap.bytes.saturating_sub(a.bytes()); + self.restore_frame(*a)?; + self.promises.running = Some(Then::Resume); + if !reject { + return self.push(argument); + } + if site.is_some() { + self.throw_site = site; + } + match self.unwind_or_abort(argument) { + Ok(Some(v)) => self.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => self.finish_job(Err(e)), + Err(e) => Err(e), + } + } +} + // ---- the job queue ---- impl Interp { @@ -627,6 +754,10 @@ impl Interp { self.use_fuel()?; scoped(self, |interp| { let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, site, .. } if interp.await_activation(&handler).is_some() => { + root(interp, &argument); + return interp.resume_async(&handler, argument, reject, site); + } Job::Reaction { handler, argument, reject, derived, site } => { if !interp.is_callable(&handler) { return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; @@ -660,7 +791,7 @@ impl Interp { match (then, r) { (Then::Settle(d), Ok(v)) => resolve_promise(self, d, v), (Then::Settle(d), Err(e)) => reject_promise(self, d, e, site), - (Then::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(_), Ok(_)) | (Then::Resume, _) => Ok(()), (Then::Reject(rec), Err(e)) => scoped(self, |interp| { root(interp, &Value::Object(rec)); reject_through(interp, rec, e, site) @@ -835,8 +966,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -845,7 +976,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { .. } => return Ok(true), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.is_async), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..723ad84b40 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -205,6 +205,9 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `value` → its awaited value: suspends the running async function until the value settles, + /// and goes on with its fulfillment value or throws its rejection reason here. + Await, } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -299,6 +302,8 @@ pub(crate) struct Code { /// The function has default or rest parameters: its parameters start uninitialized, its /// code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The code is an async function's: a call returns a promise, and it may run [`Op::Await`]. + pub(crate) is_async: bool, } impl Code { @@ -380,7 +385,7 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1), Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), - Op::ToStr => e(1, 1), + Op::ToStr | Op::Await => e(1, 1), }) } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..dac56b9359 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -268,12 +268,14 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some(f) = self.ast.function(*fid) else { return internal("function out of range") }; + let Some(name) = f.name.as_ref() else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations a variable, not async ones. + if !self.strict && !f.is_async { annex.push((k, scope, id)); } } else { @@ -1158,6 +1160,11 @@ impl<'a> FnCompiler<'a> { Expr::Template { quasis, exprs } => self.template(quasis, exprs)?, Expr::TaggedTemplate { .. } => self.chain(id)?, Expr::Spread(_) => return internal("spread outside an array literal or argument list"), + Expr::Await(arg) => { + self.expr(*arg)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::Await); + } Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?, Expr::Unary { .. } => self.unary(id)?, Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?, @@ -1762,6 +1769,7 @@ impl<'a> FnCompiler<'a> { arrow: meta.arrow, uses_this: self.uses_this, param_init: meta.param_init, + is_async: meta.is_async, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -1780,6 +1788,7 @@ struct Meta { length: u32, arrow: bool, param_init: bool, + is_async: bool, } fn len_u32(n: usize) -> u32 { @@ -1844,6 +1853,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, length: len_u32(length), arrow: f.kind == FunctionKind::Arrow, param_init, + is_async: f.is_async, }; c.finish(hoisted, meta) } diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index a1af2cd0bd..e25bac7323 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -250,6 +250,8 @@ pub(crate) enum Class { Promise(Box), /// The state that the functions a promise operation makes share; scripts never see it. PromiseRecord(Box), + /// An async function's frame waiting at `await`, until it is resumed; scripts never see it. + Activation(Option>), } /// What an XML value is. @@ -313,7 +315,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::XmlFilter(_) | Class::PromiseRecord(_) | Class::Activation(_) => "Object", Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", @@ -728,6 +730,16 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } extra = crate::builtins::promise::RECORD_BYTES; } + Class::Activation(Some(a)) => { + for v in a.values() { + mark_value(v, work, strings); + } + work.extend(a.ids()); + for code in a.codes() { + mark_code(code, strings); + } + extra = a.bytes(); + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 8c77936da5..783fd80f95 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -184,11 +184,16 @@ pub(crate) struct Frame { completion: Value, /// Returning from this frame returns from the Rust call that pushed it. boundary: bool, + /// The promise of the async function the frame runs: a return resolves it, an exception + /// that leaves the frame rejects it, and the call's value is the promise. + async_promise: Option, } /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +pub(crate) mod async_function; + /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -502,7 +507,8 @@ fn is(k: &[u16], s: &str) -> bool { } impl Interp { - pub(crate) fn new(options: Options, limits: Limits) -> Self { + pub(crate) fn new(mut options: Options, limits: Limits) -> Self { + options.es2015 = options.modern(); let mut heap = Heap::default(); let global = heap.alloc_object(Object::new(Class::Ordinary, None)); let global_env = heap.alloc_env(Env::Obj { object: global, with_this: false, outer: None }); @@ -787,7 +793,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.async_promise.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -816,7 +822,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(v), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(v); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -835,7 +845,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(Some(v)), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(Some(v)); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -870,10 +884,26 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::Await => { + let v = self.pop()?; + self.await_value(v) + } _ => self.exec(op).map(|()| None), } } + /// [`Self::unwind`], ending the frames down to the boundary frame when it fails with a limit + /// or an internal error, which leaves the frame it was in on top. + pub(crate) fn unwind_or_abort(&mut self, v: Value) -> JsResult> { + match self.unwind(v) { + Err(e @ (Abrupt::Limit(_) | Abrupt::Internal(_))) => { + self.abort_to_boundary(); + Err(e) + } + r => r, + } + } + fn note_site(&mut self) { if self.throw_site.is_none() && let Some(f) = self.frames.last() @@ -884,7 +914,10 @@ impl Interp { /// Finds the handler for an exception: in the top frame, or in the frames below it up to the /// boundary frame. Returns the exception when no handler takes it before the boundary frame. - fn unwind(&mut self, v: Value) -> JsResult<()> { + /// An async function's frame without a handler rejects its promise with the exception and + /// returns the promise as a `return` would: `Some` with it when that frame was the boundary + /// frame. + fn unwind(&mut self, v: Value) -> JsResult> { self.note_site(); let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed @@ -920,10 +953,25 @@ impl Interp { if let (false, Some(site)) = (caught, site) { self.finally_sites.push((site, target_len)); } - return Ok(()); + return Ok(None); + } + // The promise is settled while the frame is still on top, so a limit reached doing it + // ends the frames the way any other limit does. + let promise = frame.async_promise; + if let Some(p) = promise { + self.settle_async(p, Err(v.clone()))?; } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + if let Some(p) = promise { + self.drop_left_finally_marks(); + self.drop_left_finally_sites(frame.base); + if frame.boundary { + return Ok(Some(Value::Object(p))); + } + self.push(Value::Object(p))?; + return Ok(None); + } if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -947,6 +995,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // An async function's return resolves its promise, while the frame is still on top, and + // the call gives the promise. + let v = match self.async_promise() { + Some(p) => { + self.settle_async(p, Ok(v))?; + Value::Object(p) + } + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); // A `return` in a finally block leaves the block, and the value takes its exception's slot. @@ -1100,7 +1157,7 @@ impl Interp { self.replace(1, Value::String(s)) } Op::TemplateObject(i) => self.op_template_object(i), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Return | Op::ReturnCompletion | Op::Await => internal("return reached the dispatcher"), } } @@ -2095,17 +2152,30 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let is_async = code.is_async; + let proto = match self.promises.async_function_proto { + Some(p) if is_async => p, + _ => self.intrinsics.function_proto, + }; let length = code.length; let strict = code.strict; let arrow = code.arrow; let self_name = code.self_name.clone(); let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto))); self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; - // An arrow function has no `prototype` and cannot be constructed (section 14.2.16). + // An arrow function has no `prototype` and cannot be constructed (section 14.2.16), and + // neither has nor can an async function (ECMA-262 2017 section 25.5.4). An async function + // must not have own `caller` or `arguments` properties, restricted or not, in sloppy code + // too (section 16.2). if arrow { return Ok(f); } + if is_async { + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } let p = self.new_object(); self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; @@ -2701,6 +2771,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.is_async => Err(self.type_error("an async function is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; let proto = match self.get_from(callee, &key("prototype"), &f)? { @@ -2764,6 +2835,7 @@ impl Interp { } }; let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?; + let code_is_async = code.is_async; let base = self.stack.len(); self.frames.push(Frame { code, @@ -2777,7 +2849,16 @@ impl Interp { construct, completion: Value::Undefined, boundary, + async_promise: None, }); + // An async function's call makes its promise first thing (section 25.5.5.2); the frame + // keeps what the function holds reachable while it is made. + if code_is_async && let Err(e) = self.start_async_call() { + if let Some(frame) = self.frames.pop() { + self.stack.truncate(frame.base); + } + return Err(e); + } Ok(()) } @@ -3135,9 +3216,16 @@ impl Interp { self.global_lex } - /// Sets [`Options::es2015`] for the next runs. + /// Sets [`Options::es2015`] for the next runs; turning it off turns [`Options::es2017`] off too. pub(crate) fn set_es2015(&mut self, es2015: bool) { self.options.es2015 = es2015; + self.options.es2017 &= es2015; + } + + /// Sets [`Options::es2017`] for the next runs; turning it on turns [`Options::es2015`] on too. + pub(crate) fn set_es2017(&mut self, es2017: bool) { + self.options.es2017 = es2017; + self.options.es2015 |= es2017; } /// Declares a script's top-level `let` and `const` names in the global scope, uninitialized @@ -3213,6 +3301,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + async_promise: None, }); Ok(()) } diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs new file mode 100644 index 0000000000..7121215b9d --- /dev/null +++ b/crates/js/src/interp/async_function.rs @@ -0,0 +1,153 @@ +//! An async function's frame while it waits at `await` (ECMA-262 2017 sections 25.5 and 6.2.3.1, +//! ): [`Interp::suspend_frame`] moves the running +//! frame, its operands and its pending `finally` state into an [`Activation`], which lives on the +//! heap inside the functions that resume it, and [`Interp::restore_frame`] puts it back on top of +//! the frames to go on. An activation that nothing can resume any more is collected like any +//! other object. + +use std::rc::Rc; + +use super::{Frame, Interp, JsResult, ThrowSite, internal}; +use crate::bytecode::Code; +use crate::heap::{EnvId, ObjId}; +use crate::value::Value; + +/// The estimated bytes of an activation, beyond the object and its operands. +pub(crate) const ACTIVATION_BYTES: usize = 128; +/// The estimated bytes of each operand, `finally` mark or `finally` site an activation keeps. +pub(crate) const SLOT_BYTES: usize = 16; + +/// A suspended frame. Stack slots in `marks` and `sites` count from the frame's first operand. +#[derive(Clone)] +pub(crate) struct Activation { + code: Rc, + pc: usize, + env: EnvId, + var_env: EnvId, + env_depth: u32, + this: Value, + callee: Option, + completion: Value, + /// The promise the async function's call returned. + pub(crate) promise: ObjId, + stack: Vec, + marks: Vec<(ObjId, u32, usize)>, + sites: Vec<(ThrowSite, usize)>, +} + +impl Activation { + /// The values the activation holds, for the collector. + pub(crate) fn values(&self) -> impl Iterator { + self.stack.iter().chain([&self.this, &self.completion]) + } + + /// The objects and environments the activation holds, for the collector. + pub(crate) fn ids(&self) -> impl Iterator { + self.callee.iter().chain([&self.promise]).chain(self.marks.iter().map(|(o, _, _)| o)).map(|o| o.0).chain([self.env.0, self.var_env.0]) + } + + /// The code the activation runs and the code of its `finally` sites, for the collector. + pub(crate) fn codes(&self) -> impl Iterator { + std::iter::once(&*self.code).chain(self.sites.iter().map(|((code, _), _)| &**code)) + } + + /// The estimated bytes of the activation, beyond the object. + pub(crate) fn bytes(&self) -> usize { + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(self.stack.len() + self.marks.len() + self.sites.len())) + } +} + +impl Interp { + /// The promise of the async function the top frame runs, when it runs one. + pub(crate) fn async_promise(&self) -> Option { + self.frames.last().and_then(|f| f.async_promise) + } + + /// Makes the promise of the async function call whose frame was just pushed. + pub(crate) fn start_async_call(&mut self) -> JsResult<()> { + let p = self.new_async_promise()?; + match self.frames.last_mut() { + Some(f) => { + f.async_promise = Some(p); + Ok(()) + } + None => internal("an async call without a frame"), + } + } + + /// The bytes [`Self::suspend_frame`] will move off the operand stack, for the heap check made + /// before it. + pub(crate) fn suspend_bytes(&self) -> usize { + let Some(f) = self.frames.last() else { return ACTIVATION_BYTES }; + let n = self.stack.len().saturating_sub(f.base) + + self.finally_marks.iter().filter(|&&(_, _, s)| s >= f.base).count() + + self.finally_sites.iter().filter(|&&(_, s)| s >= f.base).count(); + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(n)) + } + + /// Takes the top frame, which runs an async function, off the frames with its operands and + /// its `finally` state. Gives the activation and whether the frame was a boundary frame. + pub(crate) fn suspend_frame(&mut self) -> JsResult<(Activation, bool)> { + let Some(frame) = self.frames.pop() else { return internal("await without a frame") }; + let Some(promise) = frame.async_promise else { return internal("await outside an async function") }; + let base = frame.base; + if self.stack.len() < base { + return internal("frame operands below the stack"); + } + let stack = self.stack.split_off(base); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(o, mark, slot)| { + if slot < base { + return true; + } + marks.push((o, mark, slot - base)); + false + }); + let at = self.finally_sites.iter().position(|&(_, slot)| slot >= base).unwrap_or(self.finally_sites.len()); + let sites = self.finally_sites.split_off(at).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let activation = Activation { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + promise, + stack, + marks, + sites, + }; + Ok((activation, frame.boundary)) + } + + /// Puts a suspended frame back on top of the frames as a boundary frame, with its operands at + /// the top of the operand stack. + pub(crate) fn restore_frame(&mut self, a: Activation) -> JsResult<()> { + if self.frames.len() >= self.limits.frames { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Frames)); + } + let base = self.stack.len(); + for v in a.stack { + self.push(v)?; + } + self.finally_marks.extend(a.marks.into_iter().map(|(o, mark, slot)| (o, mark, slot + base))); + self.finally_sites.extend(a.sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.frames.push(Frame { + code: a.code, + pc: a.pc, + base, + env: a.env, + var_env: a.var_env, + env_depth: a.env_depth, + this: a.this, + callee: a.callee, + construct: None, + completion: a.completion, + boundary: true, + async_promise: Some(a.promise), + }); + Ok(()) + } +} diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index d0bed32c1d..4a281a7b2f 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -983,6 +983,7 @@ fn code(ops: Vec) -> Code { arrow: false, uses_this: false, param_init: false, + is_async: false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 3bc60375e9..36577c7960 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -63,6 +63,10 @@ //! jobs a script queues run in order once its code has ended, before its run ends, on the run's //! limits; a promise still rejected with no handler at the end is reported by //! [`Realm::unhandled_rejections`]. +//! +//! With [`Options::es2017`], the parser and the realm also read and run async functions and +//! `await` (ECMA-262 2017 section 25.5, ). +//! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] pub mod ast; @@ -126,11 +130,29 @@ pub struct Options { /// Give a realm the later editions' built-ins this engine has: `Promise` and its job queue. /// Off, a realm has the ES5.1 built-ins only, as ExtendScript scripts expect. pub es2015: bool, + /// Also read and run async functions and `await` (ECMAScript 2017). It turns on + /// [`Options::es2015`] too, whatever that field says. Off, `async` and `await` are identifiers. + pub es2017: bool, +} + +impl Options { + /// [`Options::es2015`], which [`Options::es2017`] turns on too. + pub(crate) fn modern(&self) -> bool { + self.es2015 || self.es2017 + } } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } + Self { + strict: false, + preprocessor_lines: false, + max_depth: DEFAULT_MAX_DEPTH, + max_source_units: 64 << 20, + e4x: false, + es2015: false, + es2017: false, + } } } @@ -226,6 +248,8 @@ impl LineTable { } } +#[cfg(test)] +mod async_tests; #[cfg(test)] mod builtins_tests; #[cfg(test)] diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index db034d1e2d..c2ce5505b3 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -36,6 +36,21 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is an async function's body: `await` is an operator, not an identifier. + in_async: bool, + /// The code is an async function's parameters: `await` is neither an operator nor an + /// identifier there (ECMA-262 2017 section 14.6.1). + async_params: bool, +} + +/// What the parser noted about a parenthesized expression or a call to `async` that may turn out +/// to be an arrow function's head. +#[derive(Clone, Copy, Debug)] +struct Head { + /// A line break comes between `async` and `(`. + line_break: bool, + /// The parentheses hold an `await` expression or the identifier `await`. + awaits: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -72,6 +87,8 @@ enum BinKind { enum Prefix { Unary(UnaryOp), Update(UpdateOp), + /// `await`, in an async function's body. + Await, } pub(crate) struct Parser<'s> { @@ -101,11 +118,20 @@ pub(crate) struct Parser<'s> { es2015: bool, /// The scopes open around the current token, outermost first (only with `es2015`). scopes: Vec, + /// Read async functions and `await` ([`crate::Options::es2017`]). + es2017: bool, + /// How many `await` expressions and `await` identifiers have been read. + awaits: u32, + /// The parenthesized expressions and calls to `async` read so far that may be arrow heads. + heads: HashMap, + /// The last identifier expression read from an `async` written without escapes. + async_ident: Option, } impl<'s> Parser<'s> { pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result { - let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(options.es2015); + let es2015 = options.modern(); + let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(es2015); let placeholder = Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false }; let mut parser = Self { @@ -123,8 +149,12 @@ impl<'s> Parser<'s> { function_allowed: false, in_list: false, e4x: options.e4x, - es2015: options.es2015, - scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2015, + scopes: if es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2017: options.es2017, + awaits: 0, + heads: HashMap::new(), + async_ident: None, }; parser.tok = parser.next_significant()?; Ok(parser) @@ -266,9 +296,23 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if name == "await" && (self.ctx.in_async || self.ctx.async_params) { + return Err(self.error_at_token(token, "'await' cannot be an identifier in an async function")); + } Ok(()) } + /// The current token is `async` written without escapes, read as the start of an async + /// function or arrow function only with [`crate::Options::es2017`]. + fn at_async(&self) -> bool { + self.es2017 && self.tok.ident() == Some("async") && !self.tok.escaped + } + + /// The current token is `async` and `function` follows it on the same line: an async function. + fn at_async_function(&self) -> bool { + self.at_async() && self.peek().is_some_and(|t| t.is_keyword(Keyword::Function) && !t.newline_before) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -280,6 +324,9 @@ impl<'s> Parser<'s> { if self.ctx.strict && is_eval_or_arguments(&name) { return Err(self.error_at_token(&self.tok, format!("'{name}' cannot be declared in strict mode"))); } + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } let token = self.bump()?; Ok(Name { name, span: token.span }) } @@ -341,7 +388,11 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some(f) = self.ast.function(id) else { return Ok(()) }; + let Some(name) = f.name.clone() else { return Ok(()) }; + // An async function in a block never repeats another name (Annex B.3.3.4 covers plain + // function declarations only). + let plain = !f.is_async; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -350,7 +401,7 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + Some(_) => self.declare_lexical(&name, plain), None => Ok(()), } } @@ -457,7 +508,7 @@ impl<'s> Parser<'s> { /// A source element: a function declaration or a statement. fn parse_statement_item(&mut self) -> Result { - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.parse_function_declaration(); self.leave(); @@ -509,6 +560,9 @@ impl<'s> Parser<'s> { } self.parse_function_declaration() } + TokenKind::Ident(_) if self.at_async_function() => { + Err(self.error_at_token(&self.tok, "an async function declaration cannot stand here; put it in a block")) + } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), _ => self.plain_statement(start), } @@ -959,9 +1013,11 @@ impl<'s> Parser<'s> { // ---- functions ---- fn parse_function_declaration(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, is_async)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -977,15 +1033,30 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `is_async`, an async function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + is_async: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with `await` as the function has it, then the code around + // them goes on as it was. + // An `await` inside the function does not count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = false; + self.ctx.async_params = is_async; + let result = self.function_rest(kind, name, start, is_async); + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, is_async: bool) -> Result { self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1025,7 +1096,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1034,13 +1105,18 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let span = self.span_from(start); + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, is_async, span }; + // An async declaration or expression takes FormalParameters as a plain function does + // (ECMA-262 2017 section 14.6): repeated simple names are an error only in strict code. + // Arrow functions and async methods reject every repeat. self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } - /// An arrow function's body and the function, from `=>`, with its parameters read. - fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool) -> Result { + /// An arrow function's body and the function, from `=>`, with its parameters read; with + /// `is_async`, an async arrow function's. + fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool, is_async: bool) -> Result { if self.tok.newline_before { return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'")); } @@ -1048,7 +1124,7 @@ impl<'s> Parser<'s> { self.enter()?; let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let block = self.at(Punct::LBrace); @@ -1066,7 +1142,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, is_async, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1081,6 +1158,13 @@ impl<'s> Parser<'s> { Some(Expr::Sequence(list)) => list.clone(), _ => vec![*inner], }; + self.arrow_items(items) + } + + /// The parameters the items of an arrow function's head give: names, names with `= default`, + /// and a last `...name`. + fn arrow_items(&self, items: Vec) -> Result { + let invalid = |at: ExprId| self.error_at_offset(self.ast.expr_span(at).start, "invalid arrow function parameters"); let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None); let name_of = |id: ExprId| match self.ast.expr(id) { Some(Expr::Ident(n)) => Some(Name { name: n.clone(), span: self.ast.expr_span(id) }), @@ -1181,7 +1265,9 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; + // `async` followed on its line by a name starts an async arrow function. + let async_name = self.at_async() && self.peek().is_some_and(|t| matches!(t.kind, TokenKind::Ident(_)) && !t.newline_before); + let mut expr = if async_name { self.parse_async_name_arrow(no_in)? } else { self.parse_conditional(no_in)? }; if self.es2015 && self.at(Punct::Arrow) { expr = self.arrow_from(expr, no_in)?; } @@ -1203,12 +1289,39 @@ impl<'s> Parser<'s> { /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); - let params = match self.ast.expr(expr) { - Some(Expr::Ident(name)) => (vec![Name { name: name.clone(), span: start }], vec![None], None), - Some(Expr::Paren(_)) => self.arrow_params(expr)?, + let head = self.heads.get(&expr).copied(); + let (params, is_async) = match self.ast.expr(expr) { + Some(Expr::Ident(name)) => ((vec![Name { name: name.clone(), span: start }], vec![None], None), false), + Some(Expr::Paren(_)) => (self.arrow_params(expr)?, false), + // `async (…) =>` was read as a call to `async` (ECMA-262 2017 section 14.7). + Some(Expr::Call { args, .. }) if head.is_some() => { + if head.is_some_and(|h| h.line_break) { + return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function")); + } + (self.arrow_items(args.clone())?, true) + } _ => return Err(self.unexpected()), }; - self.parse_arrow(start, params, no_in) + // `await` cannot be an arrow function's parameter, or stand in one's default value, + // where it is an operator or in an async arrow function's head. + if head.is_some_and(|h| h.awaits) && (is_async || self.ctx.in_async) { + return Err(self.error_at_offset(start.start, "'await' cannot stand in an arrow function's parameters here")); + } + self.parse_arrow(start, params, no_in, is_async) + } + + /// `async name => …` from `async` (ECMA-262 2017 section 14.7): the one parameter is read as + /// an async function's is. + fn parse_async_name_arrow(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + let async_params = std::mem::replace(&mut self.ctx.async_params, true); + let param = self.binding_identifier(); + self.ctx.async_params = async_params; + let param = param?; + if !self.at(Punct::Arrow) { + return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok)))); + } + self.parse_arrow(start, (vec![param], vec![None], None), no_in, true) } /// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code @@ -1278,7 +1391,17 @@ impl<'s> Parser<'s> { /// Prefix operators, read with a loop and applied innermost first. fn parse_unary(&mut self) -> Result { let mut prefixes = Vec::new(); - while let Some(prefix) = prefix_op(&self.tok) { + loop { + // In an async function's body, `await` is a prefix operator (ECMA-262 2017 section 14.6). + let prefix = if self.ctx.in_async && self.tok.ident() == Some("await") { + if self.tok.escaped { + return Err(self.error_at_token(&self.tok, "keyword 'await' must not contain escaped characters")); + } + Prefix::Await + } else { + let Some(prefix) = prefix_op(&self.tok) else { break }; + prefix + }; prefixes.push((prefix, self.tok.span)); self.bump()?; } @@ -1296,6 +1419,10 @@ impl<'s> Parser<'s> { } self.ast.push_expr(Expr::Unary { op, arg: expr }, span) } + Prefix::Await => { + self.awaits = self.awaits.saturating_add(1); + self.ast.push_expr(Expr::Await(expr), span) + } }; } Ok(expr) @@ -1351,12 +1478,18 @@ impl<'s> Parser<'s> { expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span); } TokenKind::Punct(Punct::LParen) => { + let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); + let line_break = self.tok.newline_before; + let awaits = self.awaits; let args = self.parse_arguments()?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), None => self.ast.push_expr(Expr::Call { callee: expr, args }, span), }; + if async_head && self.at(Punct::Arrow) { + self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits }); + } } _ => break, } @@ -1409,9 +1542,19 @@ impl<'s> Parser<'s> { TokenKind::Keyword(Keyword::True) => Expr::Bool(true), TokenKind::Keyword(Keyword::False) => Expr::Bool(false), TokenKind::Keyword(Keyword::Function) => return self.parse_function_expression(), + TokenKind::Ident(_) if self.at_async_function() => return self.parse_function_expression(), TokenKind::Ident(name) => { let name = name.clone(); self.check_identifier(&self.tok, &name)?; + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } + if self.at_async() { + let token = self.bump()?; + let id = self.ast.push_expr(Expr::Ident(name), token.span); + self.async_ident = Some(id); + return Ok(id); + } Expr::Ident(name) } TokenKind::Number(n) => { @@ -1463,6 +1606,7 @@ impl<'s> Parser<'s> { /// function, which may also be `()` or end with `...name`; those two must come before `=>`. fn parse_paren_or_arrow_head(&mut self) -> Result { let start = self.expect(Punct::LParen)?.span; + let awaits = self.awaits; let mut items = Vec::new(); let mut head_only = self.at(Punct::RParen); while !self.at(Punct::RParen) { @@ -1493,7 +1637,11 @@ impl<'s> Parser<'s> { self.ast.push_expr(Expr::Sequence(items), span) } }; - Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start))) + let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start)); + if self.at(Punct::Arrow) { + self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits }); + } + Ok(paren) } /// A template literal from its first piece (the current token): its pieces and substitutions. @@ -1522,9 +1670,20 @@ impl<'s> Parser<'s> { } fn parse_function_expression(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; + // A function expression's name is read as its own body reads names (ECMA-262 2017 + // section 14.6): `await` is a name for an ordinary one, and not for an async one. + // Nor does the name count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = is_async; + self.ctx.async_params = false; + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; + let id = self.parse_function_rest(FunctionKind::Expression, name?, start, is_async)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1575,13 +1734,30 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } let key = PropertyKey::Ident(word.ident().unwrap_or_default().to_string()); return self.property_value(key, start); } + // `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, whose value is an + // async function that does not bind its own name. + if self.at_async() && self.peek().is_some_and(|t| !t.newline_before && property_key(&t).is_some()) { + self.bump()?; + let (key, _) = self.parse_property_key()?; + let function = self.parse_function_rest(FunctionKind::Expression, None, start, true)?; + // A method's parameters have distinct names (UniqueFormalParameters). + let mut seen = HashSet::new(); + for p in self.ast.function(function).into_iter().flat_map(|f| f.params.iter().chain(&f.rest)) { + if !seen.insert(p.name.as_str()) { + return Err(self.error_at_offset(p.span.start, format!("duplicate parameter name '{}'", p.name))); + } + } + let span = self.span_from(start); + let value = self.ast.push_expr(Expr::Function(function), span); + return Ok(Property { key, value: PropertyValue::Init(value), span }); + } let (key, _) = self.parse_property_key()?; self.property_value(key, start) } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ce8e37df32..166b32cea0 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -240,6 +240,14 @@ impl Realm { self.interp.set_es2015(es2015); } + /// Sets [`Options::es2017`] for the next runs, and for the code they evaluate; on, it also + /// sets [`Options::es2015`]. Async functions an earlier run made keep running when it is + /// turned off. Call [`Realm::add_es2015`] too in a realm made without either option, since + /// an async function needs `Promise`. + pub fn set_es2017(&mut self, es2017: bool) { + self.interp.set_es2017(es2017); + } + /// Gives a realm made without [`Options::es2015`] the built-ins that option adds (`Promise`), /// for its next runs; a realm that has them already is left as it is. It does not take them /// away again. Call it between runs. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 62aa806316..66a5b159d7 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -863,12 +863,11 @@ fn promise_builtins_run() { handle.join().unwrap(); } -/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global -/// `print` that collects its output; an `async` test passes when it prints -/// `Test262:AsyncTestComplete`. -fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { - let options = Options { es2015: true, ..Options::default() }; - let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); +/// Runs one test that may be asynchronous in a new realm made with `options` and a global `print` +/// that collects its output; an `async` test without a runtime negative passes when it prints +/// `Test262:AsyncTestComplete`, and one with a runtime negative must throw that error. +fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); let out = printed.clone(); realm.define_function("print", move |args| { @@ -882,7 +881,7 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool Ok(JsValue::Undefined) }); let result = realm.run(script); - if asynchronous && result.is_ok() { + if asynchronous && negative_type.is_none() && result.is_ok() { let printed = printed.borrow(); return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { Ok(()) @@ -951,7 +950,8 @@ fn run_promise(dir: &Path) { 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_promise_one(&script, negative_type.as_deref(), asynchronous)) { + let es2015 = Options { es2015: true, ..Options::default() }; + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, &es2015)) { Ok(Ok(())) => counts.passed += 1, Ok(Err(why)) => { counts.failed += 1; @@ -988,6 +988,124 @@ fn run_promise(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display()); } +/// The folders under `test/language/` that hold tests of async functions and `await`. +const ASYNC_FOLDERS: &[&str] = &["expressions/async-function", "statements/async-function", "expressions/await", "expressions/async-arrow-function"]; + +/// The feature tags an async-function test may carry and still run: [`ES2015_FEATURES`], +/// `async-functions` and `Promise`. +const ASYNC_FEATURES: &[&str] = &["async-functions", "Promise"]; + +#[test] +fn async_functions_run() { + let Some(dir) = suite_dir() else { + println!("test262 async functions: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_async_functions(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests in [`ASYNC_FOLDERS`] whose feature tags are all in [`ES2015_FEATURES`] or +/// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative +/// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests +/// included, skipping module tests and those that need a missing built-in. Prints the counts of +/// both and writes the failures with [`Options::es2017`] to `async-function-failures.txt`. +fn run_async_functions(dir: &Path) { + 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 done = harness("doneprintHandle.js"); + let missing = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let es2015 = Options { es2015: true, ..Options::default() }; + let es2017 = Options { es2015: true, es2017: true, ..Options::default() }; + let editions = [es2015, es2017.clone()]; + let mut counts = [Es2015Counts::default(), Es2015Counts::default()]; + let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize); + for folder in ASYNC_FOLDERS { + let root = or_fail(inside(dir, &format!("test/language/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + for path in or_fail(test_files(&root)) { + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !ES2015_FEATURES.contains(&f.as_str()) && !ASYNC_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if has("module") || meta.negative_phase.as_deref() == Some("resolution") { + skipped += 1; + continue; + } + let asynchronous = has("async"); + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &es2017) { + skipped += 1; + continue; + } + selected += 1; + for (options, counts) in editions.iter().zip(counts.iter_mut()) { + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let outcome = if expect_error { + let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; + if parse(&text, options).is_err() { + counts.parse_passed += 1; + continue; + } + counts.parse_failed += 1; + "parsed; a SyntaxError was expected".to_string() + } else { + 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_promise_one(&script, negative_type.as_deref(), asynchronous, options)) { + Ok(Ok(())) => { + counts.run_passed += 1; + continue; + } + Ok(Err(why)) => { + counts.run_failed += 1; + why + } + Err(_) => { + counts.run_failed += 1; + counts.panicked += 1; + "PANIC".to_string() + } + } + }; + counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n")); + } + } + } + } + assert!(selected > 0, "no async-function tests under {}", dir.display()); + let [before, after] = counts; + let report = dir.join("async-function-failures.txt"); + if let Err(e) = std::fs::write(&report, &after.failures) { + println!("could not write {}: {e}", report.display()); + } + let line = |c: &Es2015Counts| { + format!( + "negative parse runs {} passed, {} failed; other runs {} passed, {} failed ({} panicked)", + c.parse_passed, c.parse_failed, c.run_passed, c.run_failed, c.panicked + ) + }; + println!( + "test262 async functions: {selected} tests. With Options::es2015 alone: {}. With Options::es2017: {}. Skipped {skipped} module \ + or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}", + line(&before), + line(&after), + report.display() + ); + assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); diff --git a/docs/mcp.md b/docs/mcp.md index a0108999dc..2c49b01d83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,6 +2675,18 @@ own rules: all of them, and the Script Console shows an error line for each, as in `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. +A `.js` script also reads async functions and `await` as ECMA-262 2017 section 25.5 defines them +(https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, +async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` +resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function +goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` +work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is +reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. Outside an async +function `await` is an ordinary name, and in a `.jsx` file or a `source` string `async` and `await` are ordinary +names and an async function is a syntax error. These are VectorCraft's own rules: each time a function resumes +counts as a job and takes 1 unit of fuel, and a function still waiting when no job is left stays suspended, and the +run ends. + 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 https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ea01b22966..65cabd7f70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1084,6 +1084,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `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`. - 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. Until the language has iterators, `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and the statics always make plain `Promise` objects (VectorCraft's own rules). `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: 402 of 538 runs pass, where none ran before. The 136 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and a `name` on built-in functions. `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`). + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. `await` is an identifier outside async functions, and `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file; `.jsx` scripts and `source` strings do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - 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`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From a8174f2ae5cfd1dbe30f7a8867fa3922f6ac59da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:33:43 -0800 Subject: [PATCH 2/8] JavaScript: spreading a string counts the strings it makes for its characters Spreading a string makes a new one- or two-unit string for each code point, but the spread held only the bytes of each element's property, so a long string could make the host build every character string past the heap limit in one instruction. Each element now holds the bytes of its string as well, and the strings stay in the heap estimate once the array holds them. --- crates/js/src/es2015_tests.rs | 40 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 12 ++++++++--- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index d717ba2090..f7b704b210 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -513,6 +513,46 @@ fn spreading_a_rope_counts_its_flattened_length_first() { assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel"); } +#[test] +fn spreading_a_string_counts_the_string_it_makes_for_each_character() { + // Each of the 16,384 elements is a property and a one-character string of its own. The + // smaller heap has room for the properties alone but not for the strings as well, so the + // spread stops with the heap limit after about 83% of the characters, before the fuel for + // 90% of them runs out. The larger heap holds the array, its keys and the strings. + const N: usize = 16_384; + let property = crate::heap::PROP_BYTES; + let string = crate::heap::string_bytes(1); + let setup = "var s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s[0]; 0"; + let cases = [(property + string / 2, N * 9 / 10, Err(LimitKind::Heap)), (2 * (property + string) + 8, N * 2, Ok(N as f64))]; + for (per_element, fuel, expected) in cases { + let mut r = es(); + assert_eq!(r.run(setup), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let heap_bytes = r.interp().heap.bytes + N * per_element; + r.set_limits(Limits { heap_bytes, fuel: fuel as u64, ..Limits::default() }); + match (r.run("var a = [...s]; a.length"), expected) { + (Ok(JsValue::Number(n)), Ok(m)) if n == m => {} + (Err(e), Err(kind)) if e.kind == RunErrorKind::Limit(kind) => {} + (result, expected) => panic!("{per_element} bytes for each element: {result:?}, expected {expected:?}"), + } + } +} + +#[test] +fn the_strings_a_string_spread_makes_stay_counted_while_the_array_holds_them() { + const N: u32 = 4096; + let mut r = es(); + assert_eq!(r.run("var s = 'x'; for (var i = 0; i < 12; i++) s = s + s; s[0]; 0"), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let before = r.interp().heap.bytes; + assert_eq!(r.run("var a = [...s]; a.length"), Ok(JsValue::Number(f64::from(N)))); + // Takes the bytes the spread held while it ran off the estimate. + r.interp().reserve_heap(0).unwrap(); + let element = |i: u32| crate::heap::PROP_BYTES + crate::heap::string_bytes(i.to_string().len()) + crate::heap::string_bytes(1); + let least = before + (0..N).map(element).sum::(); + assert!(r.interp().heap.bytes >= least, "{} < {least}", r.interp().heap.bytes); +} + #[test] fn a_rest_parameter_checks_the_heap_before_its_array_is_made() { // The 20,000 arguments fit in the room left over, and the rest array of them does not, so diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0b75dab588..286302d021 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2404,8 +2404,9 @@ impl Interp { /// index (holes read as `undefined`), with its length read again before each one as its /// iterator reads it, a string's or a `String` object's characters by code point, and an /// object with a `length` by index. Any other value is a `TypeError`. Each element takes a - /// unit of fuel, and a concatenated string's flattened copy is counted against the heap before - /// it is made. + /// unit of fuel, a concatenated string's flattened copy is counted against the heap before + /// it is made, and so is each string a string's spread makes for its characters, while the + /// spread runs and after the array holds it. fn op_array_spread(&mut self) -> JsResult<()> { let v = self.peek(0)?; let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") }; @@ -2417,6 +2418,8 @@ impl Interp { }, _ => None, }; + // The bytes of the strings a string's spread makes, which the array keeps once it holds them. + let mut made = 0usize; let items: Vec = match boxed.as_ref().unwrap_or(&v) { Value::String(s) => { let units = crate::string_builtins::flat_charged(self, s)?; @@ -2425,9 +2428,11 @@ impl Interp { let mut i = 0; while let Some(&u) = units.get(i) { self.use_fuel()?; - held.add(self, PROP_BYTES)?; let pair = (0xD800..0xDC00).contains(&u) && units.get(i + 1).is_some_and(|n| (0xDC00..0xE000).contains(n)); let len = if pair { 2 } else { 1 }; + // Each element is a new string of its own as well as a property. + held.add(self, PROP_BYTES + string_bytes(len))?; + made = made.saturating_add(string_bytes(len)); out.push(Value::String(Str::from_units(units.get(i..i + len).unwrap_or_default().to_vec()))); i += len; } @@ -2490,6 +2495,7 @@ impl Interp { for (i, item) in (start..end).zip(items) { self.define(a, index_key(i), Prop::Data { value: item, flags: OPEN })?; } + self.heap.bytes = self.heap.bytes.saturating_add(made); self.pop().map(drop) } From b900ea2308034ec6ffe9a52613532fabd0026213 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:56:10 -0800 Subject: [PATCH 3/8] JavaScript: a block function skips its variable when a let has the name - A block function in script or eval code no longer stops the run with "redeclaration of" when a `let`, a `const` or a block function between the code and its variable environment has its name, or when the global object cannot take the variable (Annex B.3.3.2 and B.3.3.3). Its block still has the function, and a `var` of the name is still a SyntaxError. - A script stopped by the heap limit or the frame limit declares none of its `let` and `const` names, so a later script can declare them. The frame limit is checked, and the heap reserved for the names, before anything is declared. - An arrow function in an async arrow function's parameters reads `await` as an identifier, as its own body does. - With E4X, `async::name` is a qualified name. - `AsyncFunction` inherits from the built-in `Function` even after a script replaced `Function.prototype.constructor`. - The test262 reports list the older edition's panics, an async test passes only when one `print` call gives exactly the completion line, and the promise collection test checks that all 200 rejections arrive. --- crates/js/src/async_tests.rs | 20 +++++ crates/js/src/builtins.rs | 1 + crates/js/src/builtins/async_function.rs | 17 ++--- crates/js/src/bytecode.rs | 5 ++ crates/js/src/compiler.rs | 17 ++++- crates/js/src/es2015_tests.rs | 54 ++++++++++++++ crates/js/src/heap.rs | 3 +- crates/js/src/interp.rs | 95 +++++++++++++++++++++--- crates/js/src/interp/async_function.rs | 1 + crates/js/src/interp_tests.rs | 1 + crates/js/src/parser.rs | 6 +- crates/js/src/promise_tests.rs | 3 +- crates/js/tests/test262.rs | 48 +++++++----- 13 files changed, 223 insertions(+), 48 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index a473fd57da..0d78c4fd3c 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -84,6 +84,23 @@ fn async_functions_are_not_constructors_and_have_no_prototype() { assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5"); } +#[test] +fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_its_constructor() { + let mut r = Realm::new(); + assert_eq!(r.run("Function.prototype.constructor = {}; 0"), Ok(JsValue::Number(0.0))); + r.add_es2015(); + r.set_es2017(true); + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor; Object.getPrototypeOf(AF) === Function && typeof AF.call"; + assert_eq!(r.run(src), Ok(JsValue::String("function".into()))); +} + +#[test] +fn with_e4x_async_before_a_double_colon_is_a_qualified_name() { + let options = Options { es2017: true, e4x: true, ..Options::default() }; + assert!(parse("async::b", &options).is_ok()); + assert!(parse("var x = ; x.async::b", &options).is_ok()); +} + #[test] fn await_is_an_identifier_outside_async_functions() { let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\ @@ -98,6 +115,9 @@ fn await_is_an_identifier_outside_async_functions() { async function await() { return 1; }\n\ log.push(typeof g, typeof h, typeof await);"; assert_eq!(log(nested), "function function function"); + // An arrow function in an async arrow function's parameters reads `await` as its own body does. + let arrow = "var await = 7; var f = async (cb = () => await) => cb(); f().then(function (v) { log.push(v); });"; + assert_eq!(log(arrow), "7"); let mut r = realm(); syntax_error(&mut r, "async function f() { var await; }"); syntax_error(&mut r, "async function f(await) {}"); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 09cb089e5b..f1f8c0a547 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -123,6 +123,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, object_proto, "propertyIsEnumerable", property_is_enumerable, 1)?; let function = native(interp, "Function", function_ctor, 1, NativeKind::Plain, true)?; + interp.intrinsics.function_ctor = function; constructor(interp, "Function", function, function_proto)?; let call = native(interp, "call", unreachable_native, 1, NativeKind::Call, false)?; data(interp, function_proto, "call", Value::Object(call), HIDDEN)?; diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs index 43eea77b2a..4e3e65a906 100644 --- a/crates/js/src/builtins/async_function.rs +++ b/crates/js/src/builtins/async_function.rs @@ -4,7 +4,7 @@ //! reaches through it. `AsyncFunction` is not a global. use super::{data, dynamic_function, native}; -use crate::heap::{CONFIGURABLE, Class, NativeKind, ObjId, Object}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, Object}; use crate::interp::{Interp, JsResult}; use crate::value::Value; @@ -16,10 +16,11 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { interp.promises.async_function_proto = Some(proto); let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?; interp.promises.async_function_ctor = Some(ctor); - // `Function` is the constructor's prototype (section 25.5.2). - let function_ctor = constructor_of(interp, function_proto); + // The built-in `Function` is the constructor's prototype (section 25.5.2), even after a + // script has replaced `Function.prototype.constructor`. + let function_ctor = interp.intrinsics.function_ctor; if let Some(o) = interp.heap.object_mut(ctor) { - o.proto = function_ctor.or(o.proto); + o.proto = Some(function_ctor); } data(interp, ctor, "prototype", Value::Object(proto), 0)?; // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary @@ -27,14 +28,6 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) } -/// The `constructor` property `proto` has from the built-ins, when it is an object. -fn constructor_of(interp: &Interp, proto: ObjId) -> Option { - match interp.get_own_property(proto, &crate::heap::key("constructor")) { - Ok(Some(crate::heap::Prop::Data { value: Value::Object(o), .. })) => Some(o), - _ => None, - } -} - /// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { dynamic_function(interp, args, true) diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 723ad84b40..5dba6c540f 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -280,6 +280,11 @@ pub(crate) struct Code { pub(crate) vars: Vec, /// Function declarations to instantiate on entry: their names and indices in `functions`. pub(crate) fun_decls: Vec<(Key, u32)>, + /// In script and eval code, the variables of block functions (Annex B.3.3.2 and B.3.3.3) that + /// the code does not declare otherwise: each is declared, and its function assigned to it, only + /// when no `let`, `const` or block function between the code and its variable environment has + /// the name and the variable can be declared. + pub(crate) annex_vars: Vec, /// The body refers to `arguments` or calls `eval`. pub(crate) uses_arguments: bool, pub(crate) source: Rc, diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 3690ef3e28..aa0feff65f 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -106,6 +106,9 @@ struct FnCompiler<'a> { struct Hoisted { vars: Vec, fun_decls: Vec<(Key, u32)>, + /// The names of block functions (Annex B.3.3) that are neither a `var` nor a function at the + /// top of the body. + annex_vars: Vec, } fn key_of(name: &str) -> Key { @@ -244,7 +247,8 @@ impl<'a> FnCompiler<'a> { /// hoisted; one in a block is instantiated when the block is entered, and outside strict mode /// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with /// a `let` or a `const` of the body or of a block or loop around the declaration, or with a - /// function of a block around the one that holds it. + /// function of a block around the one that holds it. Such a name that the body does not also + /// declare with `var` or as a function at its top goes in [`Hoisted::annex_vars`]. fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult { let mut out = Hoisted::default(); let mut seen = HashSet::new(); @@ -259,6 +263,7 @@ impl<'a> FnCompiler<'a> { } }; let mut annex: Vec<(Key, usize, StmtId)> = Vec::new(); + let mut annex_seen = HashSet::new(); while let Some((id, nested, scope)) = work.pop() { let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") }; let inner = self.es2015; @@ -366,7 +371,9 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - add_var(&mut out, k); + if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + out.annex_vars.push(k); + } } } Ok(out) @@ -1800,6 +1807,7 @@ impl<'a> FnCompiler<'a> { params: meta.params, vars: hoisted.vars, fun_decls: hoisted.fun_decls, + annex_vars: hoisted.annex_vars, uses_arguments: self.uses_arguments, source: self.source.clone(), span: meta.span, @@ -1848,7 +1856,10 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let params: Vec = f.params.iter().map(|p| key_of(&p.name)).collect(); let rest = f.rest.as_ref().map(|r| key_of(&r.name)); let all_params: Vec = params.iter().chain(&rest).cloned().collect(); - let hoisted = c.hoist(&f.body, &all_params)?; + let mut hoisted = c.hoist(&f.body, &all_params)?; + // A function's block functions always have their variable (Annex B.3.3.1). + let annex = std::mem::take(&mut hoisted.annex_vars); + hoisted.vars.extend(annex); let top_scope = c.list_scope(&f.body, false)?; let param_init = !f.simple_params(); if param_init { diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index ec09876731..a8a77b723b 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -138,6 +138,28 @@ fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() { truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1"); } +#[test] +fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { + // A block function of a script or of eval code gets no variable when a `let`, a `const` or a + // block function out to the variable environment has its name, or when the global object + // cannot take it (Annex B.3.3.2 and B.3.3.3); its block still has it, and a `var` of the name + // is still a SyntaxError. + let mut realm = es(); + assert_eq!(realm.run("let f = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var inner; { function f() { return 2; } inner = f(); } inner + f"), Ok(JsValue::Number(3.0))); + assert!(is_thrown(&realm.run("{ function f() {} } var f;"), "SyntaxError")); + assert_eq!(realm.run("(0, eval)('{ function f() { return 4; } }'); f"), Ok(JsValue::Number(1.0))); + truth("function t() { let h = 1; { eval('{ function h() { return 2; } }'); } return h; } t() === 1"); + truth("function t() { let h = 1; eval('{ function h() {} }'); return h; } t() === 1"); + // A `catch` parameter does not stop the variable (Annex B.3.5). + truth("try { throw 1; } catch (c) { eval('{ function c() { return 5; } }'); } c() === 5"); + let mut realm = es(); + assert_eq!(realm.run("var out; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0))); + let kept = realm.run("{ function n() { return 6; } out = n(); } out + typeof n"); + assert_eq!(kept, Ok(JsValue::String("6undefined".into()))); + assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); @@ -286,6 +308,38 @@ fn a_global_var_that_cannot_be_declared_declares_nothing() { assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0))); } +#[test] +fn a_script_stopped_by_the_frame_limit_declares_no_let() { + let mut realm = Realm::with_options(es_options(), Limits { frames: 0, ..Limits::default() }); + let stopped = realm.run("let early = 1; const fixed = 2;"); + assert!(matches!(&stopped, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Frames)), "{stopped:?}"); + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0))); +} + +#[test] +fn a_script_stopped_by_the_heap_limit_declares_no_let() { + // The `let` and `const` names of a script go in before its functions are made; a heap too + // small for both stops the script before any name is declared. + let lets: String = (0..200).map(|i| format!("let a_long_lexical_name_{i} = {i}; ")).collect(); + let decls: String = (0..40).map(|i| format!("function f{i}() {{ return {i}; }} ")).collect(); + let src = format!("let early = 1; const fixed = 2; {lets}{decls}"); + let mut stopped = 0; + for spare in (40_000..200_000).step_by(97) { + let mut realm = es(); + let live = realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match realm.run(&src) { + Ok(_) => continue, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => stopped += 1, + Err(e) => panic!("{spare}: {e:?}"), + } + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)), "{spare}"); + } + assert!(stopped > 0); +} + #[test] fn eval_code_keeps_its_let_and_const_to_itself() { truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'"); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index e25bac7323..c59925c1bb 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -623,6 +623,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { + code.functions.len() + code.params.len() + code.vars.len() + + code.annex_vars.len() + 2 * code.fun_decls.len() + code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::() + code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::(); @@ -641,7 +642,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { strings.add(pattern); strings.add(flags); } - let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k)); + let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(&code.annex_vars).chain(code.fun_decls.iter().map(|(k, _)| k)); for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) { strings.add_key(k); } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index d7a0ef6481..b4fa731b76 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -92,6 +92,9 @@ impl ErrorType { pub(crate) struct Intrinsics { pub(crate) object_proto: ObjId, pub(crate) function_proto: ObjId, + /// The built-in `Function`, which a script can replace as the global or as the prototype's + /// `constructor`. + pub(crate) function_ctor: ObjId, pub(crate) array_proto: ObjId, pub(crate) string_proto: ObjId, pub(crate) number_proto: ObjId, @@ -115,6 +118,7 @@ impl Intrinsics { Self { object_proto: o, function_proto: o, + function_ctor: o, array_proto: o, string_proto: o, number_proto: o, @@ -149,6 +153,7 @@ impl Intrinsics { let mut v = vec![ self.object_proto, self.function_proto, + self.function_ctor, self.array_proto, self.string_proto, self.number_proto, @@ -187,6 +192,9 @@ pub(crate) struct Frame { /// The promise of the async function the frame runs: a return resolves it, an exception /// that leaves the frame rejects it, and the call's value is the promise. async_promise: Option, + /// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not + /// declared: [`Op::AnnexB`] leaves them alone. + annex_off: Vec, } /// Where the exception being thrown was raised: the code and the instruction. @@ -471,7 +479,13 @@ fn declaration_bytes(code: &Code) -> usize { let closure = code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f)); total.saturating_add(binding_bytes(name.len()) + closure) }); - code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) + code.vars.iter().chain(&code.annex_vars).fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) +} + +/// The bytes the `let` and `const` names at the top of a script add to the global scope. +fn global_lexical_bytes(code: &Code) -> usize { + let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets); + lets.iter().fold(0usize, |total, (name, _)| total.saturating_add(binding_bytes(name.len()))) } /// A call to a function written in JavaScript, ready to enter. @@ -2396,9 +2410,13 @@ impl Interp { Ok(()) } - /// Assigns a function declared in a block to the variable of the same name. + /// Assigns a function declared in a block to the variable of the same name, unless the + /// variable of script or eval code was not declared. fn op_annex_b(&mut self, n: u32) -> JsResult<()> { let name = self.name(n)?; + if self.frame()?.annex_off.contains(&name) { + return self.pop().map(drop); + } let v = self.peek(0)?; let var_env = self.frame()?.var_env; match self.heap.env(var_env) { @@ -2952,6 +2970,7 @@ impl Interp { completion: Value::Undefined, boundary, async_promise: None, + annex_off: Vec::new(), }); // An async function's call makes its promise first thing (section 25.5.5.2); the frame // keeps what the function holds reachable while it is made. @@ -3278,14 +3297,16 @@ impl Interp { (caller_env, caller_var_env) }; self.stack.truncate(start); - let env = self.instantiate_pending(&code, env, var_env, true)?; - self.push_code_frame(code, env, var_env, this, false) + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, true)?; + self.push_code_frame(code, env, var_env, this, false)?; + self.frame_mut()?.annex_off = annex_off; + Ok(()) } /// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the /// code counted against the heap, until its frame holds them: the scopes and functions it /// makes can collect. - fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { let mark = self.temp_envs.len(); self.temp_envs.push(env); self.temp_codes.push(code.clone()); @@ -3311,9 +3332,15 @@ impl Interp { r } - /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. + /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. The + /// frame limit and the heap, with a script's `let` and `const` names, are checked before + /// anything is declared. pub(crate) fn enter_global(&mut self, code: Rc, is_eval: bool) -> JsResult<()> { - self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let lexical = if is_eval { 0 } else { global_lexical_bytes(&code) }; + self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(lexical))?; let (scope, global) = (self.global_scope(), self.global); let (env, var_env) = if code.strict && is_eval { let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); @@ -3321,8 +3348,10 @@ impl Interp { } else { (scope, self.global_env) }; - let env = self.instantiate_pending(&code, env, var_env, is_eval)?; - self.push_code_frame(code, env, var_env, Value::Object(global), true) + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, is_eval)?; + self.push_code_frame(code, env, var_env, Value::Object(global), true)?; + self.frame_mut()?.annex_off = annex_off; + Ok(()) } /// The environment global code runs in: the one that holds the scripts' `let` and `const` @@ -3437,6 +3466,7 @@ impl Interp { completion: Value::Undefined, boundary, async_promise: None, + annex_off: Vec::new(), }); Ok(()) } @@ -3446,8 +3476,9 @@ impl Interp { /// /// Gives the environment the code runs in: `env`, or with [`Options::es2015`] eval code's own /// environment of its `let` and `const` names. A script's `let` and `const` names go in the - /// global scope ([`Self::declare_global_lexical`]). - fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + /// global scope ([`Self::declare_global_lexical`]). Also gives the names of + /// [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not declare. + fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { let configurable = if is_eval { CONFIGURABLE } else { 0 }; if is_eval && !code.strict && self.options.es2015 { self.check_eval_vars(code, env, var_env)?; @@ -3492,7 +3523,47 @@ impl Interp { self.global_vars.insert(v.clone()); } } - Ok(lex) + let mut annex_off = Vec::new(); + for v in &code.annex_vars { + self.use_fuel()?; + if !self.annex_var_declarable(v, env, var_env)? { + annex_off.push(v.clone()); + continue; + } + self.declare(var_env, v, None, configurable)?; + if on_global { + self.global_vars.insert(v.clone()); + } + } + Ok((lex, annex_off)) + } + + /// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and + /// B.3.3.3, ): no + /// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch` + /// parameter does not count, and on the global object the name is its own property or the + /// object is extensible. Each environment passed takes a unit of fuel. + fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult { + let mut cur = Some(env).filter(|&e| e != var_env); + while let Some(e) = cur { + self.use_fuel()?; + cur = match self.heap.env(e) { + Some(Env::Decl { bindings, outer }) => { + if bindings.get(name).is_some_and(|b| b.lexical) { + return Ok(false); + } + *outer + } + Some(Env::Obj { outer, .. }) => *outer, + None => return internal("environment out of range"), + } + .filter(|&o| o != var_env); + } + if var_env != self.global_env { + return Ok(true); + } + let global = self.global; + Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible) } /// A `var` or function that eval code outside strict mode code declares must not take the name diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs index 7121215b9d..9bb7c26cb8 100644 --- a/crates/js/src/interp/async_function.rs +++ b/crates/js/src/interp/async_function.rs @@ -147,6 +147,7 @@ impl Interp { completion: a.completion, boundary: true, async_promise: Some(a.promise), + annex_off: Vec::new(), }); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 4a281a7b2f..346c32983a 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -972,6 +972,7 @@ fn code(ops: Vec) -> Code { params: Vec::new(), vars: Vec::new(), fun_decls: Vec::new(), + annex_vars: Vec::new(), uses_arguments: false, source, span: (0, 0), diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 9478074e73..8a7cef804f 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -1130,6 +1130,8 @@ impl<'s> Parser<'s> { let outer_strict = self.ctx.strict; let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); + // An `await` in the body does not count for an async arrow function's head around it. + let awaits = self.awaits; self.push_scope(true, names); let block = self.at(Punct::LBrace); let body = if block { @@ -1138,6 +1140,7 @@ impl<'s> Parser<'s> { self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))]) }; self.pop_scope(); + self.awaits = awaits; let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict); self.ctx = outer; self.leave(); @@ -1553,7 +1556,8 @@ impl<'s> Parser<'s> { if name == "await" { self.awaits = self.awaits.saturating_add(1); } - if self.at_async() { + // With E4X, `async::name` is a qualified name. + if self.at_async() && !(self.e4x && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon))) { let token = self.bump()?; let id = self.ast.push_expr(Expr::Ident(name), token.span); self.async_ident = Some(id); diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 8e03f2a136..fc6d927c70 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -78,7 +78,7 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() { #[test] fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { - let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\ + let src = "var bad = 0, seen = 0; function check(e) { seen++; if (!(e instanceof TypeError)) bad++; }\n\ for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }"; let mut finished = 0; for spare in (40_000..240_000).step_by(641) { @@ -92,6 +92,7 @@ fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { } r.set_limits(Limits::default()); assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + assert_eq!(r.run("seen"), Ok(JsValue::Number(200.0)), "{spare}"); } assert!(finished > 0); } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 0fe3badb67..8cd87a33bb 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -30,7 +30,8 @@ //! //! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`, //! arrow functions, templates, default and rest parameters) without and with that option, and -//! prints both counts; its failures with the option go to `es2015-failures.txt`. +//! prints both counts; its failures with the option, and the runs without it that panicked, go to +//! `es2015-failures.txt`. //! //! 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 @@ -42,8 +43,8 @@ //! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`: //! those whose feature tags name only `Promise`, `Promise.allSettled` and //! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests -//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its -//! failures go to `promise-failures.txt`. +//! run with the suite's `doneprintHandle.js` and pass when they print the completion line and no +//! line that starts with the failure prefix. Its failures go to `promise-failures.txt`. //! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over @@ -695,13 +696,25 @@ struct Es2015Counts { failures: String, } +impl Es2015Counts { + /// The failures of the run with the option, then each run without it that panicked, marked + /// with `without`. + fn report(after: &Es2015Counts, before: &Es2015Counts, without: &str) -> String { + let mut report = after.failures.clone(); + for line in before.failures.lines().filter(|l| l.ends_with(": PANIC")) { + report.push_str(&format!("{line} ({without})\n")); + } + report + } +} + /// Runs the ES2015 subset: the tests under `test/language/` in [`ES2015_FOLDERS`] whose feature /// tags are all in [`ES2015_FEATURES`], and the tests elsewhere under `test/language/` with feature /// tags that are all in it. Negative parse tests must give a `SyntaxError`; the other tests run in a /// new realm after the harness, as [`run_tests`] runs them, skipping module and asynchronous tests /// and those that need a missing built-in. Each test is read twice, without and with -/// [`Options::es2015`], and the counts of both are printed; the failures with it go to -/// `es2015-failures.txt`. +/// [`Options::es2015`], and the counts of both are printed; the failures with it, and the runs +/// without it that panicked, go to `es2015-failures.txt`. fn run_es2015(dir: &Path) { let language = or_fail(inside(dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); @@ -779,7 +792,7 @@ fn run_es2015(dir: &Path) { assert!(selected > 0, "no ES2015 tests under {}", language.display()); let [before, after] = counts; let report = dir.join("es2015-failures.txt"); - if let Err(e) = std::fs::write(&report, &after.failures) { + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "without Options::es2015")) { println!("could not write {}: {e}", report.display()); } let line = |c: &Es2015Counts| { @@ -869,11 +882,12 @@ fn promise_builtins_run() { } /// Runs one test that may be asynchronous in a new realm made with `options` and a global `print` -/// that collects its output; an `async` test without a runtime negative passes when it prints -/// `Test262:AsyncTestComplete`, and one with a runtime negative must throw that error. +/// that collects its output; an `async` test without a runtime negative passes when one `print` +/// call gives exactly `Test262:AsyncTestComplete` and none gives a value that starts with +/// `Test262:AsyncTestFailure:`, and one with a runtime negative must throw that error. fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> { let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); - let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let out = printed.clone(); realm.define_function("print", move |args| { let line = match args.first() { @@ -881,18 +895,15 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool Some(other) => format!("{other:?}"), None => String::new(), }; - out.borrow_mut().push_str(&line); - out.borrow_mut().push('\n'); + out.borrow_mut().push(line); Ok(JsValue::Undefined) }); let result = realm.run(script); if asynchronous && result.is_ok() && negative_type.is_none() { let printed = printed.borrow(); - return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { - Ok(()) - } else { - Err(format!("printed {:?}", printed.trim())) - }; + let complete = printed.iter().any(|l| l == "Test262:AsyncTestComplete"); + let failed = printed.iter().any(|l| l.starts_with("Test262:AsyncTestFailure:")); + return if complete && !failed { Ok(()) } else { Err(format!("printed {:?}", printed.join("\n"))) }; } match (result, negative_type) { (Ok(_), None) => Ok(()), @@ -1014,7 +1025,8 @@ fn async_functions_run() { /// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative /// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests /// included, skipping module tests and those that need a missing built-in. Prints the counts of -/// both and writes the failures with [`Options::es2017`] to `async-function-failures.txt`. +/// both and writes the failures with [`Options::es2017`], and the runs with [`Options::es2015`] +/// alone that panicked, to `async-function-failures.txt`. fn run_async_functions(dir: &Path) { 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")); @@ -1092,7 +1104,7 @@ fn run_async_functions(dir: &Path) { assert!(selected > 0, "no async-function tests under {}", dir.display()); let [before, after] = counts; let report = dir.join("async-function-failures.txt"); - if let Err(e) = std::fs::write(&report, &after.failures) { + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "with Options::es2015 alone")) { println!("could not write {}: {e}", report.display()); } let line = |c: &Es2015Counts| { From 1f1b967a7c3bb04080f6eea9f6fe2dd86515186b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:01:22 -0800 Subject: [PATCH 4/8] JavaScript: Promise.all reads a String object by its characters `Promise.all`, `Promise.allSettled` and `Promise.race` read a `String` object as the string it holds, one input for each character, as they read a string. A character outside the Basic Multilingual Plane was two inputs before. --- crates/js/src/builtins/promise.rs | 9 ++++++++- crates/js/src/promise_tests.rs | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 03ece744a5..901125f565 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -1141,7 +1141,7 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe /// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to /// its length at each step, as an array iterator reads it, and another object up to the `length` -/// it had at the start. +/// it had at the start. A string, and a `String` object, gives its characters. enum Inputs { Indexed { object: ObjId, length: f64 }, CodePoints(Rc<[u16]>), @@ -1149,6 +1149,13 @@ enum Inputs { impl Inputs { fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { + // A `String` object iterates as the string it holds does (ECMA-262 2015 section 21.1.3.27). + if let Value::Object(o) = input + && let Some(Class::String(s)) = interp.heap.object(*o).map(|obj| &obj.class) + { + let s = s.clone(); + return Ok(Inputs::CodePoints(flat_charged(interp, &s)?)); + } match input { Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index fc6d927c70..6f3fb5008d 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -105,6 +105,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\ Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\ Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\ + Promise.all(new String('a\\uD83D\\uDE00')).then(function (v) { log.push('boxed ' + v.length + ' ' + v[1].length); });\n\ Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\ Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\ Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });"; @@ -117,6 +118,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { "rejected:r fulfilled:4", "race fast", "chars 2", + "boxed 2 2", "not a list true", "no length true", "bad length true", From c606701aef2a90d41fead42ad84452460e50321c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:04:25 -0800 Subject: [PATCH 5/8] JavaScript: a comma after a rest parameter is a SyntaxError in async arrows - `async (...xs,) => xs` is a SyntaxError, as `(...xs,) => xs` is. `async (x,) => x` still parses. - An arrow function's parameters may end with a comma: `(a, b,) => a + b` parses, and `(a,)` without `=>` is still a SyntaxError. - A `var` that an inherited property of the global object declared, without ECMAScript 2015 scoping, no longer stops a later `let` of its name once the realm turns the option on. - A tagged template's object reserves the heap for its index names and its `raw` property before it is made. - The test262 runner skips a test whose template literal runs a missing built-in as code, as it skips one whose string does. --- crates/js/src/async_tests.rs | 12 ++++++++++ crates/js/src/es2015_tests.rs | 42 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 17 +++++++++++--- crates/js/src/parser.rs | 37 ++++++++++++++++++++++++------ crates/js/tests/test262.rs | 11 ++++++++- 5 files changed, 108 insertions(+), 11 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 0d78c4fd3c..e16f8e2a35 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -69,6 +69,18 @@ fn arrows_expressions_and_methods_can_be_async() { assert_eq!(log(src), "4,3,function,kv"); } +#[test] +fn a_comma_may_follow_an_arrow_functions_last_parameter_but_not_a_rest_parameter() { + let src = "var f = async (x,) => x; var g = async (x, ...xs) => xs.length; var h = (a, b,) => a + b;\n\ + var async = function () { return arguments.length; }; log.push(async(...[1, 2],));\n\ + Promise.all([f(1), g(1, 2, 3), h(1, 2), h.length]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "2 1,2,3,2"); + let mut r = realm(); + for src in ["async (...xs,) => xs", "async (a, ...xs,) => xs", "(...xs,) => xs", "(a, ...xs,) => xs", "(a,);", "(a, b,);"] { + syntax_error(&mut r, src); + } +} + #[test] fn async_functions_are_not_constructors_and_have_no_prototype() { let src = "async function f() {}\n\ diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index f6a337d860..92516cc4b8 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -262,6 +262,17 @@ fn a_global_var_makes_its_own_property_over_an_inherited_one() { assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true))); } +#[test] +fn a_var_an_inherited_property_declared_does_not_stop_a_later_let() { + // Without the option, `var x` uses the inherited `x` and makes no own property, so a later + // run with the option may declare `x` with `let`. + let mut realm = Realm::new(); + assert_eq!(realm.run("Object.prototype.x = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var x; delete this.x"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("let x = 2; x"), Ok(JsValue::Number(2.0))); +} + #[test] fn a_global_function_that_cannot_be_declared_declares_nothing() { let mut realm = es(); @@ -752,6 +763,37 @@ fn spread_stops_at_the_heap_limit_before_the_next_step_runs() { } } +#[test] +fn a_template_object_stays_within_the_heap_limit() { + // The template object's two arrays, the index name of each string and the `raw` property are + // reserved before they are made, so the heap stays within each limit tried. + let setup = "function t(s) { return s.length; } 0"; + let run = format!("t`{}`", (0..10).map(|i| format!("p{i}${{{i}}}")).collect::()); + let mut measure = Realm::with_options(es_options(), Limits::default()); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + measure.interp().collect_garbage(); + let base = measure.interp().heap.bytes; + assert_eq!(measure.run(&run), Ok(JsValue::Number(11.0))); + let need = measure.interp().settled_heap_bytes() - base; + let mut stopped = 0; + for heap_bytes in (base..=base + need).step_by(4) { + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + if realm.run(setup).is_err() { + continue; + } + realm.interp().collect_garbage(); + let r = realm.run(&run); + stopped += usize::from(r.is_err()); + assert!( + matches!(&r, Ok(JsValue::Number(_))) || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), + "{heap_bytes}: {r:?}" + ); + let bytes = realm.interp().settled_heap_bytes(); + assert!(bytes <= heap_bytes, "{bytes} > {heap_bytes}"); + } + assert!(stopped > 0, "no limit stopped the run"); +} + #[test] fn spreading_other_values_is_a_type_error() { throws("[...1];", "TypeError"); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 7224b0c122..f6e21e0224 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2670,8 +2670,16 @@ impl Interp { return self.push(Value::Object(id)); } let Some(t) = code.templates.get(i as usize) else { return internal("template out of range") }; - let strings = t.cooked.len().saturating_add(t.raw.len()); - self.reserve_heap(OBJECT_BYTES.saturating_mul(2).saturating_add(strings.saturating_mul(PROP_BYTES)))?; + // Two arrays, a property and an index name for each string, and the `raw` property. + let names = |n: usize| index_keys_bytes(n).saturating_sub(n.saturating_mul(KEY_ENTRY_BYTES)); + let props = t.cooked.len().saturating_add(t.raw.len()).saturating_add(1); + let bytes = OBJECT_BYTES + .saturating_mul(2) + .saturating_add(props.saturating_mul(PROP_BYTES)) + .saturating_add(names(t.cooked.len())) + .saturating_add(names(t.raw.len())) + .saturating_add(string_bytes(3)); + self.reserve_heap(bytes)?; let raw = self.frozen_array(&t.raw)?; // The raw array stays reachable while the template object is made. self.push(Value::Object(raw))?; @@ -3620,7 +3628,10 @@ impl Interp { for v in &code.vars { self.use_fuel()?; self.declare(var_env, v, None, configurable)?; - if on_global { + // Without ECMA-262 2015's scoping, a property the global object inherits declares the + // variable and no own property is made. Only a name with an own property is kept; + // `delete` removes the name with that property. + if on_global && self.get_own_property(self.global, v)?.is_some() { self.global_vars.insert(v.clone()); } } diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index d4ed2e8c4a..4430636d2d 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -51,6 +51,8 @@ struct Head { line_break: bool, /// The parentheses hold an `await` expression or the identifier `await`. awaits: bool, + /// A comma follows the last item in the parentheses. + trailing_comma: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -1313,6 +1315,13 @@ impl<'s> Parser<'s> { if head.is_some_and(|h| h.line_break) { return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function")); } + // No comma may follow a rest parameter (ECMA-262 2017 section 14.1). + if let Some(&last) = args.last() + && head.is_some_and(|h| h.trailing_comma) + && matches!(self.ast.expr(last), Some(Expr::Spread(_))) + { + return Err(self.error_at_offset(self.ast.expr_span(last).start, "a rest parameter must be the last parameter")); + } (self.arrow_items(args.clone())?, true) } _ => return Err(self.unexpected()), @@ -1517,14 +1526,14 @@ impl<'s> Parser<'s> { let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); let line_break = self.tok.newline_before; let awaits = self.awaits; - let args = self.parse_arguments()?; + let (args, trailing_comma) = self.arguments()?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), None => self.ast.push_expr(Expr::Call { callee: expr, args }, span), }; if async_head && self.at(Punct::Arrow) { - self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits }); + self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma }); } } TokenKind::Punct(Punct::QuestionDot) => { @@ -1612,19 +1621,29 @@ impl<'s> Parser<'s> { } fn parse_arguments(&mut self) -> Result> { + Ok(self.arguments()?.0) + } + + /// An argument list, and whether a comma follows its last argument. + fn arguments(&mut self) -> Result<(Vec, bool)> { self.expect(Punct::LParen)?; let mut args = Vec::new(); + let mut trailing_comma = false; if !self.at(Punct::RParen) { loop { args.push(self.parse_element()?); // A comma may follow the last argument (ECMAScript 2017, section 12.3). - if !self.eat(Punct::Comma)? || self.at(Punct::RParen) { + if !self.eat(Punct::Comma)? { + break; + } + if self.at(Punct::RParen) { + trailing_comma = true; break; } } } self.expect(Punct::RParen)?; - Ok(args) + Ok((args, trailing_comma)) } fn parse_primary(&mut self) -> Result { @@ -1704,7 +1723,8 @@ impl<'s> Parser<'s> { } /// `( … )` with [`crate::Options::es2015`]: a parenthesized expression, or the head of an arrow - /// function, which may also be `()` or end with `...name`; those two must come before `=>`. + /// function, which may also be `()`, end with `...name` or end with a comma; those three must + /// come before `=>`. fn parse_paren_or_arrow_head(&mut self) -> Result { let start = self.expect(Punct::LParen)?.span; let awaits = self.awaits; @@ -1723,8 +1743,11 @@ impl<'s> Parser<'s> { if !self.eat(Punct::Comma)? { break; } + // A comma may follow the last parameter (ECMA-262 2017 section 14.2), but not the + // last item of a parenthesized expression. if self.at(Punct::RParen) { - return Err(self.unexpected()); + head_only = true; + break; } } self.expect(Punct::RParen)?; @@ -1740,7 +1763,7 @@ impl<'s> Parser<'s> { }; let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start)); if self.at(Punct::Arrow) { - self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits }); + self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits, trailing_comma: false }); } Ok(paren) } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fcfeb7bf25..fc90beb905 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -436,7 +436,7 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens)); lists.iter().flatten().any(|t| match &t.kind { TokenKind::Ident(name) => missing.contains(name.as_str()), - TokenKind::String(units) => { + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => { let text = String::from_utf16_lossy(units); missing.contains(text.as_str()) || (strings_are_code && text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word))) @@ -1155,6 +1155,15 @@ fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() { assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern)); } +#[test] +fn a_missing_name_in_a_template_that_can_run_as_code_skips() { + let missing: HashSet<&str> = ["Map"].into_iter().collect(); + let modern = Options { es2015: true, ..Options::default() }; + assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern)); + assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern)); + assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern)); +} + #[test] fn a_missing_name_in_code_skips() { assert!(skips(&["var m = new Map();"])); From f6a6cf35183118924bb9c391c522351571b3c479 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:25:22 -0800 Subject: [PATCH 6/8] Tests: a template key naming eval runs strings as code in the test262 runner runs_strings_as_code matched a string token naming eval, Function or constructor, but not a template, so this[`eval`](`new Map()`) did not skip when Map is missing. Templates now match the same names, as needs_missing_builtin_in already reads both forms. --- crates/js/tests/test262.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fc90beb905..77de4c13f6 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -446,12 +446,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: } /// The tokens can run a string as code: they name `eval`, `Function` or a `constructor` property, -/// as an identifier or as a string key (`this["eval"]`), called directly or through an alias. +/// as an identifier or as a string or template key (`this["eval"]`), called directly or through an alias. /// `Function.prototype` alone does not count. fn runs_strings_as_code(tokens: &[Token]) -> bool { const RUNNERS: [&str; 3] = ["eval", "Function", "constructor"]; tokens.iter().enumerate().any(|(i, t)| match &t.kind { - TokenKind::String(units) => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), TokenKind::Ident(name) if name == "eval" || name == "constructor" => true, TokenKind::Ident(name) if name == "Function" => { let prototype = tokens.get(i + 1).is_some_and(|d| d.is_punct(Punct::Dot)) @@ -1161,6 +1161,9 @@ fn a_missing_name_in_a_template_that_can_run_as_code_skips() { let modern = Options { es2015: true, ..Options::default() }; assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern)); assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern)); + // A template key names the runner, as a string key does. + assert!(needs_missing_builtin_in(&["this[`eval`](`new Map()`);"], &missing, &modern)); + assert!(needs_missing_builtin_in(&[r#"var F = this[`Function`]; F("return new Map()")();"#], &missing, &modern)); assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern)); } From c0b4413a5abe282625c5a0511327ac42ea53613a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:30:09 -0800 Subject: [PATCH 7/8] JS: fix async function review points - AsyncFunction.prototype has Symbol.toStringTag "AsyncFunction", configurable only. - await checks the room for the awaited promise's reaction or job and the suspended frame's bytes before it attaches the reaction, so a suspension stays within the heap limit. - An async function's return pops its frame before resolving its promise, so a then getter on the returned value runs without it. Returning the function's own promise rejects it at the return. - Block functions whose variable was not declared are kept in a hash set, so each block function's lookup takes constant time. - A shorthand await in an object pattern of an async arrow function's head is a syntax error, and the head accepts patterns with defaults such as async ({a = 1}) => a. async({a = 1}) without an arrow is still a syntax error. - docs: .jsx files and source strings run with module: true have Promise and the async syntax; await is an identifier only in script code. --- crates/js/src/async_tests.rs | 83 ++++++++++++++++++++++++ crates/js/src/builtins/async_function.rs | 10 ++- crates/js/src/builtins/promise.rs | 20 ++++++ crates/js/src/generator.rs | 4 +- crates/js/src/interp.rs | 47 ++++++++------ crates/js/src/interp/async_function.rs | 2 +- crates/js/src/parser.rs | 17 +++-- crates/js/src/parser/pattern.rs | 4 ++ docs/mcp.md | 18 ++--- docs/target-app-parity.md | 2 +- 10 files changed, 170 insertions(+), 37 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 6d2c4531ff..711f883633 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -184,6 +184,89 @@ fn a_run_that_ends_with_awaits_pending_ends_cleanly() { assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0)); } +#[test] +fn async_function_prototype_has_its_to_string_tag() { + let src = "var AFP = Object.getPrototypeOf(async function () {});\n\ + var d = Object.getOwnPropertyDescriptor(AFP, Symbol.toStringTag);\n\ + log.push(d.value, d.writable, d.enumerable, d.configurable, Object.prototype.toString.call(async function () {}));"; + assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]"); +} + +#[test] +fn an_await_stays_within_the_heap_limit() { + // The activation, its two reactions, the derived promise and the suspended frame's bytes all + // fit in the heap limit, or the run stops at the `await`. The frame waits with 40 operands on + // a promise that never settles, so its bytes stay charged after the run. A suspension that + // went past the limit would be stopped only later, at the end of the run, so the largest + // heap that still stops the run must stop it at the `await`. + let operands: String = (0..40).map(|i| format!("{i}, ")).collect(); + let setup = + format!("var gate = new Promise(function () {{}}); function g() {{ return 0; }} async function f() {{ return g({operands}await gate); }} 0"); + let setup = setup.as_str(); + let await_column = setup.find("await gate").map(|i| i + 1); + let run = "f(); 0"; + let mut measure = realm(); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + let base = measure.collect_garbage(); + assert_eq!(measure.run(run), Ok(JsValue::Number(0.0))); + let need = measure.interp().settled_heap_bytes().saturating_sub(base) + 1024; + let mut last_stop = None; + let mut over = Vec::new(); + for spare in (0..=need).step_by(4) { + let mut r = realm(); + assert_eq!(r.run(setup), Ok(JsValue::Number(0.0))); + let heap_bytes = r.collect_garbage() + spare; + r.set_limits(Limits { heap_bytes, ..Limits::default() }); + let out = r.run(run); + match &out { + Ok(JsValue::Number(_)) => {} + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => last_stop = Some((spare, e.line, e.column)), + other => panic!("{spare}: {other:?}"), + } + let bytes = r.interp().settled_heap_bytes(); + if out.is_ok() && bytes > heap_bytes { + over.push((spare, bytes - heap_bytes)); + } + } + assert!(over.is_empty(), "runs that suspended past the limit (spare bytes, bytes over): {over:?}"); + let Some((spare, line, column)) = last_stop else { panic!("no limit stopped the run") }; + assert_eq!((line, usize::try_from(column).ok()), (1, await_column), "the run with {spare} spare bytes stopped away from the await"); +} + +/// The fewest frames with which `src` runs to its end. +fn fewest_frames(src: &str) -> usize { + for frames in 1..64 { + let mut r = Realm::with_options(Options { es2017: true, ..Options::default() }, Limits { frames, ..Limits::default() }); + if r.run(src).is_ok() { + return frames; + } + } + panic!("{src} did not run"); +} + +#[test] +fn a_then_getter_on_a_returned_value_runs_after_the_async_frame_ends() { + let setup = "function rec(n) { return n ? rec(n - 1) : 0; }\n\ + var o = { get then() { rec(5); return undefined; } };\n"; + let direct = fewest_frames(&format!("{setup}o.then; 0")); + let returned = fewest_frames(&format!("{setup}async function f() {{ return o; }} f(); 0")); + assert_eq!(returned, direct); + // Returning the function's own promise rejects it with a TypeError. + let own = "async function f() { await 0; return p; } var p = f(); p.catch(function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(own), "true"); +} + +#[test] +fn an_async_arrow_head_reads_patterns_with_defaults_and_rejects_a_shorthand_await() { + let src = "var f = async ({a = 1}) => a; var g = async ({await: x}) => x; var h = async ([b = 2]) => b;\n\ + Promise.all([f({}), g({ await: 3 }), h([])]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "1,3,2"); + let mut r = realm(); + syntax_error(&mut r, "var async = function () {}; async({a = 1});"); + syntax_error(&mut r, "async ({await}) => 0"); + syntax_error(&mut r, "async ({a = await}) => 0"); +} + #[test] fn each_resume_takes_fuel() { let mut r = realm(); diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs index fa3d70a422..1baaeaad79 100644 --- a/crates/js/src/builtins/async_function.rs +++ b/crates/js/src/builtins/async_function.rs @@ -4,7 +4,7 @@ //! reaches through it. `AsyncFunction` is not a global. use super::{create_dynamic_function, data, native}; -use crate::heap::{CONFIGURABLE, Class, NativeKind, Object}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, Object, Prop}; use crate::interp::{Interp, JsResult}; use crate::value::Value; @@ -25,7 +25,13 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { data(interp, ctor, "prototype", Value::Object(proto), 0)?; // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary // built-in prototypes. - data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) + data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE)?; + // `AsyncFunction.prototype[@@toStringTag]` is "AsyncFunction", configurable only (section + // 25.5.3.2). + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("AsyncFunction"), flags: CONFIGURABLE })?; + } + Ok(()) } /// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 7ef696b086..8182fde016 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -609,6 +609,21 @@ impl Interp { } } + /// Resolves the promise of an async function whose frame has returned `v` and is already off + /// the frames. Returning the promise itself rejects it with a `TypeError` at `site`, the + /// return. + pub(crate) fn resolve_async_return(&mut self, p: ObjId, v: Value, site: Option) -> JsResult<()> { + if matches!(v, Value::Object(o) if o == p) { + return scoped(self, |interp| { + root(interp, &Value::Object(p)); + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + root(interp, &e); + reject_promise(interp, p, e, site) + }); + } + resolve_promise(self, p, v) + } + /// A new pending promise for the async function call whose frame is on top. pub(crate) fn new_async_promise(&mut self) -> JsResult { new_promise(self) @@ -639,6 +654,11 @@ impl Interp { let derived = new_promise(interp)?; root(interp, &Value::Object(derived)); promise_data(interp, derived)?.handled = true; + // The allocations above used up the room checked for at the start, so the reaction or + // job and the frame's bytes are checked again, with the frame still on top, before the + // awaited promise gets its reaction. + let then_bytes = if promise_data(interp, p)?.state == State::Pending { REACTION_BYTES } else { JOB_BYTES }; + interp.reserve_heap(then_bytes.saturating_add(bytes))?; perform_then(interp, p, on_fulfilled, on_rejected, derived)?; let (a, boundary) = interp.suspend_frame()?; let promise = a.promise; diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs index 195113d529..361af9a01f 100644 --- a/crates/js/src/generator.rs +++ b/crates/js/src/generator.rs @@ -18,7 +18,7 @@ use crate::LimitKind; use crate::builtins::iterator::iter_result; use crate::bytecode::Code; use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; -use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::interp::{Abrupt, AnnexOff, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; use crate::value::Value; /// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). @@ -306,7 +306,7 @@ impl Interp { boundary, generator: Some(generator), async_promise: None, - annex_off: Vec::new(), + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index c64f46e972..df44f785bb 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -211,6 +211,9 @@ impl Intrinsics { } } +/// The names of [`Frame::annex_off`], looked up once for each block function a frame assigns. +pub(crate) type AnnexOff = std::collections::HashSet; + pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, @@ -245,7 +248,7 @@ pub(crate) struct Frame { pub(crate) async_promise: Option, /// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not /// declared: [`Op::AnnexB`] leaves them alone. - pub(crate) annex_off: Vec, + pub(crate) annex_off: AnnexOff, /// The frame runs a module that another module of the same run waits under (ECMA-262 2015 /// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception /// that leaves it ends the run at the boundary frame without stopping in the frames between. @@ -1365,20 +1368,26 @@ impl Interp { Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, None => v, }; - // An async function's return resolves its promise, while the frame is still on top, and - // the call gives the promise. - let v = match self.async_promise() { - Some(p) => { - self.settle_async(p, Ok(v))?; - Value::Object(p) - } - None => v, - }; let Some(frame) = self.pop_frame() else { return internal("return without a frame") }; self.stack.truncate(frame.base); - self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); + // An async function's return resolves its promise after the frame is off the frames, so + // a `then` getter the resolution reads runs without it, and the call gives the promise. + // Settling roots the promise and the value, and a rejection for returning the promise + // itself is reported at the return. When settling fails, the frame goes back on top, so + // the error is reported at the return and ends the frames down to its boundary. + let v = match frame.async_promise { + Some(p) => match self.resolve_async_return(p, v, Some((frame.code.clone(), frame.pc.saturating_sub(1)))) { + Ok(()) => Value::Object(p), + Err(e) => { + self.frames.push(frame); + return Err(e); + } + }, + None => v, + }; + self.end_generator(frame.generator); let v = match frame.construct { Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o), _ => v, @@ -3914,7 +3923,7 @@ impl Interp { boundary, generator: None, async_promise: None, - annex_off: Vec::new(), + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); @@ -4339,7 +4348,7 @@ impl Interp { /// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the /// code counted against the heap, until its frame holds them: the scopes and functions it /// makes can collect. - fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { + fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { let mark = self.temp_envs.len(); self.temp_envs.push(env); self.temp_codes.push(code.clone()); @@ -4518,7 +4527,7 @@ impl Interp { boundary, generator: None, async_promise: None, - annex_off: Vec::new(), + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); @@ -4651,7 +4660,7 @@ impl Interp { /// option on or off, so it also meets the names that earlier runs of a kept realm declared. /// Also gives the names of [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not /// declare. - fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { + fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { // Strict eval code's own environment is in no frame yet, so it is a root while the // declarations reserve heap. let mark = self.temp_envs.len(); @@ -4662,7 +4671,7 @@ impl Interp { } /// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`]. - fn instantiate_global_rooted(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { + fn instantiate_global_rooted(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { let configurable = if is_eval { CONFIGURABLE } else { 0 }; if is_eval && !code.strict { self.check_eval_vars(code, env, var_env)?; @@ -4709,7 +4718,7 @@ impl Interp { (env, lex): (EnvId, EnvId), var_env: EnvId, configurable: u8, - ) -> JsResult> { + ) -> JsResult { // Functions close over the code's own environment with ES2015's scoping, and over its // variable environment otherwise (ECMA-262 5.1 section 13). When that is the global // object's, they close over the global scope inside it, which also holds the scripts' @@ -4740,11 +4749,11 @@ impl Interp { self.declare(var_env, v, None, configurable)?; self.note_global_var(on_global, v)?; } - let mut annex_off = Vec::new(); + let mut annex_off = AnnexOff::new(); for v in &code.annex_vars { self.use_fuel()?; if !self.annex_var_declarable(v, env, var_env)? { - annex_off.push(v.clone()); + annex_off.insert(v.clone()); continue; } self.declare(var_env, v, None, configurable)?; diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs index b96bbafe79..9bcf7f274c 100644 --- a/crates/js/src/interp/async_function.rs +++ b/crates/js/src/interp/async_function.rs @@ -167,7 +167,7 @@ impl Interp { boundary: true, generator: None, async_promise: Some(a.promise), - annex_off: Vec::new(), + annex_off: super::AnnexOff::new(), chained: false, pending_module: false, }); diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 1347f30de8..b733f90093 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -1789,7 +1789,10 @@ impl<'s> Parser<'s> { let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); let line_break = self.tok.newline_before; let awaits = self.awaits; - let (args, trailing_comma) = self.arguments()?; + // The arguments of a possible async arrow function's head may be patterns + // such as `{a = 1}`; they are checked as expressions once no `=>` follows. + let mark = self.cover_inits.len(); + let (args, trailing_comma) = self.arguments(async_head)?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), @@ -1797,6 +1800,8 @@ impl<'s> Parser<'s> { }; if async_head && self.at(Punct::Arrow) { self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma }); + } else if async_head { + self.check_cover(mark)?; } } TokenKind::Punct(Punct::QuestionDot) => { @@ -1944,16 +1949,20 @@ impl<'s> Parser<'s> { } fn parse_arguments(&mut self) -> Result> { - Ok(self.arguments()?.0) + Ok(self.arguments(false)?.0) } - /// An argument list, and whether a comma follows its last argument. - fn arguments(&mut self) -> Result<(Vec, bool)> { + /// An argument list, and whether a comma follows its last argument. With `cover`, the + /// arguments may hold initializers such as `{a = 1}`, which the caller checks. + fn arguments(&mut self, cover: bool) -> Result<(Vec, bool)> { self.expect(Punct::LParen)?; let mut args = Vec::new(); let mut trailing_comma = false; if !self.at(Punct::RParen) { loop { + if cover { + self.cover_ok = true; + } args.push(self.parse_element()?); // A comma may follow the last argument (ECMAScript 2017, section 12.3). if !self.eat(Punct::Comma)? { diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index b645238366..4bb126f8c2 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -186,6 +186,10 @@ impl Parser<'_> { { let name = name.clone(); self.check_identifier(&self.tok, &name)?; + // A shorthand `await` counts as one in an async arrow function's head, as a name does. + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } let token = self.bump()?; let target = self.ast.push_expr(Expr::Ident(name.clone()), token.span); let value = if self.at(Punct::Eq) { diff --git a/docs/mcp.md b/docs/mcp.md index 32e36656fe..b0578e7415 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2941,13 +2941,14 @@ checks that read a target descriptor also throw `ReferenceError` for an uninitia The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero; both properties are nonwritable, nonenumerable and configurable. Its first call clears the revoker's reference to the proxy. Later calls return `undefined` without revoking another object. A -`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there +`.jsx` file and a `source` string run as scripts read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there `yield` is a name like any other. A `.js` file `.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and accept the ECMAScript 2015 forms listed here. 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. A `.js` file +`.js` file also has `Promise` (described below), and so does a `.jsx` file or a `source` string run with +`module: true`; a `.jsx` file and a `source` string run as scripts 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. A `.js` file also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or `null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&` @@ -3697,15 +3698,16 @@ has them only when a `.js` script started it, and then a later `.jsx` run in it In such a `.jsx` run, `Object.prototype.toString` gives the ES5.1 result, `[object Object]` or another class name, and does not read `Symbol.toStringTag`. -A `.js` script also reads async functions and `await` as ECMA-262 2017 section 25.5 defines them +A `.js` script, and a `.jsx` file or a `source` string run with `module: true`, also read async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is -reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. Outside an async -function `await` is an ordinary name, and in a `.jsx` file or a `source` string `async` and `await` are ordinary -names and an async function is a syntax error. These are VectorCraft's own rules: each time a function resumes +reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. In script code +outside an async function `await` is an ordinary name; module code does not accept `await` as a name. In a `.jsx` +file or a `source` string run as a script, `async` and `await` are ordinary names and an async function is a syntax +error. These are VectorCraft's own rules: each time a function resumes counts as a job and takes 1 unit of fuel, and a function still waiting when no job is left stays suspended, and the run ends. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fbc78947c8..665a8b06bc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1207,7 +1207,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. When the trap returns `true`, the call returns the proxy, and the proxy's prototype is whatever the trap left, which may be unchanged for an extensible target. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.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 (with a computed name too), `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, a generator method included, has a `prototype` and 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: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect 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: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. `await` is an identifier outside async functions, and `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file; `.jsx` scripts and `source` strings do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - 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`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 8aa51b123ed28e8d526d0b00a588611921e597eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:16:37 -0800 Subject: [PATCH 8/8] JS: assert the qualified name's value in the E4X async test CI's test-lint step failed on with_e4x_async_before_a_double_colon_is_a_qualified_name: both of its assertions only checked is_ok. The test now runs x.async::b with async bound to a Namespace and asserts that it selects the namespaced child. --- crates/js/src/async_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 711f883633..6438392335 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -121,7 +121,9 @@ fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_it fn with_e4x_async_before_a_double_colon_is_a_qualified_name() { let options = Options { es2017: true, e4x: true, ..Options::default() }; assert!(parse("async::b", &options).is_ok()); - assert!(parse("var x = ; x.async::b", &options).is_ok()); + let mut r = Realm::with_options(options, Limits::default()); + let src = "var async = new Namespace('u'); var x = 78; String(x.async::b)"; + assert_eq!(r.run(src), Ok(JsValue::String("7".into()))); } #[test]