From c417aff8fbd9657fc4d9b6bfdbf54127b1a1cae9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:25:43 -0800 Subject: [PATCH 1/7] Scripts: .js scripts have Promise and run its jobs before the run ends A script run from a .js file now has Promise as ECMA-262 11th edition section 25.6 defines it: the constructor, then, catch, finally, and Promise.resolve, reject, all, allSettled and race. .jsx scripts and scripts given as source keep the ES5.1 built-ins; a named engine gets Promise at the first .js run that names it and keeps it. - The callbacks run as jobs from one FIFO queue after the script's own code ends and before the run ends, sliced like the script, with no native recursion along a then chain. Each job takes 1 unit of fuel, so an endless chain stops at the fuel limit. - More than 1,048,576 waiting jobs end the run with a Jobs limit error. A run that fails, hits a limit or is stopped drops its waiting jobs and rolls back as before. - A promise still rejected with no handler when the run ends goes to the report's unhandledRejections (first 20) and unhandledRejectionCount, 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 build plain Promise objects. Promise.any is not provided. cargo xtask test262 now runs the suite's built-ins/Promise tests that need only the built-ins present: 402 of 538 runs pass. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/include.rs | 7 + crates/engine/src/script/mod.rs | 69 +- crates/engine/src/tests/script_include.rs | 56 ++ crates/js/src/builtins.rs | 4 + crates/js/src/builtins/promise.rs | 1109 +++++++++++++++++++++ crates/js/src/heap.rs | 22 +- crates/js/src/interp.rs | 23 +- crates/js/src/lib.rs | 18 +- crates/js/src/promise_tests.rs | 223 +++++ crates/js/src/realm.rs | 85 +- crates/js/tests/test262.rs | 146 ++- docs/mcp.md | 30 +- docs/target-app-parity.md | 1 + xtask/src/test262.rs | 4 +- 14 files changed, 1765 insertions(+), 32 deletions(-) create mode 100644 crates/js/src/builtins/promise.rs create mode 100644 crates/js/src/promise_tests.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 4223d829ba..6b83c81759 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -219,6 +219,13 @@ pub(crate) struct Files { frames: Vec, } +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] 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 { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) +} + /// The output being built: its UTF-16 text, the line it is on, the units since that line began, /// whether its last unit is a carriage return, and what the last `#strict` line so far set. struct Out { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..6d51ac2925 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1592,24 +1592,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, /// with that file's name unless it is the run's own script. fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option>) { - let map = |m: &include::SourceMap| { - let (index, file, line, column) = m.locate(e.line, e.column); - let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; - (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) - }; // An error `$.evalFile` raised for a file it could not run, and no script caught, is at that // file's place. if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file)); } + placed(host, e, realm.error_source(), realm.error_tag()) +} + +/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`] +/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name +/// unless it is the run's own script. +fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option>) { + let map = |m: &include::SourceMap| { + let (index, file, line, column) = m.locate(e.line, e.column); + let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; + (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) + }; if e.line == 0 { return (e.clone(), None); } // An error in code from a source whose map is not at hand, such as code that `eval` compiled, // is given without a place. let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None); - match realm.error_source() { + match source { 0 => { let (e, index, file) = map(&host.script_map.borrow()); (e, (index > 0).then_some(file)) @@ -1626,7 +1633,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let kept = host.kept_maps.as_ref().map(|k| k.borrow()); - match kept.as_ref().and_then(|k| k.get(realm.error_tag())) { + match kept.as_ref().and_then(|k| k.get(tag)) { Some(kept) => { let (e, index, file) = map(&kept.map); let file = match &kept.script { @@ -1967,11 +1974,17 @@ impl Session { // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; + // 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() }; let strict = options.strict; let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); + if es2015 { + realm.add_es2015(); + } realm } None => { @@ -2264,6 +2277,11 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + let rejections = rejections_report(host, &job.realm); + if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) { + o.insert("unhandledRejections".into(), Value::Array(rejections)); + o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count())); + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); @@ -2309,6 +2327,29 @@ const NO_RUN: &str = "this function's script run has ended"; const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped"; const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web"; const ENGINE_BUSY: &str = "the script engine is in use by another run"; +const UNHANDLED_REJECTION: &str = "unhandled promise rejection"; +const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections"; + +/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when +/// known, the line, column and file it was rejected at. +fn rejections_report(host: &Host, realm: &Realm) -> Vec { + let mut out = Vec::new(); + for r in realm.unhandled_rejections() { + let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored }; + let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag); + let mut o = json!({ + "message": e.message, + "messageOrigin": if e.authored { "script" } else { "built-in" }, + "line": e.line, + "column": e.column, + }); + if let (Some(file), Some(map)) = (file, o.as_object_mut()) { + map.insert("file".into(), json!(&*file)); + } + out.push(o); + } + out +} /// The report of a run that failed; `file` is the included file the error is in. fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { @@ -2389,6 +2430,18 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: if report["ok"] == false { each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); } + if let Some(rejections) = report["unhandledRejections"].as_array() { + for r in rejections { + let mut placed = r.clone(); + placed["message"] = json!(format!("{UNHANDLED_REJECTION}: {}", r["message"].as_str().unwrap_or_default())); + each_line(&error_text(&host.name, &placed), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + let more = report["unhandledRejectionCount"].as_u64().unwrap_or(0).saturating_sub(rejections.len() as u64); + if more > 0 { + let text = format!("{}: {more} more {UNHANDLED_REJECTIONS}", host.name); + each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + } let timing = clock().is_some(); let ms = millis(host.run_nanos.get()); let slow = slowest(&host.commands.borrow()); diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index cc6756c332..3de6757888 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -689,3 +689,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() { } let _ = std::fs::remove_dir_all(base); } + +#[test] +fn a_js_script_has_promise_and_a_jsx_script_does_not() { + let base = folder("promise-realm"); + let main = base.join("main/main.js"); + write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);"); + let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["function", 1, 2])); + assert!(r.get("unhandledRejections").is_none(), "{r}"); + let r = run(&base, "vc.log(typeof Promise);").unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() { + let base = folder("promise-engine"); + let jsx = base.join("main/a.jsx"); + let js = base.join("main/b.js"); + let mut s = Session::new(); + let mut go = |path: &Path, text: &str| { + write(path, text); + s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone() + }; + assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"])); + assert_eq!( + go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"), + json!([1, "function", 2]) + ); + assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() { + let base = folder("promise-rejections"); + write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n"); + let main = base.join("main/main.js"); + write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n"); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + let got: Vec<(String, u64, Option)> = r["unhandledRejections"] + .as_array() + .unwrap() + .iter() + .map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc")))) + .collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}"); + assert_eq!(r["unhandledRejectionCount"], 2); + let c = s.execute("script.console", &json!({})).unwrap(); + let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect(); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}"); + assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..1be49acef9 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -15,6 +15,7 @@ mod global; mod json; mod math; mod object; +pub(crate) mod promise; use std::rc::Rc; @@ -145,6 +146,9 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + promise::install(interp)?; + } Ok(()) } diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs new file mode 100644 index 0000000000..d960fac60b --- /dev/null +++ b/crates/js/src/builtins/promise.rs @@ -0,0 +1,1109 @@ +//! `Promise` (ECMA-262 11th edition, section 25.6, ) +//! and the run's queue of promise jobs (section 8.4), in realms with [`crate::Options::es2015`]: +//! the constructor, `then`, `catch` and `finally`, and `Promise.resolve`, `reject`, `all`, +//! `allSettled` and `race`. `Promise.any` (ES2021) is not provided. +//! +//! A job is queued when a promise settles with reactions waiting, when `then` is called on a +//! settled promise, and when a promise is resolved with a thenable. Jobs run one at a time, in the +//! order they were queued, once the script's own code has ended and no other code runs: at the end +//! of [`crate::Realm::run`], and in the slices [`crate::Realm::advance`] runs after the script's +//! code, before it reports the run done. A job that a job queues joins the end of the queue. A job +//! takes a unit of fuel, its callback runs on the run's fuel, heap and frame limits, and a callback +//! written in JavaScript runs as the script's own code, so a slice can pause inside it. Each queued +//! job counts [`JOB_BYTES`] toward the heap limit, and more than [`MAX_JOBS`] queued jobs end the +//! run with [`LimitKind::Jobs`]. A run that ends with an error or a limit, or is ended, drops the +//! jobs still queued. A promise that is still pending when the queue is empty stays pending. +//! +//! A promise rejected while it has no handler is noted (HostPromiseRejectionTracker, section +//! 25.6.1.9); one that still has none when the run ends successfully is reported by +//! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. +//! +//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object +//! whose `length` is a whole number by index, and a string by code point; other values reject the +//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the +//! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` +//! are not read. + +use std::collections::VecDeque; +use std::rc::Rc; + +use super::{arg, constructor, create_at, method, native, new_array}; +use crate::LimitKind; +use crate::bytecode::Code; +use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; + +/// Where a promise was rejected: the code and the instruction. +pub(crate) type Site = (Rc, usize); + +/// The estimated bytes of a promise's state, without its reactions. +pub(crate) const PROMISE_BYTES: usize = 64; +/// The estimated bytes of a reaction a pending promise holds. +pub(crate) const REACTION_BYTES: usize = 48; +/// The estimated bytes of the state a promise operation's functions share. +pub(crate) const RECORD_BYTES: usize = 48; +/// The estimated bytes of a queued job. +pub(crate) const JOB_BYTES: usize = 64; +/// The most jobs the queue may hold at once. +pub(crate) const MAX_JOBS: usize = 1 << 20; +/// The most unhandled rejections a run reports one by one. +pub(crate) const MAX_REPORTED: usize = 20; +/// The most characters of a rejection's reason a report gives. +const MAX_REASON_CHARS: usize = 500; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum State { + Pending, + Fulfilled, + Rejected, +} + +/// A `then` waiting for a pending promise: the handlers (`undefined` when not callable) and the +/// promise `then` returned. +#[derive(Clone)] +pub(crate) struct Reaction { + on_fulfilled: Value, + on_rejected: Value, + derived: ObjId, +} + +/// A promise's internal slots (section 25.6.6), with where it was rejected. +#[derive(Clone)] +pub(crate) struct PromiseData { + pub(crate) state: State, + pub(crate) result: Value, + reactions: Vec, + pub(crate) handled: bool, + pub(crate) site: Option, +} + +impl PromiseData { + fn new() -> Self { + Self { state: State::Pending, result: Value::Undefined, reactions: Vec::new(), handled: false, site: None } + } + + /// The values the promise holds, for the collector. + pub(crate) fn values(&self) -> Vec { + let mut out = vec![self.result.clone()]; + for r in &self.reactions { + out.extend([r.on_fulfilled.clone(), r.on_rejected.clone(), Value::Object(r.derived)]); + } + out + } + + /// The estimated bytes of the state, beyond the object. + pub(crate) fn bytes(&self) -> usize { + PROMISE_BYTES + REACTION_BYTES * self.reactions.len() + } +} + +/// The state the functions a promise operation makes share. +#[derive(Clone)] +pub(crate) enum Record { + /// A promise's resolve and reject functions (section 25.6.1.3): the first call wins. + Resolving { promise: ObjId, done: bool }, + /// `Promise.all` and `allSettled`: the result's resolving record, the values so far and the + /// inputs not yet settled. + Combinator { resolving: ObjId, values: ObjId, remaining: u64 }, + /// The functions for one input of `Promise.all` or `allSettled`. + Element { combinator: ObjId, index: u32, called: bool }, + /// `finally`'s callback. + Finally { on_finally: Value }, + /// A value `finally` passes on or throws again. + Thunk { value: Value }, +} + +impl Record { + /// The values the record holds, for the collector. + pub(crate) fn values(&self) -> Vec { + match self { + Record::Resolving { promise, .. } => vec![Value::Object(*promise)], + Record::Combinator { resolving, values, .. } => vec![Value::Object(*resolving), Value::Object(*values)], + Record::Element { combinator, .. } => vec![Value::Object(*combinator)], + Record::Finally { on_finally: v } | Record::Thunk { value: v } => vec![v.clone()], + } + } +} + +/// A queued job. +enum Job { + /// PromiseReactionJob (section 25.6.2.1): calls `handler` with `argument` and settles + /// `derived` with the result, or passes `argument` on when `handler` is not callable. + Reaction { handler: Value, argument: Value, reject: bool, derived: ObjId, site: Option }, + /// PromiseResolveThenableJob (section 25.6.2.2): calls `then` on `thenable` with new + /// resolving functions for `promise`. + Thenable { promise: ObjId, thenable: Value, then: Value }, +} + +/// What happens when the running job's call ends. +enum Then { + /// The result resolves this promise, and an exception rejects it. + Settle(ObjId), + /// An exception rejects through this resolving record. + Reject(ObjId), +} + +/// The built-in functions a promise operation's functions call, with their record. +#[derive(Clone, Copy)] +enum Kind { + Resolve, + Reject, + AllElement, + SettledFulfilled, + SettledRejected, + ThenFinally, + CatchFinally, + ValueThunk, + Thrower, +} + +const KINDS: [(Kind, NativeFn); 9] = [ + (Kind::Resolve, resolve_function), + (Kind::Reject, reject_function), + (Kind::AllElement, all_element), + (Kind::SettledFulfilled, settled_fulfilled), + (Kind::SettledRejected, settled_rejected), + (Kind::ThenFinally, then_finally), + (Kind::CatchFinally, catch_finally), + (Kind::ValueThunk, value_thunk), + (Kind::Thrower, thrower), +]; + +/// `Promise`'s objects and the run's job queue. +pub(crate) struct Promises { + proto: Option, + ctor: Option, + /// The built-ins for each [`Kind`], in [`KINDS`] order. + natives: Vec, + queue: VecDeque, + running: Option, + /// The script's completion value while the jobs after it run. + completion: Option, + /// The script's own code has ended and the queue's jobs are running. + pub(crate) draining: bool, + /// Promises rejected in this run while they had no handler. + rejected: Vec, + /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). + pub(crate) max_jobs: usize, +} + +impl Default for Promises { + fn default() -> Self { + Self { + proto: None, + ctor: None, + natives: Vec::new(), + queue: VecDeque::new(), + running: None, + completion: None, + draining: false, + rejected: Vec::new(), + max_jobs: MAX_JOBS, + } + } +} + +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.values.extend(self.completion.iter()); + match &self.running { + Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), + None => {} + } + for job in &self.queue { + match job { + Job::Reaction { handler, argument, derived, site, .. } => { + roots.values.extend([handler, argument]); + roots.objects.push(*derived); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Job::Thenable { promise, thenable, then } => { + roots.values.extend([thenable, then]); + roots.objects.push(*promise); + } + } + } + } + + /// The estimated bytes the queued jobs hold. + pub(crate) fn queue_bytes(&self) -> usize { + JOB_BYTES.saturating_mul(self.queue.len()) + } + + /// Drops the noted rejections whose promise has a handler now. + pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) { + self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled)); + } +} + +/// Creates `Promise`, its prototype methods and its statics. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + interp.promises.proto = Some(proto); + let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; + interp.promises.ctor = Some(ctor); + constructor(interp, "Promise", ctor, proto)?; + method(interp, proto, "then", promise_then, 2)?; + method(interp, proto, "catch", promise_catch, 1)?; + method(interp, proto, "finally", promise_finally, 1)?; + method(interp, ctor, "resolve", promise_resolve_static, 1)?; + method(interp, ctor, "reject", promise_reject_static, 1)?; + method(interp, ctor, "all", promise_all, 1)?; + method(interp, ctor, "allSettled", promise_all_settled, 1)?; + method(interp, ctor, "race", promise_race, 1)?; + for (_, f) in KINDS { + let n = native(interp, "", f, 1, NativeKind::Plain, false)?; + interp.promises.natives.push(n); + } + Ok(()) +} + +/// Turns on [`crate::Options::es2015`] in a realm made without it and creates `Promise` there, +/// replacing a global `Promise` an earlier script defined. A realm that has the built-in `Promise` +/// already keeps it. When `Promise` cannot be created, every later run of the realm ends with an +/// internal error, as for a realm whose built-ins could not be installed. +pub(crate) fn add_to(interp: &mut Interp) { + interp.options.es2015 = true; + if interp.promises.ctor.is_some() || interp.install_error.is_some() { + return; + } + if let Err(e) = install(interp) { + let reason = match e { + Abrupt::Throw(v) => interp.describe(&v), + Abrupt::Limit(kind) => format!("limit reached: {kind:?}"), + Abrupt::Internal(message) => message, + }; + interp.install_error = Some(format!("the built-ins could not be installed: {reason}")); + } +} + +// ---- helpers ---- + +/// Runs `f`, then drops the temporary roots it added. +fn scoped(interp: &mut Interp, f: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let mark = interp.temp_roots.len(); + let r = f(interp); + interp.temp_roots.truncate(mark); + r +} + +fn root(interp: &mut Interp, v: &Value) { + interp.temp_roots.push(v.clone()); +} + +/// An exception that a promise operation turns into a rejection: it is no longer propagating, and +/// the place it was thrown at, when known, is the rejection's. +fn caught(interp: &mut Interp) -> Option { + interp.passing = Value::Undefined; + interp.thrown_mark = None; + interp.throw_site.take() +} + +/// The instruction the innermost script frame is running. +fn here(interp: &Interp) -> Option { + interp.frames.last().map(|f| (f.code.clone(), f.pc.saturating_sub(1))) +} + +/// The value an error of type `t` with `message` is. +fn error_value(interp: &mut Interp, t: ErrorType, message: &str) -> Value { + match interp.throw(t, message) { + Abrupt::Throw(v) => v, + _ => Value::Undefined, + } +} + +fn promise_data(interp: &mut Interp, p: ObjId) -> JsResult<&mut PromiseData> { + match interp.heap.object_mut(p).map(|o| &mut o.class) { + Some(Class::Promise(d)) => Ok(d), + _ => Err(Abrupt::Internal("a promise operation lost its promise".into())), + } +} + +fn record<'a>(interp: &'a mut Interp, r: &Value) -> JsResult<&'a mut Record> { + match r.as_object().and_then(|o| interp.heap.object_mut(o)).map(|o| &mut o.class) { + Some(Class::PromiseRecord(rec)) => Ok(rec), + _ => Err(Abrupt::Internal("a promise function lost its record".into())), + } +} + +fn is_promise(interp: &Interp, v: &Value) -> bool { + v.as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Promise(_))) +} + +/// `this` for a `Promise.prototype` method that needs a promise. +fn this_promise(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if is_promise(interp, this) => Ok(o), + _ => Err(interp.type_error(&format!("Promise.prototype.{name} was called on a value that is not a promise"))), + } +} + +/// Invoke (section 7.3.18): calls `v[name]` with `v` as `this`. +fn invoke(interp: &mut Interp, v: &Value, name: &str, args: &[Value]) -> JsResult { + let f = interp.get_value(v, &key(name))?; + if !interp.is_callable(&f) { + return Err(interp.type_error(&format!("{name} is not a function"))); + } + interp.call(&f, v, args) +} + +/// A new pending promise. +fn new_promise(interp: &mut Interp) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + PROMISE_BYTES)?; + let proto = interp.promises.proto; + let o = interp.heap.alloc_object(Object::new(Class::Promise(Box::new(PromiseData::new())), proto)); + interp.heap.bytes = interp.heap.bytes.saturating_add(PROMISE_BYTES); + Ok(o) +} + +/// A new record. The values it holds must be rooted. +fn new_record(interp: &mut Interp, rec: Record) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + RECORD_BYTES)?; + let o = interp.heap.alloc_object(Object::new(Class::PromiseRecord(Box::new(rec)), None)); + interp.heap.bytes = interp.heap.bytes.saturating_add(RECORD_BYTES); + Ok(o) +} + +/// A function that calls the built-in for `kind` with `rec` before its own arguments. `rec` must +/// be rooted. +fn record_function(interp: &mut Interp, kind: Kind, rec: ObjId, length: u32) -> JsResult { + let Some(&target) = interp.promises.natives.get(kind as usize) else { return Err(Abrupt::Internal("Promise is not installed".into())) }; + interp.reserve_heap(OBJECT_BYTES + PROP_BYTES + BOUND_ARG_BYTES + 16)?; + let proto = interp.intrinsics.function_proto; + let args: Rc<[Value]> = Rc::from([Value::Object(rec)]); + let f = interp.heap.alloc_object(Object::new(Class::Function(Func::Bound { target, this: Value::Undefined, args }), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES); + interp.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + Ok(Value::Object(f)) +} + +/// CreateResolvingFunctions (section 25.6.1.3): the shared record, the resolve function and the +/// reject function. `promise` must be rooted. +fn resolving_functions(interp: &mut Interp, promise: ObjId) -> JsResult<(ObjId, Value, Value)> { + scoped(interp, |interp| { + let rec = new_record(interp, Record::Resolving { promise, done: false })?; + root(interp, &Value::Object(rec)); + let resolve = record_function(interp, Kind::Resolve, rec, 1)?; + root(interp, &resolve); + let reject = record_function(interp, Kind::Reject, rec, 1)?; + Ok((rec, resolve, reject)) + }) +} + +/// Checks that `n` more jobs fit in the queue and in the heap. Everything the caller still needs +/// must be reachable from the roots. +fn reserve_jobs(interp: &mut Interp, n: usize) -> JsResult<()> { + if interp.promises.queue.len().saturating_add(n) > interp.promises.max_jobs { + return Err(Abrupt::Limit(LimitKind::Jobs)); + } + interp.reserve_heap(JOB_BYTES.saturating_mul(n)) +} + +/// Queues a job [`reserve_jobs`] made room for. +fn push_job(interp: &mut Interp, job: Job) { + interp.heap.bytes = interp.heap.bytes.saturating_add(JOB_BYTES); + interp.promises.queue.push_back(job); +} + +/// Settles pending promise `p` (FulfillPromise and RejectPromise, sections 25.6.1.4 and 25.6.1.7) +/// and queues a job for each reaction. `p` and `value` must be rooted. +fn settle(interp: &mut Interp, p: ObjId, fulfilled: bool, value: Value, site: Option) -> JsResult<()> { + let waiting = promise_data(interp, p)?.reactions.len(); + reserve_jobs(interp, waiting)?; + let data = promise_data(interp, p)?; + if data.state != State::Pending { + return Ok(()); + } + data.state = if fulfilled { State::Fulfilled } else { State::Rejected }; + data.result = value.clone(); + if !fulfilled { + data.site.clone_from(&site); + } + let reactions = std::mem::take(&mut data.reactions); + let handled = data.handled; + interp.heap.bytes = interp.heap.bytes.saturating_sub(REACTION_BYTES.saturating_mul(reactions.len())); + for r in reactions { + let handler = if fulfilled { r.on_fulfilled } else { r.on_rejected }; + push_job(interp, Job::Reaction { handler, argument: value.clone(), reject: !fulfilled, derived: r.derived, site: site.clone() }); + } + if !fulfilled && !handled { + interp.promises.rejected.push(p); + } + Ok(()) +} + +fn reject_promise(interp: &mut Interp, p: ObjId, reason: Value, site: Option) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &reason); + settle(interp, p, false, reason, site) + }) +} + +/// A resolve function's steps after its first-call check (section 25.6.1.3.2): `resolution` +/// fulfills `p`, unless it is `p` itself (a `TypeError` rejects it) or an object whose `then` is +/// callable (a job adopts its state), and an exception reading `then` rejects it. +fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &resolution); + let Value::Object(o) = resolution else { return settle(interp, p, true, resolution, None) }; + if o == p { + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + let site = here(interp); + return settle(interp, p, false, e, site); + } + let then = match interp.get_from(o, &key("then"), &resolution) { + Ok(t) => t, + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + return settle(interp, p, false, e, site); + } + Err(e) => return Err(e), + }; + if !interp.is_callable(&then) { + return settle(interp, p, true, resolution, None); + } + root(interp, &then); + reserve_jobs(interp, 1)?; + push_job(interp, Job::Thenable { promise: p, thenable: resolution, then }); + Ok(()) + }) +} + +/// The resolve function of the resolving record `rec`. +fn resolve_through(interp: &mut Interp, rec: ObjId, value: Value) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + resolve_promise(interp, p, value) +} + +/// The reject function of the resolving record `rec`. +fn reject_through(interp: &mut Interp, rec: ObjId, reason: Value, site: Option) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + reject_promise(interp, p, reason, site) +} + +/// PerformPromiseThen (section 25.6.5.4.1) with `derived` as the result capability's promise. +/// Every value must be rooted. +fn perform_then(interp: &mut Interp, p: ObjId, on_fulfilled: Value, on_rejected: Value, derived: ObjId) -> JsResult<()> { + let on_fulfilled = if interp.is_callable(&on_fulfilled) { on_fulfilled } else { Value::Undefined }; + let on_rejected = if interp.is_callable(&on_rejected) { on_rejected } else { Value::Undefined }; + let state = promise_data(interp, p)?.state; + if state == State::Pending { + interp.reserve_heap(REACTION_BYTES)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(REACTION_BYTES); + } else { + reserve_jobs(interp, 1)?; + } + let data = promise_data(interp, p)?; + data.handled = true; + match data.state { + State::Pending => { + data.reactions.push(Reaction { on_fulfilled, on_rejected, derived }); + } + State::Fulfilled => { + let argument = data.result.clone(); + push_job(interp, Job::Reaction { handler: on_fulfilled, argument, reject: false, derived, site: None }); + } + State::Rejected => { + let (argument, site) = (data.result.clone(), data.site.clone()); + push_job(interp, Job::Reaction { handler: on_rejected, argument, reject: true, derived, site }); + } + } + Ok(()) +} + +/// PromiseResolve (section 25.6.4.5.1) with `c` as the constructor: `x` when it is a promise whose +/// `constructor` is `c`, otherwise a new promise resolved with `x`. +fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &x); + if let Value::Object(o) = x + && is_promise(interp, &x) + { + let ctor = interp.get_from(o, &key("constructor"), &x)?; + if crate::interp::same_value(&ctor, c) { + return Ok(x); + } + } + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + resolve_promise(interp, p, x)?; + Ok(Value::Object(p)) + }) +} + +// ---- the job queue ---- + +impl Interp { + /// A run begun with [`crate::Realm::start`] is going: its script's code or the jobs after it. + pub(crate) fn running(&self) -> bool { + !self.frames.is_empty() || self.promises.draining + } + + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's + /// code ended with `completion`, which this gives back. + pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { + self.promises.completion = Some(completion); + loop { + if !self.frames.is_empty() { + let r = self.execute(); + self.job_returned(r)?; + continue; + } + let Some(job) = self.promises.queue.pop_front() else { break }; + self.start_job(job)?; + } + Ok(self.promises.completion.take().unwrap_or(Value::Undefined)) + } + + /// [`Interp::execute_slice`] for a run begun with [`crate::Realm::start`]: runs the script's + /// code and then the queued jobs, and gives `Some` with the script's completion value once the + /// code has ended and the queue is empty. + pub(crate) fn execute_run_slice(&mut self, pause_at: u64) -> JsResult> { + loop { + if self.frames.is_empty() { + let Some(job) = self.promises.queue.pop_front() else { + self.promises.draining = false; + return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined))); + }; + self.start_job(job)?; + if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + return Ok(None); + } + continue; + } + match self.execute_slice(pause_at) { + Ok(None) => return Ok(None), + Ok(Some(v)) if self.promises.running.is_none() => { + // The script's own code ended. + if self.promises.queue.is_empty() { + return Ok(Some(v)); + } + self.promises.completion = Some(v); + self.promises.draining = true; + } + Ok(Some(v)) => self.finish_job(Ok(v))?, + Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?, + Err(e) => return Err(e), + } + if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + return Ok(None); + } + } + } + + fn job_returned(&mut self, r: JsResult) -> JsResult<()> { + match r { + Ok(v) => self.finish_job(Ok(v)), + Err(Abrupt::Throw(v)) => self.finish_job(Err(v)), + Err(e) => Err(e), + } + } + + /// Starts a job: a native callback runs to its end here, and a callback written in JavaScript + /// gets a frame the caller runs. + fn start_job(&mut self, job: Job) -> JsResult<()> { + self.heap.bytes = self.heap.bytes.saturating_sub(JOB_BYTES); + self.use_fuel()?; + scoped(self, |interp| { + let (f, this, args, then) = match job { + 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) }; + } + root(interp, &Value::Object(derived)); + (handler, Value::Undefined, vec![argument], Then::Settle(derived)) + } + Job::Thenable { promise, thenable, then } => { + interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]); + let (rec, resolve, reject) = resolving_functions(interp, promise)?; + (then, thenable, vec![resolve, reject], Then::Reject(rec)) + } + }; + interp.temp_roots.push(f.clone()); + interp.temp_roots.push(this.clone()); + interp.temp_roots.extend(args.iter().cloned()); + interp.promises.running = Some(then); + match interp.start_call(f, this, args) { + Ok(Some(v)) => interp.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => interp.finish_job(Err(e)), + Err(e) => Err(e), + } + }) + } + + /// Ends the running job with its call's result or exception. + fn finish_job(&mut self, r: Result) -> JsResult<()> { + let site = if r.is_err() { caught(self) } else { None }; + let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) }; + 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(rec), Err(e)) => scoped(self, |interp| { + root(interp, &Value::Object(rec)); + reject_through(interp, rec, e, site) + }), + } + } + + /// Drops the run's queued jobs and its state; with `keep_rejections` false, the rejections it + /// noted too. + pub(crate) fn end_jobs(&mut self, keep_rejections: bool) { + let queued = self.promises.queue_bytes(); + self.heap.bytes = self.heap.bytes.saturating_sub(queued); + self.promises.queue.clear(); + self.promises.running = None; + self.promises.completion = None; + self.promises.draining = false; + if !keep_rejections { + self.promises.rejected.clear(); + } + } + + /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of + /// them described, and how many there are; the run's notes are cleared. + pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { + let rejected = std::mem::take(&mut self.promises.rejected); + let mut out = Vec::new(); + let mut count = 0; + for p in rejected { + let (reason, site) = match self.heap.object(p).map(|o| &o.class) { + Some(Class::Promise(d)) if !d.handled && d.state == State::Rejected => (d.result.clone(), d.site.clone()), + _ => continue, + }; + count += 1; + if out.len() >= MAX_REPORTED { + continue; + } + let mut message = self.describe(&reason); + if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) { + message.truncate(cut); + message.push('…'); + } + let authored = self.thrown_by_script(&reason); + let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc))); + out.push(crate::Rejection { message, line, column, tag, authored }); + } + (out, count) + } +} + +// ---- Promise ---- + +/// `new Promise(executor)` (section 25.6.3.1). Calling `Promise` without `new` is a `TypeError`. +fn promise_ctor(interp: &mut Interp, _: Value, args: &[Value], constructed: bool) -> JsResult { + if !constructed { + return Err(interp.type_error("Promise must be called with new")); + } + let executor = arg(args, 0); + if !interp.is_callable(&executor) { + return Err(interp.type_error("the Promise executor is not a function")); + } + scoped(interp, |interp| { + root(interp, &executor); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match interp.call(&executor, &Value::Undefined, &[resolve, reject]) { + Ok(_) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// A promise's resolve function (section 25.6.1.3.2). +fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a resolve function lost its record".into()))?; + resolve_through(interp, rec, arg(args, 1))?; + Ok(Value::Undefined) +} + +/// A promise's reject function (section 25.6.1.3.1). +fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?; + let site = here(interp); + reject_through(interp, rec, arg(args, 1), site)?; + Ok(Value::Undefined) +} + +/// `Promise.prototype.then` (section 25.6.5.4). +fn promise_then(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let p = this_promise(interp, &this, "then")?; + scoped(interp, |interp| { + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + perform_then(interp, p, arg(args, 0), arg(args, 1), derived)?; + Ok(Value::Object(derived)) + }) +} + +/// `Promise.prototype.catch` (section 25.6.5.1). +fn promise_catch(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + invoke(interp, &this, "then", &[Value::Undefined, arg(args, 0)]) +} + +/// `Promise.prototype.finally` (section 25.6.5.3). +fn promise_finally(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !matches!(this, Value::Object(_)) { + return Err(interp.type_error("Promise.prototype.finally was called on a value that is not an object")); + } + let on_finally = arg(args, 0); + if !interp.is_callable(&on_finally) { + return invoke(interp, &this, "then", &[on_finally.clone(), on_finally]); + } + scoped(interp, |interp| { + let rec = new_record(interp, Record::Finally { on_finally })?; + root(interp, &Value::Object(rec)); + let then_finally = record_function(interp, Kind::ThenFinally, rec, 1)?; + root(interp, &then_finally); + let catch_finally = record_function(interp, Kind::CatchFinally, rec, 1)?; + root(interp, &catch_finally); + invoke(interp, &this, "then", &[then_finally, catch_finally]) + }) +} + +/// Then Finally and Catch Finally (sections 25.6.5.3.1 and 25.6.5.3.2): calls the callback, then +/// passes `value` on, or throws it again when `throws`, once the callback's result settles. +fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult { + let rec_value = arg(args, 0); + let value = arg(args, 1); + let Record::Finally { on_finally } = record(interp, &rec_value)? else { return Err(Abrupt::Internal("not a finally record".into())) }; + let on_finally = on_finally.clone(); + let result = interp.call(&on_finally, &Value::Undefined, &[])?; + scoped(interp, |interp| { + root(interp, &value); + let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object); + let promise = promise_resolve(interp, &ctor, result)?; + root(interp, &promise); + let rec = new_record(interp, Record::Thunk { value })?; + root(interp, &Value::Object(rec)); + let thunk = record_function(interp, if throws { Kind::Thrower } else { Kind::ValueThunk }, rec, 0)?; + root(interp, &thunk); + invoke(interp, &promise, "then", &[thunk]) + }) +} + +fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, false) +} + +fn catch_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, true) +} + +fn thunk_value(interp: &mut Interp, args: &[Value]) -> JsResult { + match record(interp, &arg(args, 0))? { + Record::Thunk { value } => Ok(value.clone()), + _ => Err(Abrupt::Internal("not a thunk record".into())), + } +} + +fn value_thunk(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + thunk_value(interp, args) +} + +fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Err(Abrupt::Throw(thunk_value(interp, args)?)) +} + +/// `v` is a constructor: a function written in JavaScript, a built-in constructor, or a bound +/// function whose target is one. +fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { + let mut v = v.clone(); + loop { + let func = match v.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::Function(f)) => f.clone(), + _ => return Ok(false), + }; + match func { + Func::Closure { .. } => return Ok(true), + Func::Native { constructor, .. } => return Ok(constructor), + Func::Bound { target, .. } => { + interp.use_fuel()?; + v = Value::Object(target); + } + _ => return Ok(false), + } + } +} + +/// The `this` value of a static method, which must be a constructor. +fn this_constructor(interp: &mut Interp, this: &Value, name: &str) -> JsResult<()> { + if is_constructor(interp, this)? { + return Ok(()); + } + Err(interp.type_error(&format!("Promise.{name} was called on a value that is not a constructor"))) +} + +/// `Promise.resolve` (section 25.6.4.6). +fn promise_resolve_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "resolve")?; + promise_resolve(interp, &this, arg(args, 0)) +} + +/// `Promise.reject` (section 25.6.4.5). +fn promise_reject_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "reject")?; + scoped(interp, |interp| { + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let site = here(interp); + reject_promise(interp, p, arg(args, 0), site)?; + Ok(Value::Object(p)) + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Combine { + All, + AllSettled, + Race, +} + +impl Combine { + fn name(self) -> &'static str { + match self { + Combine::All => "all", + Combine::AllSettled => "allSettled", + Combine::Race => "race", + } + } +} + +fn promise_all(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::All) +} + +fn promise_all_settled(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::AllSettled) +} + +fn promise_race(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::Race) +} + +/// `Promise.all`, `allSettled` and `race` (sections 25.6.4.1, 25.6.4.2 and 25.6.4.4): an exception +/// on the way rejects the promise they return (IfAbruptRejectPromise). +fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsResult { + this_constructor(interp, &this, how.name())?; + scoped(interp, |interp| { + root(interp, &input); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match combine_inputs(interp, &this, &input, how, rec, &resolve, &reject) { + Ok(()) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. +enum Inputs { + Indexed { object: ObjId, length: f64 }, + CodePoints(Vec), +} + +impl Inputs { + fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { + 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 => { + Ok(Inputs::Indexed { object: *o, length }) + } + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + }, + Value::String(s) => Ok(Inputs::CodePoints(s.flat().to_vec())), + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + } + } + + /// The input at `index`, which counts code units for a string; `None` past the end. + fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { + match self { + Inputs::Indexed { object, length } => { + if *index >= *length { + return Ok(None); + } + let v = super::get_at(interp, *object, *index)?; + *index += 1.0; + Ok(Some(v)) + } + Inputs::CodePoints(units) => { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = *index as usize; + let Some(&first) = units.get(i) else { return Ok(None) }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let n = if pair { 2 } else { 1 }; + let piece = units.get(i..i + n).unwrap_or_default().to_vec(); + *index += n as f64; + let bytes = crate::heap::string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Some(Value::String(crate::value::Str::from_units(piece)))) + } + } + } +} + +fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { + let resolve_fn = interp.get_value(this, &key("resolve"))?; + if !interp.is_callable(&resolve_fn) { + return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); + } + root(interp, &resolve_fn); + let inputs = Inputs::new(interp, input, how)?; + let combinator = if how == Combine::Race { + None + } else { + let values = new_array(interp, 0)?; + root(interp, &Value::Object(values)); + let c = new_record(interp, Record::Combinator { resolving: rec, values, remaining: 1 })?; + root(interp, &Value::Object(c)); + Some((c, values)) + }; + let mut position = 0.0; + let mut index: u32 = 0; + loop { + interp.use_fuel()?; + let mark = interp.temp_roots.len(); + let Some(next) = inputs.get(interp, &mut position)? else { break }; + root(interp, &next); + let next_promise = interp.call(&resolve_fn, this, &[next])?; + root(interp, &next_promise); + match combinator { + None => { + invoke(interp, &next_promise, "then", &[resolve.clone(), reject.clone()])?; + } + Some((c, values)) => { + create_at(interp, values, f64::from(index), Value::Undefined)?; + let el = new_record(interp, Record::Element { combinator: c, index, called: false })?; + root(interp, &Value::Object(el)); + let (on_fulfilled, on_rejected) = if how == Combine::All { + (record_function(interp, Kind::AllElement, el, 1)?, reject.clone()) + } else { + let f = record_function(interp, Kind::SettledFulfilled, el, 1)?; + root(interp, &f); + (f, record_function(interp, Kind::SettledRejected, el, 1)?) + }; + interp.temp_roots.extend([on_fulfilled.clone(), on_rejected.clone()]); + if let Record::Combinator { remaining, .. } = record(interp, &Value::Object(c))? { + *remaining += 1; + } + invoke(interp, &next_promise, "then", &[on_fulfilled, on_rejected])?; + } + } + interp.temp_roots.truncate(mark); + index = index.checked_add(1).filter(|&i| i < u32::MAX).ok_or_else(|| interp.throw(ErrorType::Range, "too many promises to combine"))?; + } + if let Some((c, _)) = combinator { + element_done(interp, c)?; + } + Ok(()) +} + +/// Counts one more settled input of a `Promise.all` or `allSettled`; after the last one, resolves +/// the result with the values. +fn element_done(interp: &mut Interp, c: ObjId) -> JsResult<()> { + let Record::Combinator { resolving, values, remaining } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + *remaining = remaining.saturating_sub(1); + if *remaining > 0 { + return Ok(()); + } + let (resolving, values) = (*resolving, *values); + scoped(interp, |interp| { + root(interp, &Value::Object(c)); + resolve_through(interp, resolving, Value::Object(values)) + }) +} + +/// Stores `value` as one input's result (the first call only) and counts the input settled. +fn element_settled(interp: &mut Interp, args: &[Value], make: impl FnOnce(&mut Interp, Value) -> JsResult) -> JsResult { + let rec_value = arg(args, 0); + let Record::Element { combinator, index, called } = record(interp, &rec_value)? else { + return Err(Abrupt::Internal("not an element record".into())); + }; + if *called { + return Ok(Value::Undefined); + } + *called = true; + let (c, index) = (*combinator, *index); + let Record::Combinator { values, .. } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + let values = *values; + let v = make(interp, arg(args, 1))?; + scoped(interp, |interp| { + root(interp, &v); + super::put_at(interp, values, f64::from(index), v.clone())?; + element_done(interp, c) + })?; + Ok(Value::Undefined) +} + +/// `Promise.all` Resolve Element Functions (section 25.6.4.1.2). +fn all_element(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |_, v| Ok(v)) +} + +/// An `allSettled` result object: `{ status, value }` or `{ status, reason }`. +fn settled_object(interp: &mut Interp, fulfilled: bool, v: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &v); + interp.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES + 64)?; + let o = interp.new_object(); + root(interp, &Value::Object(o)); + let (status, name) = if fulfilled { ("fulfilled", "value") } else { ("rejected", "reason") }; + interp.define(o, key("status"), Prop::Data { value: Value::str(status), flags: OPEN })?; + interp.define(o, key(name), Prop::Data { value: v, flags: OPEN })?; + Ok(Value::Object(o)) + }) +} + +/// `Promise.allSettled` Resolve Element Functions (section 25.6.4.2.2). +fn settled_fulfilled(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, true, v)) +} + +/// `Promise.allSettled` Reject Element Functions (section 25.6.4.2.3). +fn settled_rejected(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, false, v)) +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..f880e7a05b 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,10 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A promise (ECMA-262 11th edition, section 25.6) and its state. + Promise(Box), + /// The state that the functions a promise operation makes share; scripts never see it. + PromiseRecord(Box), } /// What an XML value is. @@ -309,7 +313,8 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) => "Object", + Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", Class::Ordinary | Class::ForIn(_) => "Object", @@ -680,6 +685,21 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Promise(p) => { + for v in p.values() { + mark_value(&v, work, strings); + } + if let Some((code, _)) = &p.site { + mark_code(code, strings); + } + extra = p.bytes(); + } + Class::PromiseRecord(r) => { + for v in r.values() { + mark_value(&v, work, strings); + } + extra = crate::builtins::promise::RECORD_BYTES; + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..45de3cbe92 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -310,6 +310,8 @@ pub(crate) struct Interp { pub(crate) error_mark: Option, /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. pub(crate) strict_writes: bool, + /// `Promise` and the run's promise job queue ([`crate::builtins::promise`]). + pub(crate) promises: crate::builtins::promise::Promises, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -540,6 +542,7 @@ impl Interp { finally_sites: Vec::new(), error_mark: None, strict_writes: false, + promises: crate::builtins::promise::Promises::default(), }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -754,6 +757,7 @@ impl Interp { pub(crate) fn collect_garbage(&mut self) { self.drop_left_finally_marks(); self.drop_left_finally_sites(self.stack.len()); + self.promises.forget_handled(&self.heap); let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); @@ -775,11 +779,13 @@ impl Interp { roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); roots.envs.push(self.global_env); + self.promises.add_roots(&mut roots); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); - self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()); + let queued = self.promises.queue_bytes(); + self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()).saturating_add(queued); } /// Runs frames until the boundary frame on top returns, and returns its value. @@ -2536,6 +2542,21 @@ impl Interp { r } + /// Starts a call to `f` with no frame running, for a promise job: a native or host function + /// runs now and gives `Some` with its result, and a function written in JavaScript gets a + /// boundary frame that the caller runs, and gives `None`. A host function called here cannot + /// wait for its result, since no script code is running; a function written in JavaScript + /// runs as the script's own code does. + pub(crate) fn start_call(&mut self, f: Value, this: Value, args: Vec) -> JsResult> { + self.reentry += 1; + let prepared = self.prepare_call(f, this, args); + self.reentry -= 1; + match prepared? { + Prepared::Done(v) => Ok(Some(v)), + Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None), + } + } + fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..5d07c64493 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -46,6 +46,13 @@ //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and //! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each //! node. +//! +//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section +//! 25.6, ): the constructor, `then`, +//! `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. The promise +//! 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`]. #![forbid(unsafe_code)] pub mod ast; @@ -83,7 +90,9 @@ pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; +pub use realm::{ + Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE, +}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -100,11 +109,14 @@ pub struct Options { pub max_source_units: usize, /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, + /// 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, } 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 } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } } } @@ -209,6 +221,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod promise_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs new file mode 100644 index 0000000000..96e93764ff --- /dev/null +++ b/crates/js/src/promise_tests.rs @@ -0,0 +1,223 @@ +//! `Promise` and the promise job queue in realms with [`Options::es2015`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// 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:?}"), + } +} + +#[test] +fn an_extendscript_realm_has_no_promise() { + assert_eq!(Realm::new().run("typeof Promise").unwrap(), JsValue::String("undefined".into())); + assert_eq!(string("typeof Promise"), "function"); +} + +#[test] +fn then_callbacks_run_after_the_scripts_code_in_order() { + let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ + new Promise(function (res) { log.push('executor'); res(2); }).then(function (v) { log.push('b' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "executor sync a1 b2"); +} + +#[test] +fn jobs_run_first_in_first_out_and_a_jobs_jobs_join_the_end() { + let src = "var p = Promise.resolve();\n\ + p.then(function () { log.push(1); Promise.resolve().then(function () { log.push(4); }); });\n\ + p.then(function () { log.push(2); });\n\ + p.then(function () { log.push(3); });"; + assert_eq!(log(src), "1 2 3 4"); +} + +#[test] +fn a_thenable_is_adopted_in_a_later_job() { + let src = "var thenable = { then: function (res) { log.push('then'); res(7); } };\n\ + Promise.resolve(thenable).then(function (v) { log.push('got' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "sync then got7"); + let rejecting = "var t = { then: function (res, rej) { rej('no'); res(1); } };\n\ + new Promise(function (res) { res(t); }).then(null, function (r) { log.push('rejected ' + r); });"; + assert_eq!(log(rejecting), "rejected no"); + let throwing = "var t = { then: function (res) { res(1); throw new Error('late'); } };\n\ + Promise.resolve(t).then(function (v) { log.push('kept ' + v); });"; + assert_eq!(log(throwing), "kept 1"); +} + +#[test] +fn a_promise_resolved_with_itself_rejects_with_a_type_error() { + let src = "var res; var p = new Promise(function (r) { res = r; }); res(p);\n\ + p.then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true"); +} + +#[test] +fn catch_finally_and_the_combinators_settle_as_the_specification_says() { + let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\ + Promise.resolve(5).finally(function () { log.push('finally'); return 9; }).then(function (v) { log.push('kept ' + v); });\n\ + Promise.all([1, Promise.resolve(2), { then: function (r) { r(3); } }]).then(function (v) { log.push('all ' + v.join(',')); });\n\ + 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(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)); });"; + let out = log(src); + for part in [ + "caught x", + "finally", + "kept 5", + "all 1,2,3", + "rejected:r fulfilled:4", + "race fast", + "chars 2", + "not a list true", + "no length true", + "bad length true", + ] { + assert!(out.contains(part), "{part} in {out}"); + } +} + +#[test] +fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { + let mut r = realm(); + for src in [ + "Promise(function () {})", + "new Promise(1)", + "Promise.prototype.then.call({}, null)", + "Promise.resolve.call(1, 2)", + "Promise.all.call(Math.max, [])", + ] { + match r.run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } + } +} + +#[test] +fn an_unhandled_rejection_is_reported_with_its_line() { + let mut r = realm(); + r.run("var a = 1;\nPromise.reject(new Error('lost'));\nnew Promise(function () {\n throw new TypeError('also');\n});\nPromise.reject(2).catch(function () {});") + .unwrap(); + let got: Vec<(String, u32)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.line)).collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2), ("TypeError: also".to_string(), 4)]); + assert_eq!(r.unhandled_rejection_count(), 2); + assert!(r.unhandled_rejections().iter().all(|j| j.authored)); +} + +#[test] +fn a_rejection_handled_in_a_later_job_is_not_reported() { + let mut r = realm(); + r.run("var p = Promise.reject(1); Promise.resolve().then(function () { p.catch(function () {}); });").unwrap(); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.unhandled_rejection_count(), 0); +} + +#[test] +fn a_run_that_fails_reports_no_rejections_and_drops_its_jobs() { + let mut r = realm(); + let e = r.run("var ran = false; Promise.reject(1); Promise.resolve().then(function () { ran = true; }); throw 'stop';").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Thrown, "stop")); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.run("ran").unwrap(), JsValue::Bool(false)); +} + +#[test] +fn an_endless_then_chain_is_stopped_by_fuel() { + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run("function again() { return Promise.resolve().then(again); } again();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + let e = r.run("var res; var p = new Promise(function (r) { res = r; }); function loop() { p.then(loop); } p.then(loop); res(1);").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert!(!r.is_running()); +} + +#[test] +fn each_job_takes_fuel() { + // `then` on a settled promise queues a job, and on a pending one it does not; the difference in + // fuel between 50 calls and none is the jobs' fuel. + let used = |start: &str, calls: usize| { + let mut r = realm(); + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + r.run(&format!("var p = {start};{}", "p.then();".repeat(calls))).unwrap(); + 1_000_000 - r.fuel_left() + }; + let settled = used("Promise.resolve()", 50) - used("Promise.resolve()", 0); + let pending = used("new Promise(function () {})", 50) - used("new Promise(function () {})", 0); + assert_eq!(settled - pending, 50); +} + +#[test] +fn more_jobs_than_the_queue_holds_end_the_run_with_a_clear_error() { + let mut r = realm(); + r.interp().promises.max_jobs = 100; + let e = r.run("var p = Promise.resolve(); for (var i = 0; i < 200; i++) p.then(function () {});").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Jobs)); + assert!(e.message.contains("more than 100 promise jobs"), "{}", e.message); + assert!(r.run("var q = Promise.resolve(); for (var i = 0; i < 50; i++) q.then(function () {}); 1").is_ok()); +} + +#[test] +fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.start("var t = 0; Promise.resolve().then(function () { for (var i = 0; i < 5000; i++) t += i; }); 'done'").unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 1, "{paused_in_jobs}"); + assert!(!r.is_running()); + assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0)); +} + +#[test] +fn an_ended_sliced_run_drops_its_jobs() { + let mut r = realm(); + r.start("var ran = 0; Promise.resolve().then(function () { for (;;) ran++; });").unwrap(); + let mut slices = 0; + while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining { + slices += 1; + assert!(slices < 1000); + } + assert!(r.is_running()); + r.end(); + assert!(!r.is_running()); + assert_eq!(r.interp().promises.queue_bytes(), 0); + assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into())); +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ee2cd364f8..5373a8194e 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -57,6 +57,23 @@ pub enum LimitKind { Unbroken, /// A host function ended the run ([`crate::HostError::Abort`]). Host, + /// More promise jobs were waiting to run than a run may queue. + Jobs, +} + +/// A promise the last run rejected that still had no rejection handler when the run ended +/// ([`Realm::unhandled_rejections`]). `line` and `column` are where it was rejected: the `throw`, +/// or the call to its reject function or `Promise.reject`; they are 0 when that is not known. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Rejection { + /// The reason, described as an uncaught exception's message is. + pub message: String, + pub line: u32, + pub column: u32, + /// The source tag of the code `line` and `column` are in ([`Realm::error_tag`]). + pub tag: u32, + /// `message` is text the script supplied ([`RunError::authored`]). + pub authored: bool, } /// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an @@ -169,6 +186,8 @@ pub struct Realm { /// before the first script, for a script the realm did not compile, and once the tags are used /// up. script_tag: u32, + /// The unhandled rejections of the last run that ended successfully, and how many there were. + rejections: (Vec, usize), } impl Default for Realm { @@ -186,7 +205,7 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE, rejections: (Vec::new(), 0) } } /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default @@ -215,6 +234,13 @@ impl Realm { self.interp.reset_gc_threshold(); } + /// 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. + pub fn add_es2015(&mut self) { + crate::builtins::promise::add_to(&mut self.interp); + } + /// The realm's interrupt flag. Setting it stops a running script, or the next one to start. pub fn interrupt(&self) -> Interrupt { Interrupt(self.interp.interrupt.clone()) @@ -231,19 +257,21 @@ impl Realm { let _ = interp.define(global, key(name), Prop::Data { value: Value::Object(o), flags: HIDDEN }); } - /// Runs `source` as a script in the global environment and returns its completion value (the - /// value of the last expression statement that ran). A realm whose built-ins could not be - /// installed runs nothing and gives an internal error. + /// Runs `source` as a script in the global environment, then the promise jobs it queued, and + /// returns its completion value (the value of the last expression statement that ran). A realm + /// whose built-ins could not be installed runs nothing and gives an internal error. pub fn run(&mut self, source: &str) -> Result { let code = self.compile(source)?; - let result = self.interp.run_global(code, false); + let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v)); self.outcome(result) } /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { self.script_tag = UNKNOWN_SOURCE; + self.rejections = (Vec::new(), 0); let interp = &mut self.interp; + interp.end_jobs(false); if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false }); } @@ -293,8 +321,12 @@ impl Realm { interp.waiting = false; interp.resuming = None; interp.passing = Value::Undefined; + interp.end_jobs(result.is_ok()); match result { - Ok(v) => Ok(interp.to_js_value(&v)), + Ok(v) => { + self.rejections = interp.take_unhandled(); + Ok(interp.to_js_value(&v)) + } Err(Abrupt::Throw(v)) => { let message = interp.describe(&v); let authored = interp.thrown_by_script(&v); @@ -305,6 +337,11 @@ impl Realm { let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false }) } + Err(Abrupt::Limit(LimitKind::Jobs)) => { + let max = interp.promises.max_jobs; + let message = format!("limit reached: Jobs (more than {max} promise jobs were waiting to run)"); + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Jobs), message, line, column, authored: false }) + } Err(Abrupt::Limit(kind)) => { Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false }) } @@ -324,12 +361,14 @@ impl Realm { /// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one /// instruction), and pauses where it can resume: between two instructions of the script's own /// code. A getter, a built-in's callback or another nested run has native frames under it, so - /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned + /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. After the script's code + /// ends, the slices run the promise jobs it queued, pausing between jobs and inside a callback + /// written in JavaScript, and the run is done once the queue is empty. Once this has returned /// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its /// result ([`Realm::waits`]), the run does not advance: this gives an internal error. pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; - if interp.frames.is_empty() { + if !interp.running() { return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false }); } if interp.waiting { @@ -345,7 +384,7 @@ impl Realm { let cap = slice.saturating_add(self.unbroken_fuel).min(total); interp.fuel = cap; interp.in_slice = true; - let r = interp.execute_slice(cap - slice.min(cap)); + let r = interp.execute_run_slice(cap - slice.min(cap)); interp.in_slice = false; let used = cap - interp.fuel; interp.fuel = total - used; @@ -360,7 +399,28 @@ impl Realm { /// Is a run begun with [`Realm::start`] still going? pub fn is_running(&self) -> bool { - !self.interp.frames.is_empty() + self.interp.running() + } + + /// The promises the last run rejected that still had no rejection handler when it ended + /// successfully, in the order they were rejected: the first 20 of them. Empty after a run that + /// ended with an error, and until a run ends. + pub fn unhandled_rejections(&self) -> &[Rejection] { + &self.rejections.0 + } + + /// How many unhandled rejections the last run that ended successfully had, the ones + /// [`Realm::unhandled_rejections`] leaves out included. + pub fn unhandled_rejection_count(&self) -> usize { + self.rejections.1 + } + + /// Which source the code with tag `tag` is, as [`Realm::error_source`] gives it for an error. + pub fn source_of(&self, tag: u32) -> u32 { + match tag { + UNKNOWN_SOURCE => UNKNOWN_SOURCE, + tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), + } } /// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's @@ -434,10 +494,7 @@ impl Realm { /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which /// includes code from an earlier script and from the sources given during its run. pub fn error_source(&self) -> u32 { - match self.interp.error_tag { - UNKNOWN_SOURCE => UNKNOWN_SOURCE, - tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), - } + self.source_of(self.interp.error_tag) } /// The source tag of the code the last error's `line` and `column` are in, which stays the same diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 23337128bb..9f5223ea36 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -35,6 +35,12 @@ //! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without //! `test/annexB/` skips them; a folder there with no test to parse or run fails them. //! +//! 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`. +//! //! 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 //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -43,7 +49,6 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize}; - /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] struct Meta { @@ -696,6 +701,145 @@ fn run_annex_b(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); } +/// The feature tags a `test/built-ins/Promise` test may carry and still run: `Promise`, +/// `Promise.allSettled` and `Promise.prototype.finally`. +const PROMISE_FEATURES: &[&str] = &["Promise", "Promise.allSettled", "Promise.prototype.finally"]; + +#[test] +fn promise_builtins_run() { + let Some(dir) = suite_dir() else { + println!("test262 Promise: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_promise(&dir)).unwrap(); + 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() }); + let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let out = printed.clone(); + realm.define_function("print", move |args| { + let line = match args.first() { + Some(JsValue::String(s)) => s.clone(), + Some(other) => format!("{other:?}"), + None => String::new(), + }; + out.borrow_mut().push_str(&line); + out.borrow_mut().push('\n'); + Ok(JsValue::Undefined) + }); + let result = realm.run(script); + if asynchronous && result.is_ok() { + let printed = printed.borrow(); + return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { + Ok(()) + } else { + Err(format!("printed {:?}", printed.trim())) + }; + } + match (result, negative_type) { + (Ok(_), None) => Ok(()), + (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), + (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { + realm.bind_last_thrown("__thrown"); + match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { + Ok(JsValue::Bool(true)) => Ok(()), + _ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)), + } + } + (Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)), + } +} + +/// Runs the tests under `test/built-ins/Promise` whose feature tags are all in +/// [`PROMISE_FEATURES`], whose code parses as ES5 and uses only the built-ins present, as sloppy +/// and strict code as [`run_tests`] does, `async` tests included. Prints the counts and writes the +/// failures to `promise-failures.txt` beside the suite. +fn run_promise(dir: &Path) { + let root = or_fail(inside(dir, "test/built-ins/Promise")); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let done = harness("doneprintHandle.js"); + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let mut groups: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let (mut files, mut other_features) = (0usize, 0usize); + for path in or_fail(test_files(&root)) { + files += 1; + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !PROMISE_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let asynchronous = meta.flags.iter().any(|f| f == "async"); + let tags = if meta.features.is_empty() { "no feature tag".to_string() } else { meta.features.join(", ") }; + let counts = groups.entry(format!("{tags}, {}", if asynchronous { "async" } else { "sync" })).or_default(); + let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")); + if negative_parse || meta.flags.iter().any(|f| f == "module") { + counts.skipped += 1; + continue; + } + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if parse(&source, &Options::default()).is_err() || needs_missing_builtin(&[&source, &includes], &missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + let mut all = RunCounts::default(); + for (group, counts) in &groups { + println!("test262 built-ins/Promise, {group}: {}.", counts.summary()); + all.tests += counts.tests; + all.skipped += counts.skipped; + all.passed += counts.passed; + all.failed += counts.failed; + all.panicked += counts.panicked; + all.failures.push_str(&counts.failures); + } + let report = dir.join("promise-failures.txt"); + if let Err(e) = std::fs::write(&report, &all.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 built-ins/Promise through the interpreter: {files} files, {other_features} with other feature tags left out; {}. Failures: {}", + all.summary(), + report.display() + ); + assert!(all.tests > 0, "no Promise tests ran under {}", root.display()); + assert_eq!(all.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 3c577e0356..1a7b9d82dc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2616,8 +2616,10 @@ https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-act describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and -`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A script run from a +`.js` file also has `Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a +named engine (`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later +run, as it keeps its globals. The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it @@ -2644,6 +2646,27 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +In a `.js` script, `Promise` follows ECMA-262 11th edition section 25.6 +(https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, +`Promise.resolve`, `reject`, `all`, `allSettled` and `race`. `Promise.any` is not provided. These are VectorCraft's +own rules: + +- The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after + the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. + A promise still pending when no job is left stays pending, and the run ends. +- The jobs run on the run's fuel and limits, and each job takes 1 unit of fuel. A chain of callbacks that never ends + stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error + `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or + `script.stop` drops the jobs still waiting, and the documents go back as for any failed run. +- `all`, `allSettled` and `race` take an array, another object whose `length` is a whole number, or a string (one + item per character); any other value rejects the promise they return with a `TypeError`. The promises `then` and the + statics make are always plain `Promise` objects; `Symbol.species` and subclasses are not read. +- A promise rejected with no rejection handler that still has none when the run ends successfully is reported: the + report's `unhandledRejections` lists the first 20 as `{message, messageOrigin, line, column, file?}`, where it was + rejected (the `throw`, or the call of its reject function or of `Promise.reject`), `unhandledRejectionCount` counts + 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. + 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` @@ -2825,7 +2848,8 @@ VectorCraft sets these limits itself: In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, -runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In +runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`, with +`unhandledRejections` and `unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..7881566f89 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,6 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - 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: `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`. diff --git a/xtask/src/test262.rs b/xtask/src/test262.rs index 7ee456a6c2..3caf8f4a81 100644 --- a/xtask/src/test262.rs +++ b/xtask/src/test262.rs @@ -5,8 +5,8 @@ //! `test/language` tests and the tests of the ES5 built-ins under `test/built-ins` and //! `test/annexB/built-ins` that need only the interpreter's built-ins, run the `test/built-ins` //! tests for `String`, `Number`, `RegExp` and `Date`, parse and run the `test/annexB/language` -//! tests and run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and -//! `Function`), and print each one's counts. +//! tests, run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and +//! `Function`) and the `test/built-ins/Promise` tests, and print each one's counts. //! //! It also fetches `json2.js`, Douglas Crockford's public-domain JSON polyfill //! (https://github.com/douglascrockford/JSON-js), at a pinned commit, checks it against its SHA-256 From 438f2a9ba8f0f5d943925d16bdc70032d3daa983 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:29:09 -0800 Subject: [PATCH 2/7] Scripts: Promise review fixes for rooting, slices, finally and the combinators - A promise resolved with itself roots its TypeError before the queue reserves room, so a collection there no longer frees the reason. - A sliced run whose last job ends a slice reports Done in that slice instead of Paused, and a pause asked for in a run's last step no longer pauses the next run. - The job queue is replaced at run end, which frees its buffer. - A reaction job runs a finally callback as its own call, so a slice can pause inside it; the callback no longer runs to its end within the unbroken-fuel allowance. - all, allSettled and race read an array to its current length at each step, and a string input is flattened through the charged path and shared instead of copied. - The test262 runner checks the expected exception of an async test with a runtime negative. --- crates/js/src/builtins/promise.rs | 98 ++++++++++++++++++++++--- crates/js/src/promise_tests.rs | 117 +++++++++++++++++++++++++++++- crates/js/tests/test262.rs | 2 +- 3 files changed, 206 insertions(+), 11 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index d960fac60b..52c0e229ae 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -32,6 +32,7 @@ use crate::LimitKind; use crate::bytecode::Code; use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::string_builtins::flat_charged; use crate::value::Value; /// Where a promise was rejected: the code and the instruction. @@ -142,6 +143,9 @@ enum Then { Settle(ObjId), /// An exception rejects through this resolving record. Reject(ObjId), + /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or + /// Catch Finally function: `derived` is settled as that function's result settles it. + Finally { derived: ObjId, value: Value, throws: bool }, } /// The built-in functions a promise operation's functions call, with their record. @@ -211,6 +215,10 @@ impl Promises { roots.values.extend(self.completion.iter()); match &self.running { Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Finally { derived, value, .. }) => { + roots.objects.push(*derived); + roots.values.push(value); + } None => {} } for job in &self.queue { @@ -233,6 +241,12 @@ impl Promises { JOB_BYTES.saturating_mul(self.queue.len()) } + /// How many jobs are queued, and how many the queue's buffer has room for. + #[cfg(test)] + pub(crate) fn queue_size(&self) -> (usize, usize) { + (self.queue.len(), self.queue.capacity()) + } + /// Drops the noted rejections whose promise has a handler now. pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) { self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled)); @@ -455,7 +469,7 @@ fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult if o == p { let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); let site = here(interp); - return settle(interp, p, false, e, site); + return reject_promise(interp, p, e, site); } let then = match interp.get_from(o, &key("then"), &resolution) { Ok(t) => t, @@ -584,10 +598,12 @@ impl Interp { if self.frames.is_empty() { let Some(job) = self.promises.queue.pop_front() else { self.promises.draining = false; + // A pause asked for in the run's last step ends with the run. + self.pause.set(false); return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined))); }; self.start_job(job)?; - if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + if self.can_pause_between_jobs(pause_at) { return Ok(None); } continue; @@ -597,6 +613,7 @@ impl Interp { Ok(Some(v)) if self.promises.running.is_none() => { // The script's own code ended. if self.promises.queue.is_empty() { + self.pause.set(false); return Ok(Some(v)); } self.promises.completion = Some(v); @@ -606,12 +623,19 @@ impl Interp { Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?, Err(e) => return Err(e), } - if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + if self.can_pause_between_jobs(pause_at) { return Ok(None); } } } + /// No code is running and jobs are still queued, and the slice has used its fuel or the host + /// asked for a pause. With the queue empty the run is done instead, and the next turn of the + /// loop ends it. + fn can_pause_between_jobs(&self, pause_at: u64) -> bool { + self.frames.is_empty() && !self.promises.queue.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) + } + fn job_returned(&mut self, r: JsResult) -> JsResult<()> { match r { Ok(v) => self.finish_job(Ok(v)), @@ -632,7 +656,14 @@ impl Interp { return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; } root(interp, &Value::Object(derived)); - (handler, Value::Undefined, vec![argument], Then::Settle(derived)) + match finally_callback(interp, &handler) { + // The callback runs as the job's own call, so a slice can pause inside it. + Some((on_finally, throws)) => { + interp.temp_roots.extend([handler, argument.clone()]); + (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws }) + } + None => (handler, Value::Undefined, vec![argument], Then::Settle(derived)), + } } Job::Thenable { promise, thenable, then } => { interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]); @@ -665,6 +696,18 @@ impl Interp { root(interp, &Value::Object(rec)); reject_through(interp, rec, e, site) }), + (Then::Finally { derived, value, throws }, Ok(result)) => scoped(self, |interp| { + interp.temp_roots.extend([Value::Object(derived), value.clone(), result.clone()]); + match after_finally(interp, result, value, throws) { + Ok(v) => resolve_promise(interp, derived, v), + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + reject_promise(interp, derived, e, site) + } + Err(e) => Err(e), + } + }), + (Then::Finally { derived, .. }, Err(e)) => reject_promise(self, derived, e, site), } } @@ -673,7 +716,8 @@ impl Interp { pub(crate) fn end_jobs(&mut self, keep_rejections: bool) { let queued = self.promises.queue_bytes(); self.heap.bytes = self.heap.bytes.saturating_sub(queued); - self.promises.queue.clear(); + // A new queue frees the old one's buffer, which the heap estimate does not count. + self.promises.queue = VecDeque::new(); self.promises.running = None; self.promises.completion = None; self.promises.draining = false; @@ -799,8 +843,15 @@ fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult JsResult { scoped(interp, |interp| { root(interp, &value); + root(interp, &result); let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object); let promise = promise_resolve(interp, &ctor, result)?; root(interp, &promise); @@ -812,6 +863,29 @@ fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult Option<(Value, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let natives = &interp.promises.natives; + let throws = if natives.get(Kind::ThenFinally as usize) == Some(target) { + false + } else if natives.get(Kind::CatchFinally as usize) == Some(target) { + true + } else { + return None; + }; + match args.first().and_then(Value::as_object).and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::PromiseRecord(rec)) => match &**rec { + Record::Finally { on_finally } => Some((on_finally.clone(), throws)), + _ => None, + }, + _ => None, + } +} + fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { finally_step(interp, args, false) } @@ -934,10 +1008,12 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe }) } -/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. +/// 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. enum Inputs { Indexed { object: ObjId, length: f64 }, - CodePoints(Vec), + CodePoints(Rc<[u16]>), } impl Inputs { @@ -949,7 +1025,7 @@ impl Inputs { } _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), }, - Value::String(s) => Ok(Inputs::CodePoints(s.flat().to_vec())), + Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)), _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), } } @@ -958,7 +1034,11 @@ impl Inputs { fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { match self { Inputs::Indexed { object, length } => { - if *index >= *length { + let end = match interp.heap.object(*object).map(|o| &o.class) { + Some(Class::Array { length, .. }) => f64::from(*length), + _ => *length, + }; + if *index >= end { return Ok(None); } let v = super::get_at(interp, *object, *index)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 96e93764ff..8e03f2a136 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -76,6 +76,26 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() { assert_eq!(log(src), "true"); } +#[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\ + 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) { + let mut r = realm(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match r.run(src) { + Ok(_) => finished += 1, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue, + Err(e) => panic!("{spare}: {e:?}"), + } + r.set_limits(Limits::default()); + assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + } + assert!(finished > 0); +} + #[test] fn catch_finally_and_the_combinators_settle_as_the_specification_says() { let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\ @@ -104,6 +124,36 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { } } +#[test] +fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() { + // `Promise.resolve` runs once for each input and appends to the input while it is read. + let src = "var resolve = Promise.resolve; var input;\n\ + Promise.resolve = function (x) {\n\ + if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\ + return resolve.call(this, x);\n\ + };\n\ + input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\ + input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });"; + let out = log(src); + assert!(out.contains("array 1,2,3"), "{out}"); + assert!(out.contains("object 1"), "{out}"); + assert!(!out.contains("object 1,"), "{out}"); +} + +#[test] +fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() { + // A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap + // has room for. The combinator would stop at its first input. + let mut r = realm(); + r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() }); + let e = r.run("Promise.race(s)").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}"); + r.set_limits(Limits::default()); + assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0)); +} + #[test] fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { let mut r = realm(); @@ -206,18 +256,83 @@ fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() { assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0)); } +#[test] +fn a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() { + let mut r = realm(); + r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap(); + let v = loop { + match r.advance(1).unwrap() { + Progress::Paused => { + let interp = r.interp(); + assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run"); + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); +} + +#[test] +fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() { + let mut r = realm(); + let flag = r.pause_flag(); + r.define_function("pauseNow", move |_| { + flag.set(true); + Ok(JsValue::Undefined) + }); + r.start("Promise.resolve().then(pauseNow); 'first'").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into()))); + r.start("var a = 1; var b = 2; a + b").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0))); +} + +#[test] +fn a_sliced_run_pauses_inside_a_finally_callback() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.set_unbroken_fuel(5_000); + r.start( + "var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\ + Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\ + Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\ + 'done'", + ) + .unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 10, "{paused_in_jobs}"); + assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into())); +} + #[test] fn an_ended_sliced_run_drops_its_jobs() { let mut r = realm(); - r.start("var ran = 0; Promise.resolve().then(function () { for (;;) ran++; });").unwrap(); + r.start( + "var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });", + ) + .unwrap(); let mut slices = 0; while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining { slices += 1; assert!(slices < 1000); } assert!(r.is_running()); + assert_eq!(r.interp().promises.queue_size().0, 1); r.end(); assert!(!r.is_running()); assert_eq!(r.interp().promises.queue_bytes(), 0); + assert_eq!(r.interp().promises.queue_size(), (0, 0)); assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into())); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 9f5223ea36..0c23a80e9b 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -734,7 +734,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 && result.is_ok() && negative_type.is_none() { let printed = printed.borrow(); return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { Ok(()) From b7278c9b2f5c318109e54c904cf06f9368004547 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:05:54 -0800 Subject: [PATCH 3/7] Scripts: test a finally callback that returns a pending promise The result of finally() stays pending until the callback's promise settles in a later run. A fulfilled callback promise keeps the original value or reason, and a rejected one passes on its own reason. --- crates/js/src/promise_tests.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 8e03f2a136..1b258024d8 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -315,6 +315,26 @@ fn a_sliced_run_pauses_inside_a_finally_callback() { assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into())); } +#[test] +fn a_finally_callback_that_returns_a_pending_promise_holds_the_result_until_a_later_run_settles_it() { + let mut r = realm(); + r.run( + "var log = [], settle = {};\n\ + function wait(name) { return function () { return new Promise(function (res, rej) { settle[name] = { res: res, rej: rej }; }); }; }\n\ + function report(name) { return [function (v) { log.push(name + ' kept ' + v); }, function (e) { log.push(name + ' rejected ' + e); }]; }\n\ + var a = report('a'), b = report('b'), c = report('c'), d = report('d');\n\ + Promise.resolve(1).finally(wait('a')).then(a[0], a[1]);\n\ + Promise.reject(2).finally(wait('b')).then(b[0], b[1]);\n\ + Promise.resolve(3).finally(wait('c')).then(c[0], c[1]);\n\ + Promise.reject(4).finally(wait('d')).then(d[0], d[1]);", + ) + .unwrap(); + assert_eq!(r.run("Object.keys(settle).sort().join(' ') + '|' + log.join(' ')").unwrap(), JsValue::String("a b c d|".into())); + r.collect_garbage(); + r.run("settle.a.res('ignored'); settle.b.res('ignored'); settle.c.rej('new c'); settle.d.rej('new d');").unwrap(); + assert_eq!(r.run("log.join(', ')").unwrap(), JsValue::String("a kept 1, b rejected 2, c rejected new c, d rejected new d".into())); +} + #[test] fn an_ended_sliced_run_drops_its_jobs() { let mut r = realm(); From ff9ed631fa5eb5379b5db5a617ff7d2e57299263 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:13:32 -0800 Subject: [PATCH 4/7] Scripts: an unhandled rejection's reason is read only up to the report's length The report keeps the first 500 characters of a rejection reason. The reason string is now read up to that length along the rope, instead of being copied whole before it is cut. --- crates/js/src/builtins/promise.rs | 4 +++- crates/js/src/interp.rs | 10 ++++++++-- crates/js/src/promise_tests.rs | 22 ++++++++++++++++++++++ crates/js/src/value.rs | 25 +++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 52c0e229ae..655dcde430 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -741,7 +741,9 @@ impl Interp { if out.len() >= MAX_REPORTED { continue; } - let mut message = self.describe(&reason); + // Two code units per character keeps MAX_REASON_CHARS characters and one more, so the + // cut below still marks a longer reason. + let mut message = self.describe_prefix(&reason, 2 * MAX_REASON_CHARS + 2); if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) { message.truncate(cut); message.push('…'); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 45de3cbe92..e5e1d8a0d9 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3095,9 +3095,15 @@ impl Interp { /// A description of a thrown value that runs no JavaScript: `Name: message` for an error, /// the text of a primitive. pub(crate) fn describe(&mut self, v: &Value) -> String { - let Value::Object(o) = v else { return self.primitive_to_str(v).to_rust_string() }; + self.describe_prefix(v, usize::MAX) + } + + /// [`Interp::describe`] with each string it reads cut to its first `max_units` code units + /// before it is copied. + pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String { + let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) }; let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) { - Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.to_rust_string()), + Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.prefix_to_rust_string(max_units)), _ => None, }; match (data(self, "name"), data(self, "message")) { diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 1b258024d8..8c222c8de3 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -182,6 +182,28 @@ fn an_unhandled_rejection_is_reported_with_its_line() { assert!(r.unhandled_rejections().iter().all(|j| j.authored)); } +#[test] +fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { + let mut r = realm(); + r.run( + "function rep(t, n) { var s = ''; for (var i = 0; i < n; i++) s = s + t; return s; }\n\ + var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + Promise.reject(ab);\n\ + Promise.reject(new RangeError(ab));\n\ + Promise.reject(rep('\\ud83d\\ude00', 600));\n\ + Promise.reject(rep('x', 500));", + ) + .unwrap(); + let got: Vec = r.unhandled_rejections().iter().map(|j| j.message.clone()).collect(); + let want = vec![ + format!("{}…", "ab".repeat(250)), + format!("RangeError: {}…", "ab".repeat(244)), + format!("{}…", "\u{1F600}".repeat(500)), + "x".repeat(500), + ]; + assert_eq!(got, want); +} + #[test] fn a_rejection_handled_in_a_later_job_is_not_reported() { let mut r = realm(); diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index a0fbcd4a53..e0af7d9567 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -194,6 +194,31 @@ impl Str { pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } + + /// The first `max_units` code units as a Rust string, read along the rope without flattening + /// it, so a long string is not copied whole. + pub(crate) fn prefix_to_rust_string(&self, max_units: usize) -> String { + if self.len() <= max_units { + return self.to_rust_string(); + } + let mut units = Vec::with_capacity(max_units); + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + let room = max_units - units.len(); + if room == 0 { + break; + } + match &*s.0.borrow() { + Node::Flat(f) => units.extend_from_slice(&f[..f.len().min(room)]), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + String::from_utf16_lossy(&units) + } } impl PartialEq for Str { From 71d1600dabda2a161cea41f4c72cdf99b1fb2579 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 06:12:42 -0800 Subject: [PATCH 5/7] Scripts: an error's authored check hashes its name and message without copying them An error the interpreter throws keeps a hash of its description, and a run compares the error's current name and message with it to tell whether the text is the script's own. The comparison copied the whole description first, so a rejected error whose message a script had replaced with a long string was copied whole at the end of the run. The hash is now fed the strings' code units a piece at a time along the rope, so nothing is copied, and a change anywhere in the message is still seen. --- crates/js/src/interp.rs | 53 +++++++++++++++++++++++++++++++--- crates/js/src/promise_tests.rs | 22 ++++++++++++++ crates/js/src/value.rs | 15 ++++++++++ 3 files changed, 86 insertions(+), 4 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index e5e1d8a0d9..d1740a239e 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -50,12 +50,37 @@ fn internal(message: &str) -> JsResult { /// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]). fn description_hash(text: &str) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - text.hash(&mut h); + let mut h = DescriptionHash::default(); + h.text(text); h.finish() } +/// A [`description_hash`] fed the description's code units a run at a time, so a long string is +/// hashed without being copied. +#[derive(Default)] +struct DescriptionHash(std::hash::DefaultHasher); + +impl DescriptionHash { + fn units(&mut self, units: &[u16]) { + use std::hash::Hasher; + for &u in units { + self.0.write_u16(u); + } + } + + fn text(&mut self, text: &str) { + use std::hash::Hasher; + for u in text.encode_utf16() { + self.0.write_u16(u); + } + } + + fn finish(&self) -> u64 { + use std::hash::Hasher; + self.0.finish() + } +} + /// The kinds of error object the engine throws. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ErrorType { @@ -591,7 +616,7 @@ impl Interp { let Value::Object(o) = v else { return true }; let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true }; let hash = *hash; - description_hash(&self.describe(v)) != hash + self.describe_hash(*o) != hash } pub(crate) fn type_error(&mut self, message: &str) -> Abrupt { @@ -3113,6 +3138,26 @@ impl Interp { (None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())), } } + + /// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read + /// along its strings without copying them. + fn describe_hash(&self, o: ObjId) -> u64 { + let data = |k: &str| match self.find_property(o, &key(k)) { + Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s), + _ => None, + }; + let mut h = DescriptionHash::default(); + match (data("name"), data("message")) { + (Some(n), Some(m)) if m.len() != 0 => { + n.for_each_chunk(|c| h.units(c)); + h.text(": "); + m.for_each_chunk(|c| h.units(c)); + } + (Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)), + (None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))), + } + h.finish() + } } /// A compile failure, before it becomes an exception or a run error. diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 8c222c8de3..358a97a434 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -204,6 +204,28 @@ fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { assert_eq!(got, want); } +#[test] +fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() { + let mut r = realm(); + r.run( + "var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + var e; try { null.x; } catch (x) { e = x; }\n\ + e.message = ab;\n\ + Promise.reject(e);\n\ + try { null.x; } catch (x) { Promise.reject(x); }", + ) + .unwrap(); + let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect(); + assert_eq!(got.len(), 2); + assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true)); + assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]); + let interp = r.interp(); + match interp.find_property(interp.global, &crate::heap::key("ab")) { + Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"), + other => panic!("{other:?}"), + } +} + #[test] fn a_rejection_handled_in_a_later_job_is_not_reported() { let mut r = realm(); diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index e0af7d9567..9678a1895f 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -219,6 +219,21 @@ impl Str { } String::from_utf16_lossy(&units) } + + /// Calls `f` with each run of code units in order, read along the rope without flattening it. + pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) { + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + match &*s.0.borrow() { + Node::Flat(units) => f(units), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + } } impl PartialEq for Str { From 6a72901192b4c64594dd563636e9a9cb41f711fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:58:54 -0800 Subject: [PATCH 6/7] Scripts: adding Promise to a realm leaves the language it reads as it was Realm::add_es2015 no longer turns on Options::es2015, which now also selects the ECMAScript 2015 syntax. A realm made without the option gets Promise and still reads ES5.1 until set_es2015 changes it; the engine calls set_es2015 for each run before it adds Promise. --- crates/js/src/builtins/promise.rs | 10 +++++----- crates/js/src/promise_tests.rs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 655dcde430..f131e11a93 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -276,12 +276,12 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { Ok(()) } -/// Turns on [`crate::Options::es2015`] in a realm made without it and creates `Promise` there, -/// replacing a global `Promise` an earlier script defined. A realm that has the built-in `Promise` -/// already keeps it. When `Promise` cannot be created, every later run of the realm ends with an -/// internal error, as for a realm whose built-ins could not be installed. +/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global +/// `Promise` an earlier script defined, and leaves the language the realm's runs read as it is. A +/// realm that has the built-in `Promise` already keeps it. When `Promise` cannot be created, every +/// later run of the realm ends with an internal error, as for a realm whose built-ins could not be +/// installed. pub(crate) fn add_to(interp: &mut Interp) { - interp.options.es2015 = true; if interp.promises.ctor.is_some() || interp.install_error.is_some() { return; } diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 358a97a434..d65205d794 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -38,6 +38,25 @@ fn an_extendscript_realm_has_no_promise() { assert_eq!(string("typeof Promise"), "function"); } +#[test] +fn adding_promise_leaves_the_language_and_the_other_built_ins_as_they_were() { + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("typeof Promise").unwrap(), JsValue::String("function".into())); + assert_eq!(r.run("typeof Symbol").unwrap(), JsValue::String("undefined".into())); + assert!(matches!(r.run("let a = 1;"), Err(RunError { kind: RunErrorKind::Syntax, .. }))); + r.set_es2015(true); + assert_eq!(r.run("let b = 2; b").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn promise_prototype_cannot_be_replaced() { + let src = "var before = Promise.prototype; Promise.prototype = {}; \ + var p = new Promise(function () {}); \ + [Promise.prototype === before, Object.getPrototypeOf(p) === before, p instanceof Promise].join()"; + assert_eq!(string(src), "true,true,true"); +} + #[test] fn then_callbacks_run_after_the_scripts_code_in_order() { let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ From 7b9726c71eb5d73ccc9573fc2fc2e7270e584308 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:12:51 -0800 Subject: [PATCH 7/7] Scripts: Promise statics refuse arrow functions and methods as this The statics' constructor check now treats an arrow function, a method and a function bound to one as non-constructors, as new does, so Promise.resolve.call(() => {}, 1) throws a TypeError. The test262 line in docs/target-app-parity.md now gives the count on current main: 440 of 538 runs. --- crates/js/src/builtins/promise.rs | 6 +++--- crates/js/src/promise_tests.rs | 3 +++ docs/target-app-parity.md | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index f131e11a93..276acf7e96 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -911,8 +911,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -921,7 +921,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.method), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index d65205d794..915427de89 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -182,6 +182,9 @@ fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { "Promise.prototype.then.call({}, null)", "Promise.resolve.call(1, 2)", "Promise.all.call(Math.max, [])", + "Promise.resolve.call(() => {}, 1)", + "Promise.reject.call({ m() {} }.m, 1)", + "Promise.race.call((() => {}).bind(null), [])", ] { match r.run(src) { Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e39d701ba5..a121b2716a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1101,7 +1101,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - 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. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, 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: 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. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, 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: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - 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`.