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.
This commit is contained in:
dotCooCoo committed 2026-11-21 23:25:43 -08:00
1 parent db9acab4da
commit c417aff8fb
14 files changed
+1765 -32

No files matched your search

+7
View File
@@ -219,6 +219,13 @@ pub(crate) struct Files {
frames: Vec<Frame>,
}
/// 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 {
+61 -8
View File
@@ -1592,24 +1592,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
/// `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<Arc<str>>) {
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<Arc<str>>) {
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<Arc<st
// `$.evalFile` gave. A script given as text is named by that run's name.
_ => {
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<Value> {
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());
+56
View File
@@ -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<bool>)> = 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);
}
+4
View File
@@ -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(())
}
File diff suppressed because it is too large. Load diff
+21 -1
View File
@@ -246,6 +246,10 @@ pub(crate) enum Class {
},
/// A `.( )` filter in progress.
XmlFilter(Box<XmlFilterState>),
/// A promise (ECMA-262 11th edition, section 25.6) and its state.
Promise(Box<crate::builtins::promise::PromiseData>),
/// The state that the functions a promise operation makes share; scripts never see it.
PromiseRecord(Box<crate::builtins::promise::Record>),
}
/// 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<u32>, 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
+22 -1
View File
@@ -310,6 +310,8 @@ pub(crate) struct Interp {
pub(crate) error_mark: Option<u32>,
/// [`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<Value>) -> JsResult<Option<Value>> {
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<Value>, saved: usize) -> JsResult<Value> {
match self.prepare_call(f, this, args)? {
Prepared::Done(v) => Ok(v),
+16 -2
View File
@@ -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, <https://262.ecma-international.org/11.0/#sec-promise-objects>): 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;
+223
View File
@@ -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()));
}
+71 -14
View File
@@ -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<Rejection>, 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<JsValue, RunError> {
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<std::rc::Rc<crate::bytecode::Code>, 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<Progress, RunError> {
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
+145 -1
View File
@@ -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<String, RunCounts> = 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();
+27 -3
View File
@@ -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
+1
View File
@@ -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 <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`.
- With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`.
- `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. `<!DOCTYPE>` 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`.
+2 -2
View File
@@ -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