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