Merge pull request #9131 from dotCooCoo/feat/js-es2017-async-await

JavaScript: .js scripts run async functions and await
This commit is contained in:
.CooCoo
2026-12-02 11:37:17 -08:00
committed by GitHub
27 changed files with 1690 additions and 133 deletions
+5 -4
View File
@@ -238,9 +238,10 @@ pub(crate) struct Files {
entry_key: Option<String>,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` or `.mjs` (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.
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] and
/// [`vectorcraft_js::Options::es2017`] when its file name ends in `.js` or `.mjs` (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") || e.eq_ignore_ascii_case("mjs"))
}
@@ -496,7 +497,7 @@ impl Files {
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, es2017: self.es2015, e4x: true, ..Options::default() }
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
+4 -1
View File
@@ -2299,13 +2299,16 @@ impl Session {
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
let es2015 = request.module || 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() };
// It also reads async functions and `await` (ECMAScript 2017).
let options =
Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, es2017: es2015, e4x: true, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
let mut realm = match realm {
Some(mut realm) => {
realm.set_limits(limits);
realm.set_es2015(es2015);
realm.set_es2017(es2015);
if es2015 {
realm.add_es2015();
}
+23
View File
@@ -435,6 +435,29 @@ fn a_js_script_has_proxy_and_reflect_and_a_jsx_script_does_not() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them() {
let dir = fresh_folder("es2017");
let write = |name: &str, text: &str| {
let p = dir.join(name);
std::fs::write(&p, text).unwrap();
p.to_string_lossy().into_owned()
};
let mut s = two_docs();
let path = |p: &str| json!({"path": p});
let src = "async function twice(p) { return 2 * await p; }\nvar half = async x => x / 2;\n\
twice(Promise.resolve(3)).then(function (v) { vc.log(v); });\n\
(async function () { try { await Promise.reject(new Error('no')); } catch (e) { vc.log(await half(8) + e.message); } })();\n\
vc.log('sync');\n";
let r = s.execute("script.run", &path(&write("async.js", src))).unwrap();
assert_eq!(r["log"], json!(["sync", 6, "4no"]), "{r}");
for (name, text) in [("async.jsx", "async function f() {}"), ("arrow.jsx", "var f = async x => x;")] {
let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string();
assert!(e.contains("SyntaxError"), "{name}: {e}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() {
let dir = fresh_folder("es2020");
+4
View File
@@ -238,6 +238,8 @@ pub enum Expr {
/// `...expression` in an array literal or an argument list, and as the last of an arrow
/// function's parenthesized parameters while they are read.
Spread(ExprId),
/// `await operand`, in an async function's body.
Await(ExprId),
/// An optional chain (`a?.b.c`, `a?.[k]`, `f?.()`): its accesses and calls, the
/// [`Expr::Optional`] steps among them included. It is `undefined` when one of those steps
/// finds `undefined` or `null`, and the rest of the chain is skipped.
@@ -502,6 +504,8 @@ pub struct Function {
pub strict: bool,
/// A generator function (`function*`, or `*name() {…}` in an object literal).
pub generator: bool,
/// An async function (ECMAScript 2017): a call returns a promise, and its body may `await`.
pub is_async: bool,
pub span: Span,
/// The function is defined in a class body (a method, an accessor or the constructor): it has
/// a home object for `super.property`.
+333
View File
@@ -0,0 +1,333 @@
//! Async functions and `await` in realms with [`Options::es2017`].
use super::*;
fn realm() -> Realm {
Realm::with_options(Options { es2017: true, ..Options::default() }, Limits::default())
}
/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran.
fn log(src: &str) -> String {
let mut r = realm();
if let Err(e) = r.run(&format!("var log = [];\n{src}")) {
panic!("{src}\n{e:?}");
}
match r.run("log.join(' ')") {
Ok(JsValue::String(s)) => s,
other => panic!("{src}: {other:?}"),
}
}
fn syntax_error(r: &mut Realm, src: &str) {
match r.run(src) {
Err(e) if e.kind == RunErrorKind::Syntax => {}
other => panic!("{src}: {other:?}"),
}
}
#[test]
fn awaits_resume_in_the_job_order_promise_reactions_have() {
let src = "async function f() { log.push('f1'); await null; log.push('f2'); await null; log.push('f3'); }\n\
f();\n\
Promise.resolve().then(function () { log.push('t1'); }).then(function () { log.push('t2'); });\n\
log.push('sync');";
assert_eq!(log(src), "f1 sync f2 t1 f3 t2");
}
#[test]
fn the_function_returns_a_promise_its_return_resolves_and_its_throw_rejects() {
let src = "async function ok(x) { return x + 1; }\n\
async function bad() { throw new TypeError('no'); }\n\
var p = ok(1); log.push(p instanceof Promise);\n\
p.then(function (v) { log.push('ok ' + v); });\n\
bad().then(null, function (e) { log.push(e instanceof TypeError); });";
assert_eq!(log(src), "true ok 2 true");
}
#[test]
fn a_rejected_await_throws_where_it_stands_and_finally_runs_after_an_await() {
let src = "async function f() {\n\
try { await Promise.reject('r'); log.push('not here'); }\n\
catch (e) { log.push('caught ' + e); }\n\
finally { await 1; log.push('finally'); }\n\
return 'end';\n\
}\n\
f().then(function (v) { log.push(v); });";
assert_eq!(log(src), "caught r finally end");
let rethrow = "async function g() { try { await Promise.reject(new Error('x')); } finally { log.push('cleanup'); } }\n\
g().catch(function (e) { log.push('rejected ' + e.message); });";
assert_eq!(log(rethrow), "cleanup rejected x");
}
#[test]
fn arrows_expressions_and_methods_can_be_async() {
let src = "var a = async x => (await x) * 2;\n\
var b = async (x, y) => { return await x + y; };\n\
var c = async function named() { return typeof named; };\n\
var o = { async m(v) { return this.k + await v; }, k: 'k' };\n\
Promise.all([a(2), b(Promise.resolve(1), 2), c(), o.m('v')]).then(function (r) { log.push(r.join(',')); });";
assert_eq!(log(src), "4,3,function,kv");
}
#[test]
fn a_comma_may_follow_an_arrow_functions_last_parameter_but_not_a_rest_parameter() {
let src = "var f = async (x,) => x; var g = async (x, ...xs) => xs.length; var h = (a, b,) => a + b;\n\
var async = function () { return arguments.length; }; log.push(async(...[1, 2],));\n\
Promise.all([f(1), g(1, 2, 3), h(1, 2), h.length]).then(function (r) { log.push(r.join(',')); });";
assert_eq!(log(src), "2 1,2,3,2");
let mut r = realm();
for src in ["async (...xs,) => xs", "async (a, ...xs,) => xs", "(...xs,) => xs", "(a, ...xs,) => xs", "(a,);", "(a, b,);"] {
syntax_error(&mut r, src);
}
}
#[test]
fn async_functions_are_not_constructors_and_have_no_prototype() {
let src = "async function f() {}\n\
log.push(f.hasOwnProperty('prototype'));\n\
try { new f(); } catch (e) { log.push(e instanceof TypeError); }\n\
var AF = Object.getPrototypeOf(f).constructor;\n\
log.push(AF !== Function, typeof AF, Object.getPrototypeOf(AF) === Function);\n\
log.push(typeof this.AsyncFunction);\n\
var g = AF('a', 'return await a;');\n\
log.push(Object.getPrototypeOf(g) === Object.getPrototypeOf(f));\n\
g(5).then(function (v) { log.push(v); });\n\
log.push(String(async function h() { await 0; }));";
assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5");
}
#[test]
fn reflect_construct_rejects_an_async_function_as_new_target() {
let src = "async function f() {}\n\
var ran = false;\n\
function C() { ran = true; }\n\
try { Reflect.construct(C, [], f); } catch (e) { log.push(e instanceof TypeError); }\n\
log.push(ran);\n\
try { Reflect.construct(C, [], new Proxy(f, {})); } catch (e) { log.push(e instanceof TypeError); }";
assert_eq!(log(src), "true false true");
}
#[test]
fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_its_constructor() {
let mut r = Realm::new();
assert_eq!(r.run("Function.prototype.constructor = {}; 0"), Ok(JsValue::Number(0.0)));
r.add_es2015();
r.set_es2017(true);
let src = "var AF = Object.getPrototypeOf(async function () {}).constructor; Object.getPrototypeOf(AF) === Function && typeof AF.call";
assert_eq!(r.run(src), Ok(JsValue::String("function".into())));
}
#[test]
fn with_e4x_async_before_a_double_colon_is_a_qualified_name() {
let options = Options { es2017: true, e4x: true, ..Options::default() };
assert!(parse("async::b", &options).is_ok());
let mut r = Realm::with_options(options, Limits::default());
let src = "var async = new Namespace('u'); var x = <a xmlns:p='u'><p:b>7</p:b><b>8</b></a>; String(x.async::b)";
assert_eq!(r.run(src), Ok(JsValue::String("7".into())));
}
#[test]
fn await_is_an_identifier_outside_async_functions() {
let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\
var async = function (x) { return x; }; log.push(async(1));\n\
async\nfunction g() {}\n\
log.push(typeof g);";
assert_eq!(log(src), "3 1 function");
// A function in an async arrow function's parameters reads `await` as its own body does,
// and an async function declared in a script may be named `await`.
let nested = "var g = async (x = function () { return await; }) => x;\n\
var h = async (x = async function () { await 0; }) => x;\n\
async function await() { return 1; }\n\
log.push(typeof g, typeof h, typeof await);";
assert_eq!(log(nested), "function function function");
// An arrow function in an async arrow function's parameters reads `await` as its own body does.
let arrow = "var await = 7; var f = async (cb = () => await) => cb(); f().then(function (v) { log.push(v); });";
assert_eq!(log(arrow), "7");
let mut r = realm();
syntax_error(&mut r, "async function f() { var await; }");
syntax_error(&mut r, "async function f(await) {}");
syntax_error(&mut r, "async function f(x = await 1) {}");
syntax_error(&mut r, "function f() { await 1; }");
syntax_error(&mut r, "if (1) async function f() {}");
syntax_error(&mut r, "async (x = await 1) => x");
syntax_error(&mut r, "async\n(x) => x");
syntax_error(&mut r, "async (a = (...await) => {}) => {}");
}
#[test]
fn a_suspended_function_survives_a_collection_and_an_unreachable_one_is_freed() {
let mut r = realm();
r.run(
"var resume; var gate = new Promise(function (res) { resume = res; });\n\
var out = [];\n\
async function f() { var local = { n: 41 }; var v = await gate; out.push(local.n + v); }\n\
f();",
)
.unwrap();
r.interp().collect_garbage();
r.run("resume(1);").unwrap();
assert_eq!(r.run("out.join()").unwrap(), JsValue::String("42".into()));
// A function waiting on a promise nothing can settle is collected with it.
r.interp().collect_garbage();
let before = r.interp().heap.live_cells();
r.run("(function () { async function w() { var big = []; for (var i = 0; i < 200; i++) big.push({ i: i }); await new Promise(function () {}); } w(); })();")
.unwrap();
r.interp().collect_garbage();
let after = r.interp().heap.live_cells();
assert!(after < before + 50, "{before} {after}");
}
#[test]
fn a_run_that_ends_with_awaits_pending_ends_cleanly() {
let mut r = realm();
let v = r.run("async function f() { await new Promise(function () {}); return 1; } f(); 'done'").unwrap();
assert_eq!(v, JsValue::String("done".into()));
assert!(!r.is_running());
assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0));
}
#[test]
fn async_function_prototype_has_its_to_string_tag() {
let src = "var AFP = Object.getPrototypeOf(async function () {});\n\
var d = Object.getOwnPropertyDescriptor(AFP, Symbol.toStringTag);\n\
log.push(d.value, d.writable, d.enumerable, d.configurable, Object.prototype.toString.call(async function () {}));";
assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]");
}
#[test]
fn an_await_stays_within_the_heap_limit() {
// The activation, its two reactions, the derived promise and the suspended frame's bytes all
// fit in the heap limit, or the run stops at the `await`. The frame waits with 40 operands on
// a promise that never settles, so its bytes stay charged after the run. A suspension that
// went past the limit would be stopped only later, at the end of the run, so the largest
// heap that still stops the run must stop it at the `await`.
let operands: String = (0..40).map(|i| format!("{i}, ")).collect();
let setup =
format!("var gate = new Promise(function () {{}}); function g() {{ return 0; }} async function f() {{ return g({operands}await gate); }} 0");
let setup = setup.as_str();
let await_column = setup.find("await gate").map(|i| i + 1);
let run = "f(); 0";
let mut measure = realm();
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
let base = measure.collect_garbage();
assert_eq!(measure.run(run), Ok(JsValue::Number(0.0)));
let need = measure.interp().settled_heap_bytes().saturating_sub(base) + 1024;
let mut last_stop = None;
let mut over = Vec::new();
for spare in (0..=need).step_by(4) {
let mut r = realm();
assert_eq!(r.run(setup), Ok(JsValue::Number(0.0)));
let heap_bytes = r.collect_garbage() + spare;
r.set_limits(Limits { heap_bytes, ..Limits::default() });
let out = r.run(run);
match &out {
Ok(JsValue::Number(_)) => {}
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => last_stop = Some((spare, e.line, e.column)),
other => panic!("{spare}: {other:?}"),
}
let bytes = r.interp().settled_heap_bytes();
if out.is_ok() && bytes > heap_bytes {
over.push((spare, bytes - heap_bytes));
}
}
assert!(over.is_empty(), "runs that suspended past the limit (spare bytes, bytes over): {over:?}");
let Some((spare, line, column)) = last_stop else { panic!("no limit stopped the run") };
assert_eq!((line, usize::try_from(column).ok()), (1, await_column), "the run with {spare} spare bytes stopped away from the await");
}
/// The fewest frames with which `src` runs to its end.
fn fewest_frames(src: &str) -> usize {
for frames in 1..64 {
let mut r = Realm::with_options(Options { es2017: true, ..Options::default() }, Limits { frames, ..Limits::default() });
if r.run(src).is_ok() {
return frames;
}
}
panic!("{src} did not run");
}
#[test]
fn a_then_getter_on_a_returned_value_runs_after_the_async_frame_ends() {
let setup = "function rec(n) { return n ? rec(n - 1) : 0; }\n\
var o = { get then() { rec(5); return undefined; } };\n";
let direct = fewest_frames(&format!("{setup}o.then; 0"));
let returned = fewest_frames(&format!("{setup}async function f() {{ return o; }} f(); 0"));
assert_eq!(returned, direct);
// Returning the function's own promise rejects it with a TypeError.
let own = "async function f() { await 0; return p; } var p = f(); p.catch(function (e) { log.push(e instanceof TypeError); });";
assert_eq!(log(own), "true");
}
#[test]
fn an_async_arrow_head_reads_patterns_with_defaults_and_rejects_a_shorthand_await() {
let src = "var f = async ({a = 1}) => a; var g = async ({await: x}) => x; var h = async ([b = 2]) => b;\n\
Promise.all([f({}), g({ await: 3 }), h([])]).then(function (r) { log.push(r.join(',')); });";
assert_eq!(log(src), "1,3,2");
let mut r = realm();
syntax_error(&mut r, "var async = function () {}; async({a = 1});");
syntax_error(&mut r, "async ({await}) => 0");
syntax_error(&mut r, "async ({a = await}) => 0");
}
#[test]
fn each_resume_takes_fuel() {
let mut r = realm();
r.set_limits(Limits { fuel: 20_000, ..Limits::default() });
let e = r.run("async function f() { for (;;) await 0; } f();").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
}
#[test]
fn es5_and_extendscript_realms_do_not_read_async_functions() {
let mut es2015 = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
syntax_error(&mut es2015, "async function f() {}");
assert_eq!(es2015.run("var async = 1, await = 2; async + await").unwrap(), JsValue::Number(3.0));
syntax_error(&mut Realm::with_options(Options::default(), Limits::default()), "async function f() {}");
syntax_error(&mut Realm::new(), "var f = async () => 1;");
}
/// Starts `src` in a realm with `start`, calls `change` once the run has paused, runs it to its
/// end, and gives the run's value and the realm's options after it.
fn run_changing_language(src: &str, start: Options, change: impl FnOnce(&mut Realm)) -> (Result<JsValue, RunError>, Options) {
let mut realm = Realm::with_options(start, Limits::default());
if let Err(e) = realm.start(src) {
return (Err(e), realm.interp().options.clone());
}
match realm.advance(20) {
Ok(crate::Progress::Paused) => {}
other => panic!("{other:?}"),
}
change(&mut realm);
loop {
match realm.advance(1000) {
Ok(crate::Progress::Done(v)) => return (Ok(v), realm.interp().options.clone()),
Ok(_) => {}
Err(e) => return (Err(e), realm.interp().options.clone()),
}
}
}
#[test]
fn language_changes_during_a_run_apply_after_it_in_the_order_they_were_made() {
let src = "for (var i = 0; i < 200; i++) {} eval('(async function () {})'); 1";
let es2017 = Options { es2017: true, ..Options::default() };
let es2015 = Options { es2015: true, ..Options::default() };
let (v, o) = run_changing_language(src, es2017.clone(), |r| r.set_es2017(false));
assert_eq!(v, Ok(JsValue::Number(1.0)), "the run keeps async functions for the code it evaluates");
assert!(o.es2015 && !o.es2017, "{o:?}");
let (v, o) = run_changing_language(src, es2017.clone(), |r| {
r.set_es2015(false);
r.set_es2017(true);
});
assert_eq!(v, Ok(JsValue::Number(1.0)));
assert!(o.es2015 && o.es2017, "the later call wins: {o:?}");
let (v, o) = run_changing_language(src, es2017, |r| {
r.set_es2017(true);
r.set_es2015(false);
});
assert_eq!(v, Ok(JsValue::Number(1.0)));
assert!(!o.es2015 && !o.es2017, "turning es2015 off turns es2017 off: {o:?}");
let (v, o) = run_changing_language("for (var i = 0; i < 200; i++) {} 1", es2015, |r| r.set_es2017(true));
assert_eq!(v, Ok(JsValue::Number(1.0)));
assert!(o.es2015 && o.es2017, "{o:?}");
}
+18 -7
View File
@@ -14,6 +14,7 @@
//! run past [`crate::Limits`].
mod array;
mod async_function;
pub(crate) mod binary;
pub(crate) mod collections;
pub(crate) mod extensions;
@@ -250,6 +251,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
method(interp, object_proto, "propertyIsEnumerable", property_is_enumerable, 1)?;
let function = native(interp, "Function", function_ctor, 1, NativeKind::Plain, true)?;
interp.intrinsics.function_ctor = function;
constructor(interp, "Function", function, function_proto)?;
let call = native(interp, "call", unreachable_native, 1, NativeKind::Call, false)?;
data(interp, function_proto, "call", Value::Object(call), HIDDEN)?;
@@ -670,13 +672,21 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b
/// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as
/// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function.
fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
create_dynamic_function(interp, args, false)
create_dynamic_function(interp, args, false, false)
}
/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with
/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`.
pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult<Value> {
let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" };
/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function`, with
/// `generator` for `GeneratorFunction`, whose source is read as `(function* anonymous(…`, and with
/// `is_async` for `AsyncFunction` (ECMA-262 2017 section 25.5.1.1), whose source is read as
/// `(async function anonymous(…`. An async function's source is read with
/// [`crate::Options::es2017`] whatever the realm reads scripts with, since only an async function
/// leads a script to `AsyncFunction`.
pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool, is_async: bool) -> JsResult<Value> {
let head: &str = match (generator, is_async) {
(true, _) => "(function* anonymous(",
(false, true) => "(async function anonymous(",
(false, false) => "(function anonymous(",
};
const MID: &str = "\n) {\n";
const TAIL: &str = "\n})";
let mut parts = Vec::with_capacity(args.len());
@@ -706,14 +716,15 @@ pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], gener
interp.observe_code(&units);
interp.source_units = interp.source_units.saturating_add(units.len());
let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len()));
let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() };
let es2017 = interp.options.es2017 || is_async;
let options = crate::Options { strict: false, max_source_units: remaining, es2017, ..interp.options.clone() };
let program = match crate::parse_utf16(&units, &options) {
Ok(p) => p,
Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)),
};
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() });
let code = match compile_constructed_function(&program, &source) {
Ok(Some(code)) if code.generator == generator => code,
Ok(Some(code)) if code.generator == generator && code.is_async == is_async => code,
Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")),
Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)),
Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)),
+40
View File
@@ -0,0 +1,40 @@
//! `AsyncFunction` and its prototype (ECMA-262 2017 section 25.5,
//! <https://262.ecma-international.org/8.0/#sec-async-function-objects>), in realms with
//! [`crate::Options::es2015`]: the prototype of every async function, and the constructor a script
//! reaches through it. `AsyncFunction` is not a global.
use super::{create_dynamic_function, data, native};
use crate::heap::{CONFIGURABLE, Class, NativeKind, Object, Prop};
use crate::interp::{Interp, JsResult};
use crate::value::Value;
/// Creates `AsyncFunction` and `AsyncFunction.prototype`, keeping the prototype for the async
/// functions the realm makes.
pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
let function_proto = interp.intrinsics.function_proto;
let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto)));
interp.promises.async_function_proto = Some(proto);
let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?;
interp.promises.async_function_ctor = Some(ctor);
// The built-in `Function` is the constructor's prototype (section 25.5.2), even after a
// script has replaced `Function.prototype.constructor`.
let function_ctor = interp.intrinsics.function_ctor;
if let Some(o) = interp.heap.object_mut(ctor) {
o.proto = Some(function_ctor);
}
data(interp, ctor, "prototype", Value::Object(proto), 0)?;
// Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary
// built-in prototypes.
data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE)?;
// `AsyncFunction.prototype[@@toStringTag]` is "AsyncFunction", configurable only (section
// 25.5.3.2).
if let Some(tag) = interp.well_known(|w| &w.to_string_tag) {
interp.define_sym(proto, tag, Prop::Data { value: Value::str("AsyncFunction"), flags: CONFIGURABLE })?;
}
Ok(())
}
/// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1).
fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
create_dynamic_function(interp, args, false, true)
}
+1 -1
View File
@@ -47,5 +47,5 @@ pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> {
/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1).
fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
super::create_dynamic_function(interp, args, true)
super::create_dynamic_function(interp, args, true, false)
}
+158 -7
View File
@@ -145,6 +145,8 @@ enum Then {
Settle(ObjId, Option<Site>),
/// An exception rejects through this resolving record.
Reject(ObjId),
/// An async function goes on after `await`; its own promise takes its result.
Resume,
/// The call was a `finally` callback that a reaction job runs in place of the Then Finally or
/// Catch Finally function: `derived` is settled as that function's result settles it.
Finally { derived: ObjId, value: Value, throws: bool },
@@ -162,9 +164,11 @@ enum Kind {
CatchFinally,
ValueThunk,
Thrower,
AwaitFulfilled,
AwaitRejected,
}
const KINDS: [(Kind, NativeFn); 9] = [
const KINDS: [(Kind, NativeFn); 11] = [
(Kind::Resolve, resolve_function),
(Kind::Reject, reject_function),
(Kind::AllElement, all_element),
@@ -174,6 +178,8 @@ const KINDS: [(Kind, NativeFn); 9] = [
(Kind::CatchFinally, catch_finally),
(Kind::ValueThunk, value_thunk),
(Kind::Thrower, thrower),
(Kind::AwaitFulfilled, await_continuation),
(Kind::AwaitRejected, await_continuation),
];
/// `Promise`'s objects and the run's job queue.
@@ -192,11 +198,17 @@ pub(crate) struct Promises {
rejected: Vec<ObjId>,
/// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower).
pub(crate) max_jobs: usize,
/// `AsyncFunction.prototype` (ECMA-262 2017 section 25.5.3), the prototype of async functions.
pub(crate) async_function_proto: Option<ObjId>,
/// `AsyncFunction` (section 25.5.1), which is not a global.
pub(crate) async_function_ctor: Option<ObjId>,
}
impl Default for Promises {
fn default() -> Self {
Self {
async_function_proto: None,
async_function_ctor: None,
proto: None,
ctor: None,
natives: Vec::new(),
@@ -214,6 +226,7 @@ impl Promises {
/// Adds what the queue and the promise objects hold to the collector's roots.
pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) {
roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected));
roots.objects.extend(self.async_function_proto.iter().chain(&self.async_function_ctor));
roots.values.extend(self.completion.iter());
match &self.running {
Some(Then::Settle(o, site)) => {
@@ -225,7 +238,7 @@ impl Promises {
roots.objects.push(*derived);
roots.values.push(value);
}
None => {}
Some(Then::Resume) | None => {}
}
for job in &self.queue {
match job {
@@ -282,7 +295,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
let n = native(interp, "", f, 1, NativeKind::Plain, false)?;
interp.promises.natives.push(n);
}
Ok(())
super::async_function::install(interp)
}
/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global
@@ -575,6 +588,140 @@ fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult<Value>
})
}
// ---- async functions ----
/// The built-in a suspended async function's reactions are bound to. The job queue resumes the
/// function instead of calling it, and scripts cannot reach it.
fn await_continuation(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
Err(Abrupt::Internal("an await continuation was called".into()))
}
impl Interp {
/// Settles the promise of an async function whose frame ends: its return value resolves it,
/// and the exception that leaves it rejects it.
pub(crate) fn settle_async(&mut self, p: ObjId, r: Result<Value, Value>) -> JsResult<()> {
match r {
Ok(v) => resolve_promise(self, p, v),
Err(e) => {
let site = caught(self);
reject_promise(self, p, e, site)
}
}
}
/// Resolves the promise of an async function whose frame has returned `v` and is already off
/// the frames. Returning the promise itself rejects it with a `TypeError` at `site`, the
/// return.
pub(crate) fn resolve_async_return(&mut self, p: ObjId, v: Value, site: Option<Site>) -> JsResult<()> {
if matches!(v, Value::Object(o) if o == p) {
return scoped(self, |interp| {
root(interp, &Value::Object(p));
let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself");
root(interp, &e);
reject_promise(interp, p, e, site)
});
}
resolve_promise(self, p, v)
}
/// A new pending promise for the async function call whose frame is on top.
pub(crate) fn new_async_promise(&mut self) -> JsResult<ObjId> {
new_promise(self)
}
/// `await v` in the async function the top frame runs (Await, ECMA-262 2017 section 6.2.3.1,
/// with PromiseResolve as later editions have it): `v` becomes a built-in promise, the frame
/// is suspended until it settles, and the function's call gives its promise, `Some` when the
/// frame was the boundary frame. Throws at the `await` when reading `v`'s `constructor` throws.
pub(crate) fn await_value(&mut self, v: Value) -> JsResult<Option<Value>> {
if self.async_promise().is_none() {
return Err(Abrupt::Internal("await outside an async function".into()));
}
let ctor = self.promises.ctor.map_or(Value::Undefined, Value::Object);
scoped(self, |interp| {
let p = promise_resolve(interp, &ctor, v)?;
root(interp, &p);
let Value::Object(p) = p else { return Err(Abrupt::Internal("PromiseResolve gave a value that is not a promise".into())) };
let bytes = interp.suspend_bytes();
interp.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?;
let act = interp.heap.alloc_object(Object::new(Class::Activation(None), None));
root(interp, &Value::Object(act));
let on_fulfilled = record_function(interp, Kind::AwaitFulfilled, act, 1)?;
root(interp, &on_fulfilled);
let on_rejected = record_function(interp, Kind::AwaitRejected, act, 1)?;
root(interp, &on_rejected);
// The reactions settle no promise of their own; this one stays pending and unseen.
let derived = new_promise(interp)?;
root(interp, &Value::Object(derived));
promise_data(interp, derived)?.handled = true;
// The allocations above used up the room checked for at the start, so the reaction or
// job and the frame's bytes are checked again, with the frame still on top, before the
// awaited promise gets its reaction.
let then_bytes = if promise_data(interp, p)?.state == State::Pending { REACTION_BYTES } else { JOB_BYTES };
interp.reserve_heap(then_bytes.saturating_add(bytes))?;
perform_then(interp, p, on_fulfilled, on_rejected, derived)?;
let (a, boundary) = interp.suspend_frame()?;
let promise = a.promise;
let held = a.bytes();
if let Some(o) = interp.heap.object_mut(act) {
o.class = Class::Activation(Some(Box::new(a)));
}
interp.heap.bytes = interp.heap.bytes.saturating_add(held);
if boundary {
return Ok(Some(Value::Object(promise)));
}
interp.push(Value::Object(promise))?;
Ok(None)
})
}
/// The activation `handler` resumes when it is a suspended async function's reaction, and
/// whether it is the rejection's.
fn await_activation(&self, handler: &Value) -> Option<(ObjId, bool)> {
let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) else {
return None;
};
let reject = if self.promises.natives.get(Kind::AwaitFulfilled as usize) == Some(target) {
false
} else if self.promises.natives.get(Kind::AwaitRejected as usize) == Some(target) {
true
} else {
return None;
};
match args.first() {
Some(Value::Object(act)) => Some((*act, reject)),
_ => None,
}
}
/// Resumes the async function `handler` belongs to with the settled value: its frame goes back
/// on top as a boundary frame the caller runs, and a rejection is thrown at its `await`. A job
/// that finds the frame already resumed does nothing.
fn resume_async(&mut self, handler: &Value, argument: Value, reject: bool, site: Option<Site>) -> JsResult<()> {
let Some((act, _)) = self.await_activation(handler) else { return Err(Abrupt::Internal("not an await reaction".into())) };
let taken = match self.heap.object_mut(act).map(|o| &mut o.class) {
Some(Class::Activation(slot)) => slot.take(),
_ => return Err(Abrupt::Internal("an await reaction lost its activation".into())),
};
let Some(a) = taken else { return Ok(()) };
self.heap.bytes = self.heap.bytes.saturating_sub(a.bytes());
self.restore_frame(*a)?;
self.promises.running = Some(Then::Resume);
if !reject {
return self.push(argument);
}
if site.is_some() {
self.throw_site = site;
}
match self.unwind_or_abort(argument) {
Ok(Some(v)) => self.finish_job(Ok(v)),
Ok(None) => Ok(()),
Err(Abrupt::Throw(e)) => self.finish_job(Err(e)),
Err(e) => Err(e),
}
}
}
// ---- the job queue ----
impl Interp {
@@ -660,6 +807,10 @@ impl Interp {
self.use_fuel()?;
scoped(self, |interp| {
let (f, this, args, then) = match job {
Job::Reaction { handler, argument, reject, site, .. } if interp.await_activation(&handler).is_some() => {
root(interp, &argument);
return interp.resume_async(&handler, argument, reject, site);
}
Job::Reaction { handler, argument, reject, derived, site } => {
if !interp.is_callable(&handler) {
return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) };
@@ -700,7 +851,7 @@ impl Interp {
match (then, r) {
(Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v),
(Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site),
(Then::Reject(_), Ok(_)) => Ok(()),
(Then::Reject(_), Ok(_)) | (Then::Resume, _) => Ok(()),
(Then::Reject(rec), Err(e)) => scoped(self, |interp| {
root(interp, &Value::Object(rec));
reject_through(interp, rec, e, site)
@@ -935,8 +1086,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<V
}
/// `v` is a constructor: a function written in JavaScript other than an arrow function, generator
/// function or method, a built-in or registered host constructor, or a bound function whose target
/// is one.
/// function, async function or method, a built-in or registered host constructor, or a bound
/// function whose target is one.
fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult<bool> {
let mut v = v.clone();
loop {
@@ -945,7 +1096,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult<bool> {
_ => return Ok(false),
};
match func {
Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator),
Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator && !code.is_async),
Func::Native { constructor, .. } => return Ok(constructor),
Func::Data { read: ArgRead::Hosted, .. } => return Ok(v.as_object().is_some_and(|o| interp.is_constructible_host_class(o))),
Func::Bound { target, .. } => {
+11 -1
View File
@@ -334,6 +334,9 @@ pub(crate) enum Op {
DelegateResult(u32),
/// `mode value` → `value`; for `return`, jumps with it.
DelegateDone(u32),
/// `value` → its awaited value: suspends the running async function until the value settles,
/// and goes on with its fulfillment value or throws its rejection reason here.
Await,
}
/// The names a block declares, entered with [`Op::PushBlock`].
@@ -406,6 +409,11 @@ pub(crate) struct Code {
pub(crate) vars: Vec<Key>,
/// Function declarations to instantiate on entry: their names and indices in `functions`.
pub(crate) fun_decls: Vec<(Key, u32)>,
/// In script and eval code, the variables of block functions (Annex B.3.3.2 and B.3.3.3) that
/// the code does not declare otherwise: each is declared, and its function assigned to it, only
/// when no `let`, `const` or block function between the code and its variable environment has
/// the name and the variable can be declared.
pub(crate) annex_vars: Vec<Key>,
/// The body refers to `arguments` or calls `eval`.
pub(crate) uses_arguments: bool,
pub(crate) source: Rc<Source>,
@@ -453,6 +461,8 @@ pub(crate) struct Code {
/// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]),
/// and it is not a constructor.
pub(crate) generator: bool,
/// The code is an async function's: a call returns a promise, and it may run [`Op::Await`].
pub(crate) is_async: bool,
/// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the
/// rules of the function's body, of the code around an arrow function, or those eval code was
/// read with (ECMA-262 2015 section 18.2.1.1).
@@ -596,7 +606,7 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::SuperCall(n) => e(n.checked_add(1).ok_or("operand too large")?, 1),
Op::SuperCallSpread => e(2, 1),
Op::BindThis => e(1, 1),
Op::ToStr | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1),
Op::ToStr | Op::Await | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1),
Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] },
Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?),
Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?),
+2 -1
View File
@@ -155,7 +155,7 @@ impl Interp {
return p.constructor;
}
match self.func_of(&v) {
Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator),
Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator || code.is_async),
Some(Func::Native { constructor, .. }) => return constructor,
Some(Func::Data { read: crate::host::ArgRead::Hosted, .. }) => return v.as_object().is_some_and(|o| self.is_host_constructor(o)),
Some(Func::Bound { target, .. }) => v = Value::Object(target),
@@ -320,6 +320,7 @@ impl Interp {
match self.func_of(&f) {
Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")),
Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")),
Some(Func::Closure { code, .. }) if code.is_async => Err(self.type_error("an async function is not a constructor")),
Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")),
Some(Func::Closure { code, env }) if code.derived => {
self.stack.truncate(start);
+27 -6
View File
@@ -124,6 +124,9 @@ struct FnCompiler<'a> {
struct Hoisted {
vars: Vec<Key>,
fun_decls: Vec<(Key, u32)>,
/// The names of block functions (Annex B.3.3) that are neither a `var` nor a function at the
/// top of the body.
annex_vars: Vec<Key>,
}
fn key_of(name: &str) -> Key {
@@ -273,7 +276,8 @@ impl<'a> FnCompiler<'a> {
/// hoisted; one in a block is instantiated when the block is entered, and outside strict mode
/// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with
/// a `let` or a `const` of the body or of a block or loop around the declaration, or with a
/// function of a block around the one that holds it.
/// function of a block around the one that holds it. Such a name that the body does not also
/// declare with `var` or as a function at its top goes in [`Hoisted::annex_vars`].
fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult<Hoisted> {
let mut out = Hoisted::default();
let mut seen = HashSet::new();
@@ -290,6 +294,7 @@ impl<'a> FnCompiler<'a> {
}
};
let mut annex: Vec<(Key, usize, StmtId)> = Vec::new();
let mut annex_seen = HashSet::new();
while let Some((id, nested, scope)) = work.pop() {
let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") };
let inner = self.es2015;
@@ -301,13 +306,15 @@ impl<'a> FnCompiler<'a> {
Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))),
Stmt::Lexical(..) | Stmt::Class(_) => {}
Stmt::FunctionDecl(fid) => {
let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else {
let Some(f) = self.ast.function(*fid) else { return internal("function out of range") };
let Some(name) = f.name.as_ref() else {
return internal("function declaration without a name");
};
let k = key_of(&name.name);
if self.es2015 && nested {
// Annex B.3.3 gives plain function declarations only a var binding too.
if !self.strict && !generator {
// Annex B.3.3 gives plain function declarations a variable, not generator
// or async ones.
if !self.strict && !f.generator && !f.is_async {
annex.push((k, scope, id));
}
} else {
@@ -415,7 +422,9 @@ impl<'a> FnCompiler<'a> {
}
if !clash {
self.annex.insert(id);
add_var(&mut out, k);
if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) {
out.annex_vars.push(k);
}
}
}
Ok(out)
@@ -1396,6 +1405,11 @@ impl<'a> FnCompiler<'a> {
self.uses_new_target = true;
self.emit(Op::NewTarget);
}
Expr::Await(arg) => {
self.expr(*arg)?;
self.at(self.ast.expr_span(id).start);
self.emit(Op::Await);
}
Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?,
Expr::Unary { .. } => self.unary(id)?,
Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?,
@@ -2400,6 +2414,7 @@ impl<'a> FnCompiler<'a> {
params: meta.params,
vars: hoisted.vars,
fun_decls: hoisted.fun_decls,
annex_vars: hoisted.annex_vars,
uses_arguments: self.uses_arguments,
source: self.source.clone(),
span: meta.span,
@@ -2419,6 +2434,7 @@ impl<'a> FnCompiler<'a> {
own_name: meta.own_name,
method: meta.method,
generator: self.generator,
is_async: meta.is_async,
supers: self.supers,
};
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
@@ -2443,6 +2459,7 @@ struct Meta {
pattern_names: Vec<Key>,
own_name: Option<Key>,
method: bool,
is_async: bool,
}
fn len_u32(n: usize) -> u32 {
@@ -2478,7 +2495,10 @@ pub(crate) fn compile_function(
let rest = f.rest.as_ref().map(|r| param_key(&c, f.params.len(), r));
let pattern_names: Vec<Key> = f.params.iter().chain(&f.rest).filter(|p| matches!(p, Binding::Pattern(_))).flat_map(|p| c.bound_keys(p)).collect();
let all_params: Vec<Key> = f.params.iter().chain(&f.rest).flat_map(|p| c.bound_keys(p)).collect();
let hoisted = c.hoist(&f.body, &all_params)?;
let mut hoisted = c.hoist(&f.body, &all_params)?;
// A function's block functions always have their variable (Annex B.3.3.1).
let annex = std::mem::take(&mut hoisted.annex_vars);
hoisted.vars.extend(annex);
let top_scope = c.list_scope(&f.body, false)?;
// Default values are expressions (ContainsExpression, ECMA-262 2015 section 14.1.5), and a
// destructured parameter is bound by code of its own: a rest parameter alone leaves the
@@ -2551,6 +2571,7 @@ pub(crate) fn compile_function(
}),
method: (f.home && !f.is_class_constructor())
|| (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)),
is_async: f.is_async,
};
c.finish(hoisted, meta)
}
+137
View File
@@ -181,6 +181,28 @@ fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() {
truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1");
}
#[test]
fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() {
// A block function of a script or of eval code gets no variable when a `let`, a `const` or a
// block function out to the variable environment has its name, or when the global object
// cannot take it (Annex B.3.3.2 and B.3.3.3); its block still has it, and a `var` of the name
// is still a SyntaxError.
let mut realm = es();
assert_eq!(realm.run("let f = 1; 0"), Ok(JsValue::Number(0.0)));
assert_eq!(realm.run("var inner; { function f() { return 2; } inner = f(); } inner + f"), Ok(JsValue::Number(3.0)));
assert!(is_thrown(&realm.run("{ function f() {} } var f;"), "SyntaxError"));
assert_eq!(realm.run("(0, eval)('{ function f() { return 4; } }'); f"), Ok(JsValue::Number(1.0)));
truth("function t() { let h = 1; { eval('{ function h() { return 2; } }'); } return h; } t() === 1");
truth("function t() { let h = 1; eval('{ function h() {} }'); return h; } t() === 1");
// A `catch` parameter does not stop the variable (Annex B.3.5).
truth("try { throw 1; } catch (c) { eval('{ function c() { return 5; } }'); } c() === 5");
let mut realm = es();
assert_eq!(realm.run("var out; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0)));
let kept = realm.run("{ function n() { return 6; } out = n(); } out + typeof n");
assert_eq!(kept, Ok(JsValue::String("6undefined".into())));
assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into())));
}
#[test]
fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() {
truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0");
@@ -333,6 +355,17 @@ fn a_global_var_makes_its_own_property_over_an_inherited_one() {
assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true)));
}
#[test]
fn a_var_an_inherited_property_declared_does_not_stop_a_later_let() {
// Without the option, `var x` uses the inherited `x` and makes no own property, so a later
// run with the option may declare `x` with `let`.
let mut realm = Realm::new();
assert_eq!(realm.run("Object.prototype.x = 1; 0"), Ok(JsValue::Number(0.0)));
assert_eq!(realm.run("var x; delete this.x"), Ok(JsValue::Bool(true)));
realm.set_es2015(true);
assert_eq!(realm.run("let x = 2; x"), Ok(JsValue::Number(2.0)));
}
#[test]
fn a_global_function_that_cannot_be_declared_declares_nothing() {
let mut realm = es();
@@ -454,6 +487,38 @@ fn a_global_var_that_cannot_be_declared_declares_nothing() {
assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0)));
}
#[test]
fn a_script_stopped_by_the_frame_limit_declares_no_let() {
let mut realm = Realm::with_options(es_options(), Limits { frames: 0, ..Limits::default() });
let stopped = realm.run("let early = 1; const fixed = 2;");
assert!(matches!(&stopped, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Frames)), "{stopped:?}");
realm.set_limits(Limits::default());
assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)));
}
#[test]
fn a_script_stopped_by_the_heap_limit_declares_no_let() {
// The `let` and `const` names of a script go in before its functions are made; a heap too
// small for both stops the script before any name is declared.
let lets: String = (0..200).map(|i| format!("let a_long_lexical_name_{i} = {i}; ")).collect();
let decls: String = (0..40).map(|i| format!("function f{i}() {{ return {i}; }} ")).collect();
let src = format!("let early = 1; const fixed = 2; {lets}{decls}");
let mut stopped = 0;
for spare in (40_000..200_000).step_by(97) {
let mut realm = es();
let live = realm.collect_garbage();
realm.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() });
match realm.run(&src) {
Ok(_) => continue,
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => stopped += 1,
Err(e) => panic!("{spare}: {e:?}"),
}
realm.set_limits(Limits::default());
assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)), "{spare}");
}
assert!(stopped > 0);
}
#[test]
fn eval_code_keeps_its_let_and_const_to_itself() {
truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'");
@@ -866,6 +931,37 @@ fn spread_stops_at_the_heap_limit_before_the_next_step_runs() {
}
}
#[test]
fn a_template_object_stays_within_the_heap_limit() {
// The template object's two arrays, the index name of each string and the `raw` property are
// reserved before they are made, so the heap stays within each limit tried.
let setup = "function t(s) { return s.length; } 0";
let run = format!("t`{}`", (0..10).map(|i| format!("p{i}${{{i}}}")).collect::<String>());
let mut measure = Realm::with_options(es_options(), Limits::default());
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
measure.interp().collect_garbage();
let base = measure.interp().heap.bytes;
assert_eq!(measure.run(&run), Ok(JsValue::Number(11.0)));
let need = measure.interp().settled_heap_bytes() - base;
let mut stopped = 0;
for heap_bytes in (base..=base + need).step_by(4) {
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
if realm.run(setup).is_err() {
continue;
}
realm.interp().collect_garbage();
let r = realm.run(&run);
stopped += usize::from(r.is_err());
assert!(
matches!(&r, Ok(JsValue::Number(_))) || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)),
"{heap_bytes}: {r:?}"
);
let bytes = realm.interp().settled_heap_bytes();
assert!(bytes <= heap_bytes, "{bytes} > {heap_bytes}");
}
assert!(stopped > 0, "no limit stopped the run");
}
#[test]
fn spreading_other_values_is_a_type_error() {
throws("[...1];", "TypeError");
@@ -972,6 +1068,47 @@ fn spreading_a_rope_counts_its_flattened_length_first() {
assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel");
}
#[test]
fn spreading_a_string_counts_the_string_it_makes_for_each_character() {
// Each of the 16,384 elements is a property and a one-character string of its own. The
// smaller heap has room for the properties alone but not for the strings as well, so the
// spread stops with the heap limit. The larger heap holds the array, its keys and the
// strings. The spread steps the string's iterator, so the fuel is set well above what it
// takes.
const N: usize = 16_384;
let property = crate::heap::PROP_BYTES;
let string = crate::heap::string_bytes(1);
let setup = "var s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s[0]; 0";
let cases = [(property + string / 2, N * 1000, Err(LimitKind::Heap)), (2 * (property + string) + 8, N * 1000, Ok(N as f64))];
for (per_element, fuel, expected) in cases {
let mut r = es();
assert_eq!(r.run(setup), Ok(JsValue::Number(0.0)));
r.interp().collect_garbage();
let heap_bytes = r.interp().heap.bytes + N * per_element;
r.set_limits(Limits { heap_bytes, fuel: fuel as u64, ..Limits::default() });
match (r.run("var a = [...s]; a.length"), expected) {
(Ok(JsValue::Number(n)), Ok(m)) if n == m => {}
(Err(e), Err(kind)) if e.kind == RunErrorKind::Limit(kind) => {}
(result, expected) => panic!("{per_element} bytes for each element: {result:?}, expected {expected:?}"),
}
}
}
#[test]
fn the_strings_a_string_spread_makes_stay_counted_while_the_array_holds_them() {
const N: u32 = 4096;
let mut r = es();
assert_eq!(r.run("var s = 'x'; for (var i = 0; i < 12; i++) s = s + s; s[0]; 0"), Ok(JsValue::Number(0.0)));
r.interp().collect_garbage();
let before = r.interp().heap.bytes;
assert_eq!(r.run("var a = [...s]; a.length"), Ok(JsValue::Number(f64::from(N))));
// Takes the bytes the spread held while it ran off the estimate.
r.interp().reserve_heap(0).unwrap();
let element = |i: u32| crate::heap::PROP_BYTES + crate::heap::string_bytes(i.to_string().len()) + crate::heap::string_bytes(1);
let least = before + (0..N).map(element).sum::<usize>();
assert!(r.interp().heap.bytes >= least, "{} < {least}", r.interp().heap.bytes);
}
#[test]
fn a_rest_parameter_checks_the_heap_before_its_array_is_made() {
// The 20,000 arguments fit in the room left over, and the rest array of them does not, so
+3 -1
View File
@@ -18,7 +18,7 @@ use crate::LimitKind;
use crate::builtins::iterator::iter_result;
use crate::bytecode::Code;
use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key};
use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal};
use crate::interp::{Abrupt, AnnexOff, Frame, Interp, JsResult, Prepared, ThrowSite, internal};
use crate::value::Value;
/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4).
@@ -305,6 +305,8 @@ impl Interp {
completion,
boundary,
generator: Some(generator),
async_promise: None,
annex_off: AnnexOff::new(),
chained: false,
pending_module: false,
});
+22 -2
View File
@@ -301,6 +301,8 @@ pub(crate) enum Class {
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>),
/// An async function's frame waiting at `await`, until it is resumed; scripts never see it.
Activation(Option<Box<crate::interp::async_function::Activation>>),
/// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added.
Map(Box<Coll>),
/// A `Set` (section 23.2): its values in the order they were added, each with `undefined`.
@@ -609,7 +611,7 @@ impl Class {
Class::XmlList(_) => "XMLList",
Class::Namespace(_) => "Namespace",
Class::QName { .. } => "QName",
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object",
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) | Class::Activation(_) => "Object",
Class::Promise(_) => "Promise",
Class::Math => "Math",
Class::Json => "JSON",
@@ -1105,6 +1107,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
+ code.params.len()
+ code.pattern_names.len()
+ code.vars.len()
+ code.annex_vars.len()
+ 2 * code.fun_decls.len()
+ code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::<usize>();
let tables = code.finally_tables.iter().map(|t| 24 + 4 * t.len()).sum::<usize>();
@@ -1128,7 +1131,14 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
strings.add(pattern);
strings.add(flags);
}
let keys = code.names.iter().chain(&code.params).chain(&code.pattern_names).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
let keys = code
.names
.iter()
.chain(&code.params)
.chain(&code.pattern_names)
.chain(&code.vars)
.chain(&code.annex_vars)
.chain(code.fun_decls.iter().map(|(k, _)| k));
for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) {
strings.add_key(k);
}
@@ -1298,6 +1308,16 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
}
extra = crate::builtins::promise::RECORD_BYTES;
}
Class::Activation(Some(a)) => {
for v in a.values() {
mark_value(v, work, strings);
}
work.extend(a.ids());
for code in a.codes() {
mark_code(code, strings);
}
extra = a.bytes();
}
_ => {}
}
OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra
+207 -28
View File
@@ -123,6 +123,9 @@ impl ErrorType {
pub(crate) struct Intrinsics {
pub(crate) object_proto: ObjId,
pub(crate) function_proto: ObjId,
/// The built-in `Function`, which a script can replace as the global or as the prototype's
/// `constructor`.
pub(crate) function_ctor: ObjId,
pub(crate) array_proto: ObjId,
pub(crate) string_proto: ObjId,
pub(crate) number_proto: ObjId,
@@ -150,6 +153,7 @@ impl Intrinsics {
Self {
object_proto: o,
function_proto: o,
function_ctor: o,
array_proto: o,
string_proto: o,
number_proto: o,
@@ -186,6 +190,7 @@ impl Intrinsics {
let mut v = vec![
self.object_proto,
self.function_proto,
self.function_ctor,
self.array_proto,
self.string_proto,
self.number_proto,
@@ -207,6 +212,9 @@ impl Intrinsics {
}
}
/// The names of [`Frame::annex_off`], looked up once for each block function a frame assigns.
pub(crate) type AnnexOff = std::collections::HashSet<Key>;
pub(crate) struct Frame {
pub(crate) code: Rc<Code>,
pub(crate) pc: usize,
@@ -236,6 +244,12 @@ pub(crate) struct Frame {
pub(crate) boundary: bool,
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
pub(crate) generator: Option<ObjId>,
/// The promise of the async function the frame runs: a return resolves it, an exception
/// that leaves the frame rejects it, and the call's value is the promise.
pub(crate) async_promise: Option<ObjId>,
/// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not
/// declared: [`Op::AnnexB`] leaves them alone.
pub(crate) annex_off: AnnexOff,
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
@@ -246,6 +260,8 @@ pub(crate) struct Frame {
/// Where the exception being thrown was raised: the code and the instruction.
pub(crate) type ThrowSite = (Rc<Code>, usize);
pub(crate) mod async_function;
/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time.
pub(crate) type CodeObserver = Rc<dyn Fn(&[u16])>;
@@ -330,6 +346,10 @@ pub(crate) struct Interp {
/// ECMAScript 2015 gives them ([`crate::builtins::es2015_names`]): set once the realm first
/// reads code with [`Options::es2015`], and kept after that.
pub(crate) builtin_names: bool,
/// The [`Options::es2017`] a host set while a run was going, for the runs after it. It is
/// applied after [`Self::next_es2015`], and the setters keep the two consistent with the
/// order they were called in.
pub(crate) next_es2017: Option<bool>,
/// The template objects tagged templates have made, by code and template index, each with
/// its code (ECMA-262 2015 section 12.2.9.3 keeps one object for each site).
pub(crate) template_objects: std::collections::HashMap<(usize, u32), (Rc<Code>, ObjId)>,
@@ -675,7 +695,7 @@ fn declaration_bytes(code: &Code) -> usize {
let closure = code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f));
total.saturating_add(binding_bytes(name.len()) + closure)
});
code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len())))
code.vars.iter().chain(&code.annex_vars).fold(funs, |total, v| total.saturating_add(binding_bytes(v.len())))
}
/// At least the bytes that [`Interp::block_env`] adds to the heap for `code.scopes[i]`: the
@@ -754,7 +774,8 @@ fn is(k: &[u16], s: &str) -> bool {
}
impl Interp {
pub(crate) fn new(options: Options, limits: Limits) -> Self {
pub(crate) fn new(mut options: Options, limits: Limits) -> Self {
options.es2015 = options.modern();
let mut heap = Heap::default();
let global = heap.alloc_object(Object::new(Class::Ordinary, None));
let global_env = heap.alloc_env(Env::Obj { object: global, with_this: false, outer: None });
@@ -774,6 +795,7 @@ impl Interp {
next_es2015: None,
es2015_installed: false,
builtin_names: false,
next_es2017: None,
template_objects: std::collections::HashMap::new(),
intrinsics: Intrinsics::placeholder(),
fuel: u64::MAX,
@@ -1074,7 +1096,9 @@ impl Interp {
for f in &self.frames {
roots.values.push(&f.this);
roots.values.push(&f.completion);
roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()).chain(f.generator.iter()));
roots
.objects
.extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()).chain(f.generator.iter()).chain(f.async_promise.iter()));
roots.envs.extend(f.this_env);
roots.envs.push(f.env);
roots.envs.push(f.var_env);
@@ -1119,7 +1143,11 @@ impl Interp {
match self.step() {
Ok(Some(v)) => return Ok(v),
Ok(None) => {}
Err(Abrupt::Throw(v)) => self.unwind(v)?,
Err(Abrupt::Throw(v)) => {
if let Some(v) = self.unwind_or_abort(v)? {
return Ok(v);
}
}
Err(other) => {
self.note_site();
self.abort_to_boundary();
@@ -1138,7 +1166,11 @@ impl Interp {
match self.step() {
Ok(Some(v)) => return Ok(Some(v)),
Ok(None) => {}
Err(Abrupt::Throw(v)) => self.unwind(v)?,
Err(Abrupt::Throw(v)) => {
if let Some(v) = self.unwind_or_abort(v)? {
return Ok(Some(v));
}
}
Err(other) => {
self.note_site();
self.abort_to_boundary();
@@ -1184,10 +1216,26 @@ impl Interp {
}
Op::GeneratorStart => self.op_generator_start(),
Op::Yield(raw) => self.op_yield(raw),
Op::Await => {
let v = self.pop()?;
self.await_value(v)
}
_ => self.exec(op).map(|()| None),
}
}
/// [`Self::unwind`], ending the frames down to the boundary frame when it fails with a limit
/// or an internal error, which leaves the frame it was in on top.
pub(crate) fn unwind_or_abort(&mut self, v: Value) -> JsResult<Option<Value>> {
match self.unwind(v) {
Err(e @ (Abrupt::Limit(_) | Abrupt::Internal(_))) => {
self.abort_to_boundary();
Err(e)
}
r => r,
}
}
fn note_site(&mut self) {
if self.throw_site.is_none()
&& let Some(f) = self.frames.last()
@@ -1198,7 +1246,10 @@ impl Interp {
/// Finds the handler for an exception: in the top frame, or in the frames below it up to the
/// boundary frame. Returns the exception when no handler takes it before the boundary frame.
fn unwind(&mut self, v: Value) -> JsResult<()> {
/// An async function's frame without a handler rejects its promise with the exception and
/// returns the promise as a `return` would: `Some` with it when that frame was the boundary
/// frame.
fn unwind(&mut self, v: Value) -> JsResult<Option<Value>> {
self.note_site();
let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b);
if !passed
@@ -1237,11 +1288,26 @@ impl Interp {
if let (false, Some(site)) = (caught, site) {
self.finally_sites.push((site, target_len));
}
return Ok(());
return Ok(None);
}
// The promise is settled while the frame is still on top, so a limit reached doing it
// ends the frames the way any other limit does.
let promise = frame.async_promise;
if let Some(p) = promise {
self.settle_async(p, Err(v.clone()))?;
}
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if let Some(p) = promise {
self.drop_left_finally_marks();
self.drop_left_finally_sites(frame.base);
if frame.boundary {
return Ok(Some(Value::Object(p)));
}
self.push(Value::Object(p))?;
return Ok(None);
}
if frame.chained {
// The modules under it have not started, so no handler of theirs takes it.
self.abort_to_boundary();
@@ -1305,9 +1371,24 @@ impl Interp {
};
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
self.drop_left_finally_sites(frame.base);
// An async function's return resolves its promise after the frame is off the frames, so
// a `then` getter the resolution reads runs without it, and the call gives the promise.
// Settling roots the promise and the value, and a rejection for returning the promise
// itself is reported at the return. When settling fails, the frame goes back on top, so
// the error is reported at the return and ends the frames down to its boundary.
let v = match frame.async_promise {
Some(p) => match self.resolve_async_return(p, v, Some((frame.code.clone(), frame.pc.saturating_sub(1)))) {
Ok(()) => Value::Object(p),
Err(e) => {
self.frames.push(frame);
return Err(e);
}
},
None => v,
};
self.end_generator(frame.generator);
let v = match frame.construct {
Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o),
_ => v,
@@ -1520,7 +1601,9 @@ impl Interp {
Op::DelegateCall(t) => self.op_delegate_call(t),
Op::DelegateResult(t) => self.op_delegate_result(t),
Op::DelegateDone(t) => self.op_delegate_done(t),
Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"),
Op::Return | Op::ReturnCompletion | Op::Await | Op::GeneratorStart | Op::Yield(_) => {
internal("a frame-ending instruction reached the dispatcher")
}
}
}
@@ -3018,8 +3101,13 @@ impl Interp {
Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }),
None => env,
};
let is_async = code.is_async;
let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten();
let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto);
let proto = match (generator, self.promises.async_function_proto) {
(Some((function_proto, _)), _) => function_proto,
(None, Some(p)) if is_async => p,
_ => self.intrinsics.function_proto,
};
let length = code.length;
let strict = code.strict;
let arrow = code.arrow;
@@ -3052,6 +3140,15 @@ impl Interp {
if arrow || method || class_ctor {
return Ok(f);
}
// An async function has no `prototype` and cannot be constructed (ECMA-262 2017 section
// 25.5.4), and must not have own `caller` or `arguments` properties, restricted or not, in
// sloppy code too (section 16.2).
if is_async {
if let Some(name) = self_name {
self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?;
}
return Ok(f);
}
let p = self.new_object();
self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?;
self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?;
@@ -3238,9 +3335,13 @@ impl Interp {
Ok(())
}
/// Assigns a function declared in a block to the variable of the same name.
/// Assigns a function declared in a block to the variable of the same name, unless the
/// variable of script or eval code was not declared.
fn op_annex_b(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
if self.frame()?.annex_off.contains(&name) {
return self.pop().map(drop);
}
let v = self.peek(0)?;
let var_env = self.frame()?.var_env;
match self.heap.env(var_env) {
@@ -3805,6 +3906,7 @@ impl Interp {
/// the stack.
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
let Entry { callee, code, env, this, args, new_target } = entry;
let code_is_async = code.is_async;
self.check_frame_room()?;
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
// An arrow function reads the `arguments` object of the function around it.
@@ -3866,6 +3968,8 @@ impl Interp {
completion: Value::Undefined,
boundary,
generator: None,
async_promise: None,
annex_off: AnnexOff::new(),
chained: false,
pending_module: false,
});
@@ -3873,7 +3977,16 @@ impl Interp {
};
let r = enter();
self.temp_roots.truncate(mark);
r
r?;
// An async function's call makes its promise first thing (section 25.5.5.2); the frame
// keeps what the function holds reachable while it is made.
if code_is_async && let Err(e) = self.start_async_call() {
if let Some(frame) = self.frames.pop() {
self.stack.truncate(frame.base);
}
return Err(e);
}
Ok(())
}
/// Declaration binding instantiation for function code (section 10.5). Each parameter and
@@ -4268,10 +4381,11 @@ impl Interp {
};
self.stack.truncate(start);
self.check_frame_room()?;
let env = self.instantiate_pending(&code, env, var_env, true)?;
let (env, annex_off) = self.instantiate_pending(&code, env, var_env, true)?;
self.push_code_frame(code, env, var_env, this, false)?;
// The eval code reads `this` the way the code that called it does (section 18.2.1.1).
let frame = self.frame_mut()?;
frame.annex_off = annex_off;
// The eval code reads `this` the way the code that called it does (section 18.2.1.1).
frame.this_in_env = this_in_env;
frame.new_target = new_target.and_then(|v| v.as_object());
Ok(())
@@ -4280,7 +4394,7 @@ impl Interp {
/// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the
/// code counted against the heap, until its frame holds them: the scopes and functions it
/// makes can collect.
fn instantiate_pending(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
fn instantiate_pending(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> {
let mark = self.temp_envs.len();
self.temp_envs.push(env);
self.temp_codes.push(code.clone());
@@ -4306,7 +4420,9 @@ impl Interp {
r
}
/// Declares `code`'s variables and functions and pushes its boundary frame, ready to run.
/// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. The
/// frame limit and the heap, with a script's `let` and `const` names, are checked before
/// anything is declared.
pub(crate) fn enter_global(&mut self, code: Rc<Code>, is_eval: bool) -> JsResult<()> {
// A script's `let` and `const` names are counted with its declarations, so none of them
// is declared unless all of them fit.
@@ -4322,8 +4438,10 @@ impl Interp {
// The frame limit is checked before anything is declared, so a script that cannot start
// leaves the global scope as it was.
self.check_frame_room()?;
let env = self.instantiate_pending(&code, env, var_env, is_eval)?;
self.push_code_frame(code, env, var_env, Value::Object(global), true)
let (env, annex_off) = self.instantiate_pending(&code, env, var_env, is_eval)?;
self.push_code_frame(code, env, var_env, Value::Object(global), true)?;
self.frame_mut()?.annex_off = annex_off;
Ok(())
}
/// The environment global code runs in: the one that holds the scripts' `let` and `const`
@@ -4332,10 +4450,18 @@ impl Interp {
self.global_lex
}
/// Sets [`Options::es2015`] for the next runs. The first run with it on gives the built-in
/// functions their ECMAScript 2015 `name` and `length` ([`crate::builtins::es2015_names`]).
/// Sets [`Options::es2015`] for the next runs; turning it off turns [`Options::es2017`] off too.
/// The first run with it on gives the built-in functions their ECMAScript 2015 `name` and
/// `length` ([`crate::builtins::es2015_names`]).
pub(crate) fn set_es2015(&mut self, es2015: bool) {
self.options.es2015 = es2015;
self.options.es2017 &= es2015;
}
/// Sets [`Options::es2017`] for the next runs; turning it on turns [`Options::es2015`] on too.
pub(crate) fn set_es2017(&mut self, es2017: bool) {
self.options.es2017 = es2017;
self.options.es2015 |= es2017;
}
/// Declares a script's top-level `let` and `const` names in the global scope, uninitialized
@@ -4446,6 +4572,8 @@ impl Interp {
completion: Value::Undefined,
boundary,
generator: None,
async_promise: None,
annex_off: AnnexOff::new(),
chained: false,
pending_module: false,
});
@@ -4463,7 +4591,8 @@ impl Interp {
let scope = self.global_lex;
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
self.temp_envs.push(env);
let lex = self.instantiate_global(code, env, env, true)?;
// Module code is strict, so no block function needs its variable left alone.
let (lex, _annex_off) = self.instantiate_global(code, env, env, true)?;
self.temp_envs.push(lex);
Ok((lex, env))
}
@@ -4575,7 +4704,9 @@ impl Interp {
/// global scope ([`Self::declare_global_lexical`]). Eval code outside strict mode code is
/// checked against the `let` and `const` names around it ([`Self::check_eval_vars`]) with the
/// option on or off, so it also meets the names that earlier runs of a kept realm declared.
fn instantiate_global(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
/// Also gives the names of [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not
/// declare.
fn instantiate_global(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> {
// Strict eval code's own environment is in no frame yet, so it is a root while the
// declarations reserve heap.
let mark = self.temp_envs.len();
@@ -4586,7 +4717,7 @@ impl Interp {
}
/// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`].
fn instantiate_global_rooted(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
fn instantiate_global_rooted(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> {
let configurable = if is_eval { CONFIGURABLE } else { 0 };
if is_eval && !code.strict {
self.check_eval_vars(code, env, var_env)?;
@@ -4608,7 +4739,8 @@ impl Interp {
// some of it (a script's names in the global scope were checked with the declarations
// before they were added). Their environment stays reachable if the check collects.
self.temp_envs.push(lex);
let r = self.reserve_heap(declaration_bytes(code)).and_then(|()| self.declare_global_functions_and_vars(code, lex, var_env, configurable));
let r =
self.reserve_heap(declaration_bytes(code)).and_then(|()| self.declare_global_functions_and_vars(code, (env, lex), var_env, configurable));
self.temp_envs.pop();
if r.is_err() && global_lets {
// A script that stops before it runs, at a limit, leaves none of its `let` and `const`
@@ -4620,12 +4752,19 @@ impl Interp {
}
}
}
r.map(|()| lex)
r.map(|annex_off| (lex, annex_off))
}
/// Declares the functions and variables of global or eval code for
/// [`Self::instantiate_global_rooted`], each taking a unit of fuel.
fn declare_global_functions_and_vars(&mut self, code: &Rc<Code>, lex: EnvId, var_env: EnvId, configurable: u8) -> JsResult<()> {
/// [`Self::instantiate_global_rooted`], each taking a unit of fuel, and gives the names of
/// [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not declare.
fn declare_global_functions_and_vars(
&mut self,
code: &Rc<Code>,
(env, lex): (EnvId, EnvId),
var_env: EnvId,
configurable: u8,
) -> JsResult<AnnexOff> {
// Functions close over the code's own environment with ES2015's scoping, and over its
// variable environment otherwise (ECMA-262 5.1 section 13). When that is the global
// object's, they close over the global scope inside it, which also holds the scripts'
@@ -4656,7 +4795,47 @@ impl Interp {
self.declare(var_env, v, None, configurable)?;
self.note_global_var(on_global, v)?;
}
Ok(())
let mut annex_off = AnnexOff::new();
for v in &code.annex_vars {
self.use_fuel()?;
if !self.annex_var_declarable(v, env, var_env)? {
annex_off.insert(v.clone());
continue;
}
self.declare(var_env, v, None, configurable)?;
if on_global {
self.global_vars.insert(v.clone());
}
}
Ok(annex_off)
}
/// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and
/// B.3.3.3, <https://tc39.es/ecma262/#sec-web-compat-globaldeclarationinstantiation>): no
/// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch`
/// parameter does not count, and on the global object the name is its own property or the
/// object is extensible. Each environment passed takes a unit of fuel.
fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult<bool> {
let mut cur = Some(env).filter(|&e| e != var_env);
while let Some(e) = cur {
self.use_fuel()?;
cur = match self.heap.env(e) {
Some(Env::Decl { bindings, outer }) => {
if bindings.get(name).is_some_and(|b| b.lexical) {
return Ok(false);
}
*outer
}
Some(Env::Obj { outer, .. }) => *outer,
None => return internal("environment out of range"),
}
.filter(|&o| o != var_env);
}
if var_env != self.global_env {
return Ok(true);
}
let global = self.global;
Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible)
}
/// Adds `name`, which global code just declared, to [`Self::global_vars`] when `on_global`
+176
View File
@@ -0,0 +1,176 @@
//! An async function's frame while it waits at `await` (ECMA-262 2017 sections 25.5 and 6.2.3.1,
//! <https://262.ecma-international.org/8.0/#await>): [`Interp::suspend_frame`] moves the running
//! frame, its operands and its pending `finally` state into an [`Activation`], which lives on the
//! heap inside the functions that resume it, and [`Interp::restore_frame`] puts it back on top of
//! the frames to go on. An activation that nothing can resume any more is collected like any
//! other object.
use std::rc::Rc;
use super::{Frame, Interp, JsResult, ThrowSite, internal};
use crate::bytecode::Code;
use crate::heap::{EnvId, ObjId};
use crate::value::Value;
/// The estimated bytes of an activation, beyond the object and its operands.
pub(crate) const ACTIVATION_BYTES: usize = 128;
/// The estimated bytes of each operand, `finally` mark or `finally` site an activation keeps.
pub(crate) const SLOT_BYTES: usize = 16;
/// A suspended frame. Stack slots in `marks` and `sites` count from the frame's first operand.
#[derive(Clone)]
pub(crate) struct Activation {
code: Rc<Code>,
pc: usize,
env: EnvId,
var_env: EnvId,
env_depth: u32,
this: Value,
this_in_env: bool,
strict_class: bool,
callee: Option<ObjId>,
new_target: Option<ObjId>,
this_env: Option<EnvId>,
completion: Value,
/// The promise the async function's call returned.
pub(crate) promise: ObjId,
stack: Vec<Value>,
marks: Vec<(ObjId, u32, usize)>,
sites: Vec<(ThrowSite, usize)>,
}
impl Activation {
/// The values the activation holds, for the collector.
pub(crate) fn values(&self) -> impl Iterator<Item = &Value> {
self.stack.iter().chain([&self.this, &self.completion])
}
/// The objects and environments the activation holds, for the collector.
pub(crate) fn ids(&self) -> impl Iterator<Item = u32> {
self.callee
.iter()
.chain(self.new_target.iter())
.chain([&self.promise])
.chain(self.marks.iter().map(|(o, _, _)| o))
.map(|o| o.0)
.chain([self.env.0, self.var_env.0])
.chain(self.this_env.iter().map(|e| e.0))
}
/// The code the activation runs and the code of its `finally` sites, for the collector.
pub(crate) fn codes(&self) -> impl Iterator<Item = &Code> {
std::iter::once(&*self.code).chain(self.sites.iter().map(|((code, _), _)| &**code))
}
/// The estimated bytes of the activation, beyond the object.
pub(crate) fn bytes(&self) -> usize {
ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(self.stack.len() + self.marks.len() + self.sites.len()))
}
}
impl Interp {
/// The promise of the async function the top frame runs, when it runs one.
pub(crate) fn async_promise(&self) -> Option<ObjId> {
self.frames.last().and_then(|f| f.async_promise)
}
/// Makes the promise of the async function call whose frame was just pushed.
pub(crate) fn start_async_call(&mut self) -> JsResult<()> {
let p = self.new_async_promise()?;
match self.frames.last_mut() {
Some(f) => {
f.async_promise = Some(p);
Ok(())
}
None => internal("an async call without a frame"),
}
}
/// The bytes [`Self::suspend_frame`] will move off the operand stack, for the heap check made
/// before it.
pub(crate) fn suspend_bytes(&self) -> usize {
let Some(f) = self.frames.last() else { return ACTIVATION_BYTES };
let n = self.stack.len().saturating_sub(f.base)
+ self.finally_marks.iter().filter(|&&(_, _, s)| s >= f.base).count()
+ self.finally_sites.iter().filter(|&&(_, s)| s >= f.base).count();
ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(n))
}
/// Takes the top frame, which runs an async function, off the frames with its operands and
/// its `finally` state. Gives the activation and whether the frame was a boundary frame.
pub(crate) fn suspend_frame(&mut self) -> JsResult<(Activation, bool)> {
let Some(frame) = self.frames.pop() else { return internal("await without a frame") };
let Some(promise) = frame.async_promise else { return internal("await outside an async function") };
let base = frame.base;
if self.stack.len() < base {
return internal("frame operands below the stack");
}
let stack = self.stack.split_off(base);
let mut marks = Vec::new();
self.finally_marks.retain(|&(o, mark, slot)| {
if slot < base {
return true;
}
marks.push((o, mark, slot - base));
false
});
let at = self.finally_sites.iter().position(|&(_, slot)| slot >= base).unwrap_or(self.finally_sites.len());
let sites = self.finally_sites.split_off(at).into_iter().map(|(site, slot)| (site, slot - base)).collect();
let activation = Activation {
code: frame.code,
pc: frame.pc,
env: frame.env,
var_env: frame.var_env,
env_depth: frame.env_depth,
this: frame.this,
this_in_env: frame.this_in_env,
strict_class: frame.strict_class,
callee: frame.callee,
new_target: frame.new_target,
this_env: frame.this_env,
completion: frame.completion,
promise,
stack,
marks,
sites,
};
Ok((activation, frame.boundary))
}
/// Puts a suspended frame back on top of the frames as a boundary frame, with its operands at
/// the top of the operand stack.
pub(crate) fn restore_frame(&mut self, a: Activation) -> JsResult<()> {
if self.frames.len() >= self.limits.frames {
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Frames));
}
let base = self.stack.len();
for v in a.stack {
self.push(v)?;
}
self.finally_marks.extend(a.marks.into_iter().map(|(o, mark, slot)| (o, mark, slot + base)));
self.finally_sites.extend(a.sites.into_iter().map(|(site, slot)| (site, slot + base)));
self.frames.push(Frame {
code: a.code,
pc: a.pc,
base,
env: a.env,
var_env: a.var_env,
env_depth: a.env_depth,
this: a.this,
this_in_env: a.this_in_env,
strict_class: a.strict_class,
callee: a.callee,
construct: None,
new_target: a.new_target,
this_env: a.this_env,
completion: a.completion,
boundary: true,
generator: None,
async_promise: Some(a.promise),
annex_off: super::AnnexOff::new(),
chained: false,
pending_module: false,
});
Ok(())
}
}
+2
View File
@@ -1029,6 +1029,7 @@ fn code(ops: Vec<Op>) -> Code {
params: Vec::new(),
vars: Vec::new(),
fun_decls: Vec::new(),
annex_vars: Vec::new(),
uses_arguments: false,
source,
span: (0, 0),
@@ -1048,6 +1049,7 @@ fn code(ops: Vec<Op>) -> Code {
own_name: None,
method: false,
generator: false,
is_async: false,
supers: crate::parser::SuperRules::default(),
}
}
+25 -1
View File
@@ -126,6 +126,10 @@
//! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5,
//! <https://262.ecma-international.org/11.0/>), with string and Symbol property keys: a trap is
//! given either kind of key, an `ownKeys` trap may return both, and `Reflect.ownKeys` lists both.
//!
//! With [`Options::es2017`], the parser and the realm also read and run async functions and
//! `await` (ECMA-262 2017 section 25.5, <https://262.ecma-international.org/8.0/#sec-async-function-objects>).
//! An `await` suspends its function's frame until the value settles, and a promise job resumes it.
#![forbid(unsafe_code)]
pub mod ast;
@@ -220,11 +224,29 @@ pub struct Options {
/// `Promise` to a realm made without it. Runs with it on also convert `0b` and `0o` strings to
/// numbers.
pub es2015: bool,
/// Also read and run async functions and `await` (ECMAScript 2017). It turns on
/// [`Options::es2015`] too, whatever that field says. Off, `async` and `await` are identifiers.
pub es2017: bool,
}
impl Options {
/// [`Options::es2015`], which [`Options::es2017`] turns on too.
pub(crate) fn modern(&self) -> bool {
self.es2015 || self.es2017
}
}
impl Default for Options {
fn default() -> Self {
Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false }
Self {
strict: false,
preprocessor_lines: false,
max_depth: DEFAULT_MAX_DEPTH,
max_source_units: 64 << 20,
e4x: false,
es2015: false,
es2017: false,
}
}
}
@@ -355,6 +377,8 @@ impl LineTable {
}
}
#[cfg(test)]
mod async_tests;
#[cfg(test)]
mod builtins_tests;
#[cfg(test)]
+258 -45
View File
@@ -47,6 +47,23 @@ struct Context {
/// The code is a generator function's body or parameters: `yield` starts a yield expression
/// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4).
generator: bool,
/// The code is an async function's body: `await` is an operator, not an identifier.
in_async: bool,
/// The code is an async function's parameters: `await` is neither an operator nor an
/// identifier there (ECMA-262 2017 section 14.6.1).
async_params: bool,
}
/// What the parser noted about a parenthesized expression or a call to `async` that may turn out
/// to be an arrow function's head.
#[derive(Clone, Copy, Debug)]
struct Head {
/// A line break comes between `async` and `(`.
line_break: bool,
/// The parentheses hold an `await` expression or the identifier `await`.
awaits: bool,
/// A comma follows the last item in the parentheses.
trailing_comma: bool,
}
/// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations
@@ -104,6 +121,8 @@ enum BinKind {
enum Prefix {
Unary(UnaryOp),
Update(UpdateOp),
/// `await`, in an async function's body.
Await,
}
pub(crate) struct Parser<'s> {
@@ -154,11 +173,20 @@ pub(crate) struct Parser<'s> {
/// Where each yield expression read so far starts, in the order read, so the parameters of a
/// generator function and an arrow function's head can be checked for one.
yields: Vec<u32>,
/// Read async functions and `await` ([`crate::Options::es2017`]).
es2017: bool,
/// How many `await` expressions and `await` identifiers have been read.
awaits: u32,
/// The parenthesized expressions and calls to `async` read so far that may be arrow heads.
heads: HashMap<ExprId, Head>,
/// The last identifier expression read from an `async` written without escapes.
async_ident: Option<ExprId>,
}
impl<'s> Parser<'s> {
pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result<Self> {
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(options.es2015);
let es2015 = options.modern();
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(es2015);
let placeholder =
Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false };
let mut parser = Self {
@@ -176,8 +204,12 @@ impl<'s> Parser<'s> {
function_allowed: false,
in_list: false,
e4x: options.e4x,
es2015: options.es2015,
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
es2015,
scopes: if es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
es2017: options.es2017,
awaits: 0,
heads: HashMap::new(),
async_ident: None,
supers: SuperRules::default(),
module: false,
cover_inits: Vec::new(),
@@ -349,6 +381,9 @@ impl<'s> Parser<'s> {
if self.ctx.generator && name == "yield" {
return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function"));
}
if name == "await" && (self.ctx.in_async || self.ctx.async_params) {
return Err(self.error_at_token(token, "'await' cannot be an identifier in an async function"));
}
Ok(())
}
@@ -358,6 +393,17 @@ impl<'s> Parser<'s> {
self.yields.get(i).is_some_and(|&y| y < end)
}
/// The current token is `async` written without escapes, read as the start of an async
/// function or arrow function only with [`crate::Options::es2017`].
fn at_async(&self) -> bool {
self.es2017 && self.tok.ident() == Some("async") && !self.tok.escaped
}
/// The current token is `async` and `function` follows it on the same line: an async function.
fn at_async_function(&self) -> bool {
self.at_async() && self.peek().is_some_and(|t| t.is_keyword(Keyword::Function) && !t.newline_before)
}
/// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does,
/// and in strict code neither `eval` nor `arguments`.
fn binding_identifier(&mut self) -> Result<Name> {
@@ -369,6 +415,9 @@ impl<'s> Parser<'s> {
if self.ctx.strict && is_eval_or_arguments(&name) {
return Err(self.error_at_token(&self.tok, format!("'{name}' cannot be declared in strict mode")));
}
if name == "await" {
self.awaits = self.awaits.saturating_add(1);
}
let token = self.bump()?;
Ok(Name { name, span: token.span })
}
@@ -438,7 +487,11 @@ impl<'s> Parser<'s> {
/// Declares a function declaration that stands in a statement list: var-scoped in a function
/// body or the script, lexical in a block.
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
let Some(f) = self.ast.function(id) else { return Ok(()) };
let Some(name) = f.name.clone() else { return Ok(()) };
// Only plain function declarations may repeat in a block (Annex B.3.3.4), not generator
// or async ones.
let plain = !f.is_async && !f.generator;
if self.module && self.scopes.len() == 1 {
return self.declare_lexical(&name, true);
}
@@ -450,8 +503,7 @@ impl<'s> Parser<'s> {
scope.vars.insert(name.name);
Ok(())
}
// Only plain function declarations may repeat in a block (Annex B.3.3.4).
Some(_) => self.declare_lexical(&name, !generator),
Some(_) => self.declare_lexical(&name, plain),
None => Ok(()),
}
}
@@ -565,7 +617,7 @@ impl<'s> Parser<'s> {
/// A source element: a function declaration or a statement.
fn parse_statement_item(&mut self) -> Result<StmtId> {
if self.at_keyword(Keyword::Function) {
if self.at_keyword(Keyword::Function) || self.at_async_function() {
self.enter()?;
let result = self.parse_function_declaration();
self.leave();
@@ -631,6 +683,9 @@ impl<'s> Parser<'s> {
}
self.parse_function_declaration()
}
TokenKind::Ident(_) if self.at_async_function() => {
Err(self.error_at_token(&self.tok, "an async function declaration cannot stand here; put it in a block"))
}
TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list),
_ => self.plain_statement(start),
}
@@ -1138,10 +1193,13 @@ impl<'s> Parser<'s> {
// ---- functions ----
fn parse_function_declaration(&mut self) -> Result<StmtId> {
let start = self.expect_keyword(Keyword::Function)?.span;
let generator = self.es2015 && self.eat(Punct::Star)?;
let is_async = self.at_async();
let start = if is_async { self.bump()?.span } else { self.tok.span };
self.expect_keyword(Keyword::Function)?;
// Async generators (ECMAScript 2018) stay syntax errors: the `*` is not read after `async`.
let generator = !is_async && self.es2015 && self.eat(Punct::Star)?;
let name = self.function_name()?;
let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?;
Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start)))
}
@@ -1157,20 +1215,22 @@ impl<'s> Parser<'s> {
Ok((Name { name, span: token.span }, token))
}
/// The parameters and body of a function, from `(`; with `generator`, a generator function's.
/// The parameters and body of a function, from `(`; with `generator`, a generator function's,
/// and with `is_async`, an async function's.
fn parse_function_rest(
&mut self,
kind: FunctionKind,
name: Option<(Name, Token)>,
start: Span,
generator: bool,
is_async: bool,
) -> Result<crate::ast::FunctionId> {
self.parse_function_with(kind, name, start, false, generator)
self.parse_function_with(kind, name, start, false, generator, is_async)
}
/// The parameters and body of a function, from `(`; `home` for one defined in a class body or
/// as a method of an object literal, where `super.property` may stand, and with `generator`, a
/// generator function's.
/// as a method of an object literal, where `super.property` may stand, with `generator`, a
/// generator function's, and with `is_async`, an async function's.
fn parse_function_with(
&mut self,
kind: FunctionKind,
@@ -1178,6 +1238,7 @@ impl<'s> Parser<'s> {
start: Span,
home: bool,
generator: bool,
is_async: bool,
) -> Result<crate::ast::FunctionId> {
self.enter()?;
let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor);
@@ -1185,7 +1246,16 @@ impl<'s> Parser<'s> {
// The parameters are read with the function's own `yield` rule, not the enclosing code's.
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
let yields = self.yields.len();
let result = self.function_rest(kind, name, start, home, generator);
// The parameters are read with `await` as the function has it, then the code around
// them goes on as it was.
// An `await` inside the function does not count for an arrow function's head around it.
let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits);
self.ctx.in_async = false;
self.ctx.async_params = is_async;
let result = self.function_rest(kind, name, start, home, generator, is_async);
self.ctx.in_async = in_async;
self.ctx.async_params = async_params;
self.awaits = awaits;
// The `yield` expressions of this function are not in the code around it.
self.yields.truncate(yields);
self.ctx.generator = outer_generator;
@@ -1201,6 +1271,7 @@ impl<'s> Parser<'s> {
start: Span,
home: bool,
generator: bool,
is_async: bool,
) -> Result<crate::ast::FunctionId> {
let params_start = self.tok.span.start;
self.expect(Punct::LParen)?;
@@ -1254,7 +1325,7 @@ impl<'s> Parser<'s> {
self.expect(Punct::LBrace)?;
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
let outer_strict = self.ctx.strict;
let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() };
let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, generator, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
self.push_scope(true, names);
let body = self.parse_body(true);
@@ -1263,14 +1334,18 @@ impl<'s> Parser<'s> {
self.ctx = outer;
let body = body?;
self.expect(Punct::RBrace)?;
let function =
Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start), home };
let span = self.span_from(start);
let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, is_async, span, home };
// An async declaration or expression takes FormalParameters as a plain function does
// (ECMA-262 2017 section 14.6): repeated simple names are an error only in strict code.
// Arrow functions and async methods reject every repeat.
self.check_params(&function, use_strict)?;
Ok(self.ast.push_function(function))
}
/// An arrow function's body and the function, from `=>`, with its parameters read.
fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool) -> Result<ExprId> {
/// An arrow function's body and the function, from `=>`, with its parameters read; with
/// `is_async`, an async arrow function's.
fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool, is_async: bool) -> Result<ExprId> {
if self.tok.newline_before {
return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'"));
}
@@ -1278,8 +1353,10 @@ impl<'s> Parser<'s> {
self.enter()?;
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
let outer_strict = self.ctx.strict;
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
// An `await` in the body does not count for an async arrow function's head around it.
let awaits = self.awaits;
self.push_scope(true, names);
let block = self.at(Punct::LBrace);
let body = if block {
@@ -1288,6 +1365,7 @@ impl<'s> Parser<'s> {
self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))])
};
self.pop_scope();
self.awaits = awaits;
let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict);
self.ctx = outer;
self.leave();
@@ -1305,6 +1383,7 @@ impl<'s> Parser<'s> {
body,
strict,
generator: false,
is_async,
span: self.span_from(start),
home: false,
};
@@ -1323,6 +1402,13 @@ impl<'s> Parser<'s> {
Some(Expr::Sequence(list)) => list.clone(),
_ => vec![*inner],
};
self.arrow_items(items)
}
/// The parameters the items of an arrow function's head give: names, names with `= default`,
/// and a last `...name`.
fn arrow_items(&mut self, items: Vec<ExprId>) -> Result<Params> {
let invalid = |p: &Self, at: ExprId| p.error_at_offset(p.ast.expr_span(at).start, "invalid arrow function parameters");
let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None);
let count = items.len();
for (i, item) in items.into_iter().enumerate() {
@@ -1426,10 +1512,12 @@ impl<'s> Parser<'s> {
fn assignment(&mut self, no_in: bool) -> Result<ExprId> {
let mut targets: Vec<(ExprId, AssignOp)> = Vec::new();
loop {
// `async` followed on its line by a name starts an async arrow function.
let async_name = self.at_async() && self.peek().is_some_and(|t| matches!(t.kind, TokenKind::Ident(_)) && !t.newline_before);
let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped {
self.parse_yield(no_in)?
} else {
let mut expr = self.parse_conditional(no_in)?;
let mut expr = if async_name { self.parse_async_name_arrow(no_in)? } else { self.parse_conditional(no_in)? };
if self.es2015 && self.at(Punct::Arrow) {
expr = self.arrow_from(expr, no_in)?;
}
@@ -1475,12 +1563,46 @@ impl<'s> Parser<'s> {
if self.yield_between(start.start, start.end) {
return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters"));
}
let params = match self.ast.expr(expr) {
Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None),
Some(Expr::Paren(_)) => self.arrow_params(expr)?,
let head = self.heads.get(&expr).copied();
let (params, is_async) = match self.ast.expr(expr) {
Some(Expr::Ident(name)) => ((vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), false),
Some(Expr::Paren(_)) => (self.arrow_params(expr)?, false),
// `async (…) =>` was read as a call to `async` (ECMA-262 2017 section 14.7).
Some(Expr::Call { args, .. }) if head.is_some() => {
if head.is_some_and(|h| h.line_break) {
return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function"));
}
// No comma may follow a rest parameter (ECMA-262 2017 section 14.1).
if let Some(&last) = args.last()
&& head.is_some_and(|h| h.trailing_comma)
&& matches!(self.ast.expr(last), Some(Expr::Spread(_)))
{
return Err(self.error_at_offset(self.ast.expr_span(last).start, "a rest parameter must be the last parameter"));
}
(self.arrow_items(args.clone())?, true)
}
_ => return Err(self.unexpected()),
};
self.parse_arrow(start, params, no_in)
// `await` cannot be an arrow function's parameter, or stand in one's default value,
// where it is an operator or in an async arrow function's head.
if head.is_some_and(|h| h.awaits) && (is_async || self.ctx.in_async) {
return Err(self.error_at_offset(start.start, "'await' cannot stand in an arrow function's parameters here"));
}
self.parse_arrow(start, params, no_in, is_async)
}
/// `async name => …` from `async` (ECMA-262 2017 section 14.7): the one parameter is read as
/// an async function's is.
fn parse_async_name_arrow(&mut self, no_in: bool) -> Result<ExprId> {
let start = self.bump()?.span;
let async_params = std::mem::replace(&mut self.ctx.async_params, true);
let param = self.binding_identifier();
self.ctx.async_params = async_params;
let param = param?;
if !self.at(Punct::Arrow) {
return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok))));
}
self.parse_arrow(start, (vec![Binding::Name(param)], vec![None], None), no_in, true)
}
/// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code
@@ -1571,7 +1693,17 @@ impl<'s> Parser<'s> {
/// Prefix operators, read with a loop and applied innermost first.
fn parse_unary(&mut self) -> Result<ExprId> {
let mut prefixes = Vec::new();
while let Some(prefix) = prefix_op(&self.tok) {
loop {
// In an async function's body, `await` is a prefix operator (ECMA-262 2017 section 14.6).
let prefix = if self.ctx.in_async && self.tok.ident() == Some("await") {
if self.tok.escaped {
return Err(self.error_at_token(&self.tok, "keyword 'await' must not contain escaped characters"));
}
Prefix::Await
} else {
let Some(prefix) = prefix_op(&self.tok) else { break };
prefix
};
prefixes.push((prefix, self.tok.span));
self.bump()?;
}
@@ -1589,6 +1721,10 @@ impl<'s> Parser<'s> {
}
self.ast.push_expr(Expr::Unary { op, arg: expr }, span)
}
Prefix::Await => {
self.awaits = self.awaits.saturating_add(1);
self.ast.push_expr(Expr::Await(expr), span)
}
};
}
Ok(expr)
@@ -1650,12 +1786,23 @@ impl<'s> Parser<'s> {
expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span);
}
TokenKind::Punct(Punct::LParen) => {
let args = self.parse_arguments()?;
let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr);
let line_break = self.tok.newline_before;
let awaits = self.awaits;
// The arguments of a possible async arrow function's head may be patterns
// such as `{a = 1}`; they are checked as expressions once no `=>` follows.
let mark = self.cover_inits.len();
let (args, trailing_comma) = self.arguments(async_head)?;
let span = Span::new(self.ast.expr_span(expr).start, self.prev_end);
expr = match news.pop() {
Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)),
None => self.ast.push_expr(Expr::Call { callee: expr, args }, span),
};
if async_head && self.at(Punct::Arrow) {
self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma });
} else if async_head {
self.check_cover(mark)?;
}
}
TokenKind::Punct(Punct::QuestionDot) => {
if !news.is_empty() {
@@ -1802,19 +1949,33 @@ impl<'s> Parser<'s> {
}
fn parse_arguments(&mut self) -> Result<Vec<ExprId>> {
Ok(self.arguments(false)?.0)
}
/// An argument list, and whether a comma follows its last argument. With `cover`, the
/// arguments may hold initializers such as `{a = 1}`, which the caller checks.
fn arguments(&mut self, cover: bool) -> Result<(Vec<ExprId>, bool)> {
self.expect(Punct::LParen)?;
let mut args = Vec::new();
let mut trailing_comma = false;
if !self.at(Punct::RParen) {
loop {
if cover {
self.cover_ok = true;
}
args.push(self.parse_element()?);
// A comma may follow the last argument (ECMAScript 2017, section 12.3).
if !self.eat(Punct::Comma)? || self.at(Punct::RParen) {
if !self.eat(Punct::Comma)? {
break;
}
if self.at(Punct::RParen) {
trailing_comma = true;
break;
}
}
}
self.expect(Punct::RParen)?;
Ok(args)
Ok((args, trailing_comma))
}
fn parse_primary(&mut self) -> Result<ExprId> {
@@ -1836,9 +1997,20 @@ impl<'s> Parser<'s> {
let class = self.parse_class(false)?;
return Ok(self.ast.push_expr(Expr::Class(Box::new(class)), self.span_from(start)));
}
TokenKind::Ident(_) if self.at_async_function() => return self.parse_function_expression(),
TokenKind::Ident(name) => {
let name = name.clone();
self.check_identifier(&self.tok, &name)?;
if name == "await" {
self.awaits = self.awaits.saturating_add(1);
}
// With E4X, `async::name` is a qualified name.
if self.at_async() && !(self.e4x && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon))) {
let token = self.bump()?;
let id = self.ast.push_expr(Expr::Ident(name), token.span);
self.async_ident = Some(id);
return Ok(id);
}
Expr::Ident(name)
}
TokenKind::Number(n) => {
@@ -1887,9 +2059,11 @@ impl<'s> Parser<'s> {
}
/// `( … )` with [`crate::Options::es2015`]: a parenthesized expression, or the head of an arrow
/// function, which may also be `()` or end with `...name`; those two must come before `=>`.
/// function, which may also be `()`, end with `...name` or end with a comma; those three must
/// come before `=>`.
fn parse_paren_or_arrow_head(&mut self) -> Result<ExprId> {
let start = self.expect(Punct::LParen)?.span;
let awaits = self.awaits;
let mut items = Vec::new();
let mut head_only = self.at(Punct::RParen);
let mark = self.cover_inits.len();
@@ -1906,8 +2080,11 @@ impl<'s> Parser<'s> {
if !self.eat(Punct::Comma)? {
break;
}
// A comma may follow the last parameter (ECMA-262 2017 section 14.2), but not the
// last item of a parenthesized expression.
if self.at(Punct::RParen) {
return Err(self.unexpected());
head_only = true;
break;
}
}
self.expect(Punct::RParen)?;
@@ -1924,7 +2101,11 @@ impl<'s> Parser<'s> {
self.ast.push_expr(Expr::Sequence(items), span)
}
};
Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start)))
let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start));
if self.at(Punct::Arrow) {
self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits, trailing_comma: false });
}
Ok(paren)
}
/// A template literal from its first piece (the current token): its pieces and substitutions.
@@ -1953,14 +2134,25 @@ impl<'s> Parser<'s> {
}
fn parse_function_expression(&mut self) -> Result<ExprId> {
let start = self.expect_keyword(Keyword::Function)?.span;
let generator = self.es2015 && self.eat(Punct::Star)?;
// A generator expression's name is read with its own `yield` rule.
let is_async = self.at_async();
let start = if is_async { self.bump()?.span } else { self.tok.span };
self.expect_keyword(Keyword::Function)?;
// Async generators (ECMAScript 2018) stay syntax errors: the `*` is not read after `async`.
let generator = !is_async && self.es2015 && self.eat(Punct::Star)?;
// A function expression's name is read as its own body reads names (ECMA-262 2017
// section 14.6): `await` is a name for an ordinary one, and not for an async one, and a
// generator expression's name is read with its own `yield` rule.
// Nor does the name count for an arrow function's head around it.
let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits);
self.ctx.in_async = is_async;
self.ctx.async_params = false;
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) };
self.ctx.generator = outer_generator;
let name = name?;
let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?;
self.ctx.in_async = in_async;
self.ctx.async_params = async_params;
self.awaits = awaits;
let id = self.parse_function_rest(FunctionKind::Expression, name?, start, generator, is_async)?;
Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start)))
}
@@ -2023,14 +2215,21 @@ impl<'s> Parser<'s> {
self.bump()?;
}
let start = self.tok.span;
let generator = self.eat(Punct::Star)?;
// `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, with no line break
// after `async`. Async generator methods (ECMAScript 2018) stay syntax errors.
let is_async =
self.at_async() && self.peek().is_some_and(|t| !t.newline_before && (property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
if is_async {
self.bump()?;
}
let generator = !is_async && self.eat(Punct::Star)?;
// `get` and `set` start an accessor only when written without escapes and followed by a name.
let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) {
Some("get") => Some(MethodKind::Get),
Some("set") => Some(MethodKind::Set),
_ => None,
}
.filter(|_| !generator && self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
.filter(|_| !generator && !is_async && self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
if accessor.is_some() {
self.bump()?;
}
@@ -2051,7 +2250,10 @@ impl<'s> Parser<'s> {
return Err(self.error_at_offset(start.start, "a class constructor cannot be a generator"));
}
let ctor = if derived { FunctionKind::DerivedConstructor } else { FunctionKind::ClassConstructor };
return Ok(Err(self.parse_function_with(ctor, None, start, true, false)?));
if is_async {
return Err(self.error_at_offset(start.start, "a class constructor cannot be async"));
}
return Ok(Err(self.parse_function_with(ctor, None, start, true, false, false)?));
}
if is_static && named("prototype") {
return Err(self.error_at_offset(start.start, "a class cannot have a static method named 'prototype'"));
@@ -2061,7 +2263,7 @@ impl<'s> Parser<'s> {
MethodKind::Get => FunctionKind::Getter,
MethodKind::Set => FunctionKind::Setter,
};
let function = self.parse_function_with(fkind, None, start, true, generator)?;
let function = self.parse_function_with(fkind, None, start, true, generator, is_async)?;
Ok(Ok(ClassElement { key, is_static, kind, function }))
}
@@ -2078,8 +2280,19 @@ impl<'s> Parser<'s> {
} else {
(FunctionKind::ClassConstructor, None, Vec::new())
};
let function =
Function { kind, name: None, params: Vec::new(), defaults: Vec::new(), rest, body, strict: true, generator: false, span, home: true };
let function = Function {
kind,
name: None,
params: Vec::new(),
defaults: Vec::new(),
rest,
body,
strict: true,
generator: false,
is_async: false,
span,
home: true,
};
self.ast.push_function(function)
}
@@ -2162,7 +2375,7 @@ impl<'s> Parser<'s> {
let word = self.bump()?;
if property_key(&self.tok).is_some() {
let (key, _) = self.parse_property_key()?;
let function = self.parse_function_rest(kind, None, start, false)?;
let function = self.parse_function_rest(kind, None, start, false, false)?;
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
return Ok(Property { key, value, span: self.span_from(start) });
}
+1 -1
View File
@@ -317,7 +317,7 @@ impl Parser<'_> {
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
};
let local = name.0.name.clone();
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, false)?;
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
Ok((stmt, fid, local))
}
+15 -3
View File
@@ -149,7 +149,15 @@ impl Parser<'_> {
// `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4).
if self.eat(Punct::Star)? {
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
let function = self.parse_function_with(FunctionKind::Method, None, start, true, true)?;
let function = self.parse_function_with(FunctionKind::Method, None, start, true, true, false)?;
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
}
// `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, with no line break
// after `async`. Async generator methods (ECMAScript 2018) stay syntax errors.
if self.at_async() && self.peek().is_some_and(|t| !t.newline_before && (property_key(&t).is_some() || t.is_punct(Punct::LBracket))) {
self.bump()?;
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
let function = self.parse_function_with(FunctionKind::Method, None, start, true, false, true)?;
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
}
// `get` and `set` start an accessor only when written without escapes and followed by a
@@ -165,7 +173,7 @@ impl Parser<'_> {
self.bump()?;
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
// An accessor is a method, whose home object is the literal's object.
let function = self.parse_function_with(kind, None, start, true, false)?;
let function = self.parse_function_with(kind, None, start, true, false, false)?;
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
return Ok(Property { key, value, span: self.span_from(start) });
}
@@ -178,6 +186,10 @@ impl Parser<'_> {
{
let name = name.clone();
self.check_identifier(&self.tok, &name)?;
// A shorthand `await` counts as one in an async arrow function's head, as a name does.
if name == "await" {
self.awaits = self.awaits.saturating_add(1);
}
let token = self.bump()?;
let target = self.ast.push_expr(Expr::Ident(name.clone()), token.span);
let value = if self.at(Punct::Eq) {
@@ -199,7 +211,7 @@ impl Parser<'_> {
/// the value may still turn out to be a pattern.
fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result<Property> {
if self.at(Punct::LParen) {
let function = self.parse_function_with(FunctionKind::Method, None, start, true, false)?;
let function = self.parse_function_with(FunctionKind::Method, None, start, true, false, false)?;
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
}
self.expect(Punct::Colon)?;
+4 -1
View File
@@ -167,7 +167,7 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() {
#[test]
fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\
let src = "var bad = 0, seen = 0; function check(e) { seen++; if (!(e instanceof TypeError)) bad++; }\n\
for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }";
let mut finished = 0;
for spare in (40_000..240_000).step_by(641) {
@@ -181,6 +181,7 @@ fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
}
r.set_limits(Limits::default());
assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}");
assert_eq!(r.run("seen"), Ok(JsValue::Number(200.0)), "{spare}");
}
assert!(finished > 0);
}
@@ -193,6 +194,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\
Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\
Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\
Promise.all(new String('a\\uD83D\\uDE00')).then(function (v) { log.push('boxed ' + v.length + ' ' + v[1].length); });\n\
Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\
Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\
Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });";
@@ -205,6 +207,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
"rejected:r fulfilled:4",
"race fast",
"chars 2",
"boxed 2 2",
"not a list true",
"no length true",
"bad length true",
+25
View File
@@ -269,12 +269,34 @@ impl Realm {
pub fn set_es2015(&mut self, es2015: bool) {
if self.is_running() || self.interp.waiting {
self.interp.next_es2015 = Some(es2015);
if !es2015 {
self.interp.next_es2017 = Some(false);
}
} else {
self.interp.next_es2015 = None;
self.interp.next_es2017 = None;
self.interp.set_es2015(es2015);
}
}
/// Sets [`Options::es2017`] for the next runs, and for the code they evaluate; on, it also
/// sets [`Options::es2015`]. Async functions an earlier run made keep running when it is
/// turned off. Call [`Realm::add_es2015`] too in a realm made without either option, since
/// an async function needs `Promise`. Like [`Realm::set_es2015`], it applies once a run that
/// is still going ends.
pub fn set_es2017(&mut self, es2017: bool) {
if self.is_running() || self.interp.waiting {
self.interp.next_es2017 = Some(es2017);
if es2017 {
self.interp.next_es2015 = Some(true);
}
} else {
self.interp.next_es2015 = None;
self.interp.next_es2017 = None;
self.interp.set_es2017(es2017);
}
}
/// 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())
@@ -462,6 +484,9 @@ impl Realm {
if let Some(es2015) = interp.next_es2015.take() {
interp.set_es2015(es2015);
}
if let Some(es2017) = interp.next_es2017.take() {
interp.set_es2017(es2017);
}
match result {
Ok(v) => {
self.rejections = interp.take_unhandled();
+169 -21
View File
@@ -31,7 +31,8 @@
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
//! arrow functions, templates, default and rest parameters, classes, `super` and `new.target`,
//! and from ECMAScript 2020 optional chains and `??`) without and with that option, and
//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs
//! prints both counts; its failures with the option, and the runs without it that panicked, go to
//! `es2015-failures.txt`. A sixth test runs
//! the module tests under `test/language/module-code`, `import` and `export` as modules, reading
//! the fixture files they import from the suite, and as scripts for comparison; its failures as
//! modules go to `module-failures.txt`.
@@ -56,8 +57,8 @@
//! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`:
//! those whose feature tags name only `Promise`, `Promise.allSettled` and
//! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests
//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its
//! failures go to `promise-failures.txt`.
//! run with the suite's `doneprintHandle.js` and pass when they print the completion line and no
//! line that starts with the failure prefix. Its failures go to `promise-failures.txt`.
//!
//! 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
@@ -473,7 +474,7 @@ fn uses_missing_builtin(lists: &[Vec<Token>], missing: &HashSet<&str>) -> bool {
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
lists.iter().flatten().any(|t| match &t.kind {
TokenKind::Ident(name) => missing.contains(name.as_str()),
TokenKind::String(units) => {
TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => {
let text = String::from_utf16_lossy(units);
missing.contains(text.as_str())
|| (strings_are_code && text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word)))
@@ -483,12 +484,12 @@ fn uses_missing_builtin(lists: &[Vec<Token>], missing: &HashSet<&str>) -> bool {
}
/// The tokens can run a string as code: they name `eval`, `Function` or a `constructor` property,
/// as an identifier or as a string key (`this["eval"]`), called directly or through an alias.
/// as an identifier or as a string or template key (`this["eval"]`), called directly or through an alias.
/// `Function.prototype` alone does not count.
fn runs_strings_as_code(tokens: &[Token]) -> bool {
const RUNNERS: [&str; 3] = ["eval", "Function", "constructor"];
tokens.iter().enumerate().any(|(i, t)| match &t.kind {
TokenKind::String(units) => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())),
TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())),
TokenKind::Ident(name) if name == "eval" || name == "constructor" => true,
TokenKind::Ident(name) if name == "Function" => {
let prototype = tokens.get(i + 1).is_some_and(|d| d.is_punct(Punct::Dot))
@@ -883,14 +884,26 @@ struct Es2015Counts {
failures: String,
}
impl Es2015Counts {
/// The failures of the run with the option, then each run without it that panicked, marked
/// with `without`.
fn report(after: &Es2015Counts, before: &Es2015Counts, without: &str) -> String {
let mut report = after.failures.clone();
for line in before.failures.lines().filter(|l| l.ends_with(": PANIC")) {
report.push_str(&format!("{line} ({without})\n"));
}
report
}
}
/// Runs the ES2015 subset: the tests under `test/language/` in [`ES2015_FOLDERS`], under
/// `test/built-ins/` in [`ES2015_BUILT_INS`] and those [`es2015_name_test`] picks, whose feature
/// tags are all in [`ES2015_FEATURES`], and the tests elsewhere under `test/language/` with feature
/// tags that are all in it. Negative parse tests must give a `SyntaxError`; the other tests run in a
/// new realm after the harness, as [`run_tests`] runs them, skipping module and asynchronous tests
/// and those that need a missing built-in. Each test is read twice, without and with
/// [`Options::es2015`], and the counts of both are printed; the failures with it go to
/// `es2015-failures.txt`.
/// [`Options::es2015`], and the counts of both are printed; the failures with it, and the runs
/// without it that panicked, go to `es2015-failures.txt`.
fn run_es2015(dir: &Path) {
let language = or_fail(inside(dir, "test/language"));
assert!(language.is_dir(), "{} is not a test262 checkout", dir.display());
@@ -974,7 +987,7 @@ fn run_es2015(dir: &Path) {
assert!(selected > 0, "no ES2015 tests under {}", language.display());
let [before, after] = counts;
let report = dir.join("es2015-failures.txt");
if let Err(e) = std::fs::write(&report, &after.failures) {
if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "without Options::es2015")) {
println!("could not write {}: {e}", report.display());
}
let line = |c: &Es2015Counts| {
@@ -1338,23 +1351,26 @@ fn promise_builtins_run() {
#[test]
fn promise_async_completion_requires_an_exact_print_argument() {
assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true).is_err());
assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true).is_err());
assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true).is_ok());
assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true).is_ok());
let es2015 = Options { es2015: true, ..Options::default() };
assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true, &es2015).is_err());
assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true, &es2015).is_err());
assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true, &es2015).is_ok());
assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true, &es2015).is_ok());
}
#[test]
fn promise_async_failure_checks_each_print_argument() {
assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true).is_err());
assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true).is_ok());
let es2015 = Options { es2015: true, ..Options::default() };
assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true, &es2015).is_err());
assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true, &es2015).is_ok());
}
/// Runs one Promise test with a global `print` that collects every argument. An `async` test
/// needs an exact `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix.
fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> {
let options = Options { es2015: true, ..Options::default() };
let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
/// Runs one test that may be asynchronous in a new realm made with `options` and a global `print`
/// that collects every argument; an `async` test without a runtime negative needs an exact
/// `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix, and one with a
/// runtime negative must throw that error.
fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> {
let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let out = printed.clone();
realm.define_function("print", move |args| {
@@ -1439,7 +1455,8 @@ fn run_promise(dir: &Path) {
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) {
let es2015 = Options { es2015: true, ..Options::default() };
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, &es2015)) {
Ok(Ok(())) => counts.passed += 1,
Ok(Err(why)) => {
counts.failed += 1;
@@ -1740,6 +1757,125 @@ fn run_tagged_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, options: &
counts
}
/// The folders under `test/language/` that hold tests of async functions and `await`.
const ASYNC_FOLDERS: &[&str] = &["expressions/async-function", "statements/async-function", "expressions/await", "expressions/async-arrow-function"];
/// The feature tags an async-function test may carry and still run: [`ES2015_FEATURES`],
/// `async-functions` and `Promise`.
const ASYNC_FEATURES: &[&str] = &["async-functions", "Promise"];
#[test]
fn async_functions_run() {
let Some(dir) = suite_dir() else {
println!("test262 async functions: SKIPPED (no suite; run cargo xtask test262)");
return;
};
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_async_functions(&dir)).unwrap();
handle.join().unwrap();
}
/// Runs the tests in [`ASYNC_FOLDERS`] whose feature tags are all in [`ES2015_FEATURES`] or
/// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative
/// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests
/// included, skipping module tests and those that need a missing built-in. Prints the counts of
/// both and writes the failures with [`Options::es2017`], and the runs with [`Options::es2015`]
/// alone that panicked, to `async-function-failures.txt`.
fn run_async_functions(dir: &Path) {
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
let done = harness("doneprintHandle.js");
let missing = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]);
let es2015 = Options { es2015: true, ..Options::default() };
let es2017 = Options { es2015: true, es2017: true, ..Options::default() };
let editions = [es2015, es2017.clone()];
let mut counts = [Es2015Counts::default(), Es2015Counts::default()];
let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize);
for folder in ASYNC_FOLDERS {
let root = or_fail(inside(dir, &format!("test/language/{folder}")));
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
for path in or_fail(test_files(&root)) {
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
let source = or_fail(read_source(&path));
let meta = meta(&source);
if meta.features.iter().any(|f| !ES2015_FEATURES.contains(&f.as_str()) && !ASYNC_FEATURES.contains(&f.as_str())) {
other_features += 1;
continue;
}
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
if has("module") || meta.negative_phase.as_deref() == Some("resolution") {
skipped += 1;
continue;
}
let asynchronous = has("async");
let expect_error = meta.negative_phase.as_deref() == Some("parse");
let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
if asynchronous {
includes.push_str(&done);
includes.push('\n');
}
if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &es2017) {
skipped += 1;
continue;
}
selected += 1;
for (options, counts) in editions.iter().zip(counts.iter_mut()) {
for &strict in modes(&meta) {
let mode = if strict { "strict" } else { "sloppy" };
let outcome = if expect_error {
let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() };
if parse(&text, options).is_err() {
counts.parse_passed += 1;
continue;
}
counts.parse_failed += 1;
"parsed; a SyntaxError was expected".to_string()
} else {
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, options)) {
Ok(Ok(())) => {
counts.run_passed += 1;
continue;
}
Ok(Err(why)) => {
counts.run_failed += 1;
why
}
Err(_) => {
counts.run_failed += 1;
counts.panicked += 1;
"PANIC".to_string()
}
}
};
counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n"));
}
}
}
}
assert!(selected > 0, "no async-function tests under {}", dir.display());
let [before, after] = counts;
let report = dir.join("async-function-failures.txt");
if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "with Options::es2015 alone")) {
println!("could not write {}: {e}", report.display());
}
let line = |c: &Es2015Counts| {
format!(
"negative parse runs {} passed, {} failed; other runs {} passed, {} failed ({} panicked)",
c.parse_passed, c.parse_failed, c.run_passed, c.run_failed, c.panicked
)
};
println!(
"test262 async functions: {selected} tests. With Options::es2015 alone: {}. With Options::es2017: {}. Skipped {skipped} module \
or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}",
line(&before),
line(&after),
report.display()
);
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display());
}
/// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing.
fn skips(sources: &[&str]) -> bool {
let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect();
@@ -1769,6 +1905,18 @@ fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() {
assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern));
}
#[test]
fn a_missing_name_in_a_template_that_can_run_as_code_skips() {
let missing: HashSet<&str> = ["Map"].into_iter().collect();
let modern = Options { es2015: true, ..Options::default() };
assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern));
assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern));
// A template key names the runner, as a string key does.
assert!(needs_missing_builtin_in(&["this[`eval`](`new Map()`);"], &missing, &modern));
assert!(needs_missing_builtin_in(&[r#"var F = this[`Function`]; F("return new Map()")();"#], &missing, &modern));
assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern));
}
#[test]
fn a_missing_name_in_code_skips() {
assert!(skips(&["var m = new Map();"]));
+19 -2
View File
@@ -2951,10 +2951,14 @@ checks that read a target descriptor also throw `ReferenceError` for an uninitia
The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero;
both properties are nonwritable, nonenumerable and configurable. Its first call clears the revoker's reference
to the proxy. Later calls return `undefined` without revoking another object. A
`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there
`.jsx` file and a `source` string run as scripts read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there
`yield` is a name like any other. A `.js` file
`.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and
accept the ECMAScript 2015 forms listed here. A `.js` file
accept the ECMAScript 2015 forms listed here. A
`.js` file also has `Promise` (described below), and so does a `.jsx` file or a `source` string run with
`module: true`; a `.jsx` file and a `source` string run as scripts do not, except that a named engine
(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps
its globals. A `.js` file
also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`,
`f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or
`null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&`
@@ -3714,6 +3718,19 @@ has them only when a `.js` script started it, and then a later `.jsx` run in it
In such a `.jsx` run, `Object.prototype.toString` gives the ES5.1 result, `[object Object]` or another class name,
and does not read `Symbol.toStringTag`.
A `.js` script, and a `.jsx` file or a `source` string run with `module: true`, also read async functions and `await` as ECMA-262 2017 section 25.5 defines them
(https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions,
async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return`
resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function
goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally`
work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is
reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. In script code
outside an async function `await` is an ordinary name; module code does not accept `await` as a name. In a `.jsx`
file or a `source` string run as a script, `async` and `await` are ordinary names and an async function is a syntax
error. These are VectorCraft's own rules: each time a function resumes
counts as a job and takes 1 unit of fuel, and a function still waiting when no job is left stays suspended, and the
run ends.
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`
+1
View File
@@ -1207,6 +1207,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
- A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. When the trap returns `true`, the call returns the proxy, and the proxy's prototype is whatever the trap left, which may be unchanged for an extensible target. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`.
- With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
- Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`).
- Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report <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`.