mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 11:45:55 +00:00
Merge pull request #9074 from dotCooCoo/feat/js-promise-job-queue
Scripts: .js scripts have Promise and run its jobs before the run ends
This commit is contained in:
@@ -1649,24 +1649,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))
|
||||
@@ -1683,7 +1690,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 {
|
||||
@@ -2025,7 +2032,8 @@ impl Session {
|
||||
// from its first run, and they act for the run that calls them.
|
||||
let fresh = realm.is_none();
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does.
|
||||
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
|
||||
// `.js` run that names it, and keeps it 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, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
@@ -2034,6 +2042,9 @@ impl Session {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
if es2015 {
|
||||
realm.add_es2015();
|
||||
}
|
||||
realm
|
||||
}
|
||||
None => {
|
||||
@@ -2338,6 +2349,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());
|
||||
@@ -2383,6 +2399,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 {
|
||||
@@ -2463,6 +2502,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());
|
||||
|
||||
@@ -692,3 +692,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);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ pub(crate) mod iterator;
|
||||
mod json;
|
||||
mod math;
|
||||
mod object;
|
||||
pub(crate) mod promise;
|
||||
mod symbol;
|
||||
|
||||
use std::rc::Rc;
|
||||
@@ -264,6 +265,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
@@ -268,6 +268,10 @@ pub(crate) enum Class {
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
UnitValue(Box<crate::unit_value::Measure>),
|
||||
/// 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.
|
||||
@@ -331,7 +335,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(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
|
||||
@@ -779,6 +784,21 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
|
||||
}
|
||||
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
|
||||
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() + syms) + extra
|
||||
|
||||
+85
-8
@@ -55,12 +55,37 @@ pub(crate) fn internal<T>(message: &str) -> JsResult<T> {
|
||||
|
||||
/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]).
|
||||
fn description_hash(text: &str) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
text.hash(&mut h);
|
||||
let mut h = DescriptionHash::default();
|
||||
h.text(text);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// A [`description_hash`] fed the description's code units a run at a time, so a long string is
|
||||
/// hashed without being copied.
|
||||
#[derive(Default)]
|
||||
struct DescriptionHash(std::hash::DefaultHasher);
|
||||
|
||||
impl DescriptionHash {
|
||||
fn units(&mut self, units: &[u16]) {
|
||||
use std::hash::Hasher;
|
||||
for &u in units {
|
||||
self.0.write_u16(u);
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&mut self, text: &str) {
|
||||
use std::hash::Hasher;
|
||||
for u in text.encode_utf16() {
|
||||
self.0.write_u16(u);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
use std::hash::Hasher;
|
||||
self.0.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds of error object the engine throws.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ErrorType {
|
||||
@@ -354,6 +379,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 well-known Symbols, `Symbol.for`'s registry and the objects that go with them, in a
|
||||
/// realm with [`crate::Options::es2015`].
|
||||
pub(crate) symbols: crate::symbol::Symbols,
|
||||
@@ -625,6 +652,7 @@ impl Interp {
|
||||
finally_sites: Vec::new(),
|
||||
error_mark: None,
|
||||
strict_writes: false,
|
||||
promises: crate::builtins::promise::Promises::default(),
|
||||
symbols: crate::symbol::Symbols::default(),
|
||||
};
|
||||
// With `Options::es2015`, the first run names the built-in functions, under the limits
|
||||
@@ -676,7 +704,7 @@ impl Interp {
|
||||
let Value::Object(o) = v else { return true };
|
||||
let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true };
|
||||
let hash = *hash;
|
||||
description_hash(&self.describe(v)) != hash
|
||||
self.describe_hash(*o) != hash
|
||||
}
|
||||
|
||||
pub(crate) fn type_error(&mut self, message: &str) -> Abrupt {
|
||||
@@ -854,6 +882,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());
|
||||
@@ -890,13 +919,20 @@ impl Interp {
|
||||
}
|
||||
self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0));
|
||||
roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
|
||||
self.promises.add_roots(&mut roots);
|
||||
self.heap.collect(&roots);
|
||||
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes);
|
||||
// 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()).saturating_add(self.symbols.registry_bytes());
|
||||
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(self.symbols.registry_bytes())
|
||||
.saturating_add(queued);
|
||||
}
|
||||
|
||||
/// Runs frames until the boundary frame on top returns, and returns its value.
|
||||
@@ -3249,6 +3285,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),
|
||||
@@ -4084,9 +4135,15 @@ impl Interp {
|
||||
/// A description of a thrown value that runs no JavaScript: `Name: message` for an error,
|
||||
/// the text of a primitive.
|
||||
pub(crate) fn describe(&mut self, v: &Value) -> String {
|
||||
let Value::Object(o) = v else { return self.primitive_to_str(v).to_rust_string() };
|
||||
self.describe_prefix(v, usize::MAX)
|
||||
}
|
||||
|
||||
/// [`Interp::describe`] with each string it reads cut to its first `max_units` code units
|
||||
/// before it is copied.
|
||||
pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String {
|
||||
let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) };
|
||||
let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) {
|
||||
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.to_rust_string()),
|
||||
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.prefix_to_rust_string(max_units)),
|
||||
_ => None,
|
||||
};
|
||||
match (data(self, "name"), data(self, "message")) {
|
||||
@@ -4096,6 +4153,26 @@ impl Interp {
|
||||
(None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read
|
||||
/// along its strings without copying them.
|
||||
fn describe_hash(&self, o: ObjId) -> u64 {
|
||||
let data = |k: &str| match self.find_property(o, &key(k)) {
|
||||
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s),
|
||||
_ => None,
|
||||
};
|
||||
let mut h = DescriptionHash::default();
|
||||
match (data("name"), data("message")) {
|
||||
(Some(n), Some(m)) if m.len() != 0 => {
|
||||
n.for_each_chunk(|c| h.units(c));
|
||||
h.text(": ");
|
||||
m.for_each_chunk(|c| h.units(c));
|
||||
}
|
||||
(Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)),
|
||||
(None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))),
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A compile failure, before it becomes an exception or a run error.
|
||||
|
||||
+19
-6
@@ -78,6 +78,14 @@
|
||||
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
|
||||
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
|
||||
//! entry counts against the heap limit.
|
||||
//!
|
||||
//! 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`]. [`Realm::add_es2015`] gives a realm made without the option
|
||||
//! `Promise` for its next runs.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
@@ -121,7 +129,9 @@ pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostIte
|
||||
pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts};
|
||||
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.
|
||||
@@ -145,11 +155,12 @@ pub struct Options {
|
||||
/// `f?.()`) and `??`. Off, they are syntax errors and the language is ES5.1's. Code a
|
||||
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
|
||||
/// A realm made with it on also has the later editions' built-ins this engine has: `Symbol`
|
||||
/// with Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects.
|
||||
/// A realm made with it off has the ES5.1 built-ins only, as the app's scripts expect. Those
|
||||
/// built-ins are chosen when the realm is made: turning the option on or off later with
|
||||
/// [`Realm::set_es2015`] changes the language later runs read, and does not add or remove
|
||||
/// them. Runs with it on also convert `0b` and `0o` strings to numbers.
|
||||
/// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, and
|
||||
/// `Promise` with its job queue. A realm made with it off has the ES5.1 built-ins only, as the
|
||||
/// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option
|
||||
/// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does
|
||||
/// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it.
|
||||
/// Runs with it on also convert `0b` and `0o` strings to numbers.
|
||||
pub es2015: bool,
|
||||
}
|
||||
|
||||
@@ -266,6 +277,8 @@ mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
#[cfg(test)]
|
||||
mod promise_tests;
|
||||
#[cfg(test)]
|
||||
mod symbol_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
//! `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 adding_promise_leaves_the_language_and_the_other_built_ins_as_they_were() {
|
||||
let mut r = Realm::new();
|
||||
r.add_es2015();
|
||||
assert_eq!(r.run("typeof Promise").unwrap(), JsValue::String("function".into()));
|
||||
assert_eq!(r.run("typeof Symbol").unwrap(), JsValue::String("undefined".into()));
|
||||
assert!(matches!(r.run("let a = 1;"), Err(RunError { kind: RunErrorKind::Syntax, .. })));
|
||||
r.set_es2015(true);
|
||||
assert_eq!(r.run("let b = 2; b").unwrap(), JsValue::Number(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_prototype_cannot_be_replaced() {
|
||||
let src = "var before = Promise.prototype; Promise.prototype = {}; \
|
||||
var p = new Promise(function () {}); \
|
||||
[Promise.prototype === before, Object.getPrototypeOf(p) === before, p instanceof Promise].join()";
|
||||
assert_eq!(string(src), "true,true,true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn then_callbacks_run_after_the_scripts_code_in_order() {
|
||||
let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\
|
||||
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 collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
|
||||
let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\
|
||||
for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }";
|
||||
let mut finished = 0;
|
||||
for spare in (40_000..240_000).step_by(641) {
|
||||
let mut r = realm();
|
||||
let live = r.collect_garbage();
|
||||
r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() });
|
||||
match r.run(src) {
|
||||
Ok(_) => finished += 1,
|
||||
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue,
|
||||
Err(e) => panic!("{spare}: {e:?}"),
|
||||
}
|
||||
r.set_limits(Limits::default());
|
||||
assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}");
|
||||
}
|
||||
assert!(finished > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
|
||||
let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\
|
||||
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 the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() {
|
||||
// `Promise.resolve` runs once for each input and appends to the input while it is read.
|
||||
let src = "var resolve = Promise.resolve; var input;\n\
|
||||
Promise.resolve = function (x) {\n\
|
||||
if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\
|
||||
return resolve.call(this, x);\n\
|
||||
};\n\
|
||||
input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\
|
||||
input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });";
|
||||
let out = log(src);
|
||||
assert!(out.contains("array 1,2,3"), "{out}");
|
||||
assert!(out.contains("object 1"), "{out}");
|
||||
assert!(!out.contains("object 1,"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() {
|
||||
// A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap
|
||||
// has room for. The combinator would stop at its first input.
|
||||
let mut r = realm();
|
||||
r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap();
|
||||
let live = r.collect_garbage();
|
||||
r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() });
|
||||
let e = r.run("Promise.race(s)").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
|
||||
r.set_limits(Limits::default());
|
||||
assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calling_promise_without_new_or_without_an_executor_is_a_type_error() {
|
||||
let mut r = realm();
|
||||
for src in [
|
||||
"Promise(function () {})",
|
||||
"new Promise(1)",
|
||||
"Promise.prototype.then.call({}, null)",
|
||||
"Promise.resolve.call(1, 2)",
|
||||
"Promise.all.call(Math.max, [])",
|
||||
"Promise.resolve.call(() => {}, 1)",
|
||||
"Promise.reject.call({ m() {} }.m, 1)",
|
||||
"Promise.race.call((() => {}).bind(null), [])",
|
||||
] {
|
||||
match r.run(src) {
|
||||
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"),
|
||||
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_long_rejection_reason_is_reported_cut_to_its_first_500_characters() {
|
||||
let mut r = realm();
|
||||
r.run(
|
||||
"function rep(t, n) { var s = ''; for (var i = 0; i < n; i++) s = s + t; return s; }\n\
|
||||
var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\
|
||||
Promise.reject(ab);\n\
|
||||
Promise.reject(new RangeError(ab));\n\
|
||||
Promise.reject(rep('\\ud83d\\ude00', 600));\n\
|
||||
Promise.reject(rep('x', 500));",
|
||||
)
|
||||
.unwrap();
|
||||
let got: Vec<String> = r.unhandled_rejections().iter().map(|j| j.message.clone()).collect();
|
||||
let want = vec![
|
||||
format!("{}…", "ab".repeat(250)),
|
||||
format!("RangeError: {}…", "ab".repeat(244)),
|
||||
format!("{}…", "\u{1F600}".repeat(500)),
|
||||
"x".repeat(500),
|
||||
];
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() {
|
||||
let mut r = realm();
|
||||
r.run(
|
||||
"var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\
|
||||
var e; try { null.x; } catch (x) { e = x; }\n\
|
||||
e.message = ab;\n\
|
||||
Promise.reject(e);\n\
|
||||
try { null.x; } catch (x) { Promise.reject(x); }",
|
||||
)
|
||||
.unwrap();
|
||||
let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect();
|
||||
assert_eq!(got.len(), 2);
|
||||
assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true));
|
||||
assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]);
|
||||
let interp = r.interp();
|
||||
match interp.find_property(interp.global, &crate::heap::key("ab")) {
|
||||
Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejection_handled_in_a_later_job_is_not_reported() {
|
||||
let mut r = realm();
|
||||
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 a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() {
|
||||
let mut r = realm();
|
||||
r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap();
|
||||
let v = loop {
|
||||
match r.advance(1).unwrap() {
|
||||
Progress::Paused => {
|
||||
let interp = r.interp();
|
||||
assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run");
|
||||
}
|
||||
Progress::Done(v) => break v,
|
||||
}
|
||||
};
|
||||
assert_eq!(v, JsValue::String("done".into()));
|
||||
assert!(!r.is_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() {
|
||||
let mut r = realm();
|
||||
let flag = r.pause_flag();
|
||||
r.define_function("pauseNow", move |_| {
|
||||
flag.set(true);
|
||||
Ok(JsValue::Undefined)
|
||||
});
|
||||
r.start("Promise.resolve().then(pauseNow); 'first'").unwrap();
|
||||
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into())));
|
||||
r.start("var a = 1; var b = 2; a + b").unwrap();
|
||||
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sliced_run_pauses_inside_a_finally_callback() {
|
||||
let mut r = realm();
|
||||
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
r.set_unbroken_fuel(5_000);
|
||||
r.start(
|
||||
"var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\
|
||||
Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\
|
||||
Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\
|
||||
'done'",
|
||||
)
|
||||
.unwrap();
|
||||
let mut paused_in_jobs = 0;
|
||||
let v = loop {
|
||||
match r.advance(500).unwrap() {
|
||||
Progress::Paused => {
|
||||
if r.interp().promises.draining {
|
||||
paused_in_jobs += 1;
|
||||
}
|
||||
}
|
||||
Progress::Done(v) => break v,
|
||||
}
|
||||
};
|
||||
assert_eq!(v, JsValue::String("done".into()));
|
||||
assert!(paused_in_jobs > 10, "{paused_in_jobs}");
|
||||
assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finally_callback_that_returns_a_pending_promise_holds_the_result_until_a_later_run_settles_it() {
|
||||
let mut r = realm();
|
||||
r.run(
|
||||
"var log = [], settle = {};\n\
|
||||
function wait(name) { return function () { return new Promise(function (res, rej) { settle[name] = { res: res, rej: rej }; }); }; }\n\
|
||||
function report(name) { return [function (v) { log.push(name + ' kept ' + v); }, function (e) { log.push(name + ' rejected ' + e); }]; }\n\
|
||||
var a = report('a'), b = report('b'), c = report('c'), d = report('d');\n\
|
||||
Promise.resolve(1).finally(wait('a')).then(a[0], a[1]);\n\
|
||||
Promise.reject(2).finally(wait('b')).then(b[0], b[1]);\n\
|
||||
Promise.resolve(3).finally(wait('c')).then(c[0], c[1]);\n\
|
||||
Promise.reject(4).finally(wait('d')).then(d[0], d[1]);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Object.keys(settle).sort().join(' ') + '|' + log.join(' ')").unwrap(), JsValue::String("a b c d|".into()));
|
||||
r.collect_garbage();
|
||||
r.run("settle.a.res('ignored'); settle.b.res('ignored'); settle.c.rej('new c'); settle.d.rej('new d');").unwrap();
|
||||
assert_eq!(r.run("log.join(', ')").unwrap(), JsValue::String("a kept 1, b rejected 2, c rejected new c, d rejected new d".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_sliced_run_drops_its_jobs() {
|
||||
let mut r = realm();
|
||||
r.start(
|
||||
"var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });",
|
||||
)
|
||||
.unwrap();
|
||||
let mut slices = 0;
|
||||
while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining {
|
||||
slices += 1;
|
||||
assert!(slices < 1000);
|
||||
}
|
||||
assert!(r.is_running());
|
||||
assert_eq!(r.interp().promises.queue_size().0, 1);
|
||||
r.end();
|
||||
assert!(!r.is_running());
|
||||
assert_eq!(r.interp().promises.queue_bytes(), 0);
|
||||
assert_eq!(r.interp().promises.queue_size(), (0, 0));
|
||||
assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into()));
|
||||
assert_eq!(r.run("after").unwrap(), JsValue::Bool(false));
|
||||
}
|
||||
+72
-14
@@ -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
|
||||
@@ -172,6 +189,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 {
|
||||
@@ -189,7 +208,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
|
||||
@@ -218,6 +237,14 @@ impl Realm {
|
||||
self.interp.reset_gc_threshold();
|
||||
}
|
||||
|
||||
/// Gives a realm made without [`Options::es2015`] the `Promise` that option adds, for its next
|
||||
/// runs; a realm that has it already is left as it is. It does not take it away again, and it
|
||||
/// does not add the option's other built-ins (`Symbol` and the iterators). Call it between
|
||||
/// runs.
|
||||
pub fn add_es2015(&mut self) {
|
||||
crate::builtins::promise::add_to(&mut self.interp);
|
||||
}
|
||||
|
||||
/// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and
|
||||
/// `const` names earlier runs declared stay visible when it is turned off. A run begun with
|
||||
/// [`Realm::start`] that is still going keeps the language it started with for the code it
|
||||
@@ -247,19 +274,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 });
|
||||
}
|
||||
@@ -330,11 +359,15 @@ impl Realm {
|
||||
interp.constructing = false;
|
||||
interp.resuming = None;
|
||||
interp.passing = Value::Undefined;
|
||||
interp.end_jobs(result.is_ok());
|
||||
if let Some(es2015) = interp.next_es2015.take() {
|
||||
interp.set_es2015(es2015);
|
||||
}
|
||||
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);
|
||||
@@ -345,6 +378,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 })
|
||||
}
|
||||
@@ -364,12 +402,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 {
|
||||
@@ -385,7 +425,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;
|
||||
@@ -400,7 +440,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
|
||||
@@ -483,10 +544,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
|
||||
|
||||
@@ -221,6 +221,46 @@ impl Str {
|
||||
pub(crate) fn to_rust_string(&self) -> String {
|
||||
String::from_utf16_lossy(&self.flat())
|
||||
}
|
||||
|
||||
/// The first `max_units` code units as a Rust string, read along the rope without flattening
|
||||
/// it, so a long string is not copied whole.
|
||||
pub(crate) fn prefix_to_rust_string(&self, max_units: usize) -> String {
|
||||
if self.len() <= max_units {
|
||||
return self.to_rust_string();
|
||||
}
|
||||
let mut units = Vec::with_capacity(max_units);
|
||||
let mut stack = vec![self.clone()];
|
||||
while let Some(s) = stack.pop() {
|
||||
let room = max_units - units.len();
|
||||
if room == 0 {
|
||||
break;
|
||||
}
|
||||
match &*s.0.borrow() {
|
||||
Node::Flat(f) => units.extend_from_slice(&f[..f.len().min(room)]),
|
||||
Node::Concat { left, right, .. } => {
|
||||
stack.push(right.clone());
|
||||
stack.push(left.clone());
|
||||
}
|
||||
Node::Taken => {}
|
||||
}
|
||||
}
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// Calls `f` with each run of code units in order, read along the rope without flattening it.
|
||||
pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) {
|
||||
let mut stack = vec![self.clone()];
|
||||
while let Some(s) = stack.pop() {
|
||||
match &*s.0.borrow() {
|
||||
Node::Flat(units) => f(units),
|
||||
Node::Concat { left, right, .. } => {
|
||||
stack.push(right.clone());
|
||||
stack.push(left.clone());
|
||||
}
|
||||
Node::Taken => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Str {
|
||||
|
||||
+145
-1
@@ -40,6 +40,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`.
|
||||
//!
|
||||
//! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of
|
||||
//! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with
|
||||
//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and
|
||||
@@ -58,7 +64,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 {
|
||||
@@ -899,6 +904,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() && negative_type.is_none() {
|
||||
let printed = printed.borrow();
|
||||
return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("printed {:?}", printed.trim()))
|
||||
};
|
||||
}
|
||||
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());
|
||||
}
|
||||
|
||||
/// The folders of the tests of `Symbol`, Symbol-keyed properties and the iterators of arrays and
|
||||
/// strings, which run in a realm with [`Options::es2015`].
|
||||
const SYMBOL_BUILT_INS: &[&str] = &[
|
||||
|
||||
+28
-3
@@ -2717,8 +2717,11 @@ string, `?.` and `??` are syntax errors. Which files read these forms is VectorC
|
||||
https://ecma-international.org/publications-and-standards/standards/ecma-357/): XML and XMLList literals, the `..`,
|
||||
`.@`, `.*`, `.()` and `::` selectors, `for each`, `default xml namespace`, and the global `XML`, `XMLList`,
|
||||
`Namespace`, `QName`, `isXMLName` and `setDefaultXMLNamespace`, as the XML object pages describe them
|
||||
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). The script reaches the
|
||||
app through the global object `vc`, and writes to the Script Console and runs other files through `$`:
|
||||
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). 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
|
||||
@@ -2872,6 +2875,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.
|
||||
|
||||
The first run in an engine decides whether the engine has `Symbol` and the iterators of arrays, strings and
|
||||
`arguments` objects, and each run's script decides which syntax that run reads. The built-in functions' names follow
|
||||
the rule above. A `.jsx` script or a `source` string that starts a new engine has no `Symbol` and no iterators of arrays,
|
||||
@@ -3084,7 +3108,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
|
||||
|
||||
@@ -1103,6 +1103,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), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
|
||||
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
|
||||
- Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`).
|
||||
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user