diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs
index a473fd57da..0d78c4fd3c 100644
--- a/crates/js/src/async_tests.rs
+++ b/crates/js/src/async_tests.rs
@@ -84,6 +84,23 @@ fn async_functions_are_not_constructors_and_have_no_prototype() {
assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5");
}
+#[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());
+ assert!(parse("var x = ; x.async::b", &options).is_ok());
+}
+
#[test]
fn await_is_an_identifier_outside_async_functions() {
let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\
@@ -98,6 +115,9 @@ fn await_is_an_identifier_outside_async_functions() {
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) {}");
diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs
index 09cb089e5b..f1f8c0a547 100644
--- a/crates/js/src/builtins.rs
+++ b/crates/js/src/builtins.rs
@@ -123,6 +123,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)?;
diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs
index 43eea77b2a..4e3e65a906 100644
--- a/crates/js/src/builtins/async_function.rs
+++ b/crates/js/src/builtins/async_function.rs
@@ -4,7 +4,7 @@
//! reaches through it. `AsyncFunction` is not a global.
use super::{data, dynamic_function, native};
-use crate::heap::{CONFIGURABLE, Class, NativeKind, ObjId, Object};
+use crate::heap::{CONFIGURABLE, Class, NativeKind, Object};
use crate::interp::{Interp, JsResult};
use crate::value::Value;
@@ -16,10 +16,11 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
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);
- // `Function` is the constructor's prototype (section 25.5.2).
- let function_ctor = constructor_of(interp, function_proto);
+ // 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 = function_ctor.or(o.proto);
+ 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
@@ -27,14 +28,6 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE)
}
-/// The `constructor` property `proto` has from the built-ins, when it is an object.
-fn constructor_of(interp: &Interp, proto: ObjId) -> Option {
- match interp.get_own_property(proto, &crate::heap::key("constructor")) {
- Ok(Some(crate::heap::Prop::Data { value: Value::Object(o), .. })) => Some(o),
- _ => None,
- }
-}
-
/// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1).
fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult {
dynamic_function(interp, args, true)
diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs
index 723ad84b40..5dba6c540f 100644
--- a/crates/js/src/bytecode.rs
+++ b/crates/js/src/bytecode.rs
@@ -280,6 +280,11 @@ pub(crate) struct Code {
pub(crate) vars: Vec,
/// 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,
/// The body refers to `arguments` or calls `eval`.
pub(crate) uses_arguments: bool,
pub(crate) source: Rc,
diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs
index 3690ef3e28..aa0feff65f 100644
--- a/crates/js/src/compiler.rs
+++ b/crates/js/src/compiler.rs
@@ -106,6 +106,9 @@ struct FnCompiler<'a> {
struct Hoisted {
vars: Vec,
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,
}
fn key_of(name: &str) -> Key {
@@ -244,7 +247,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 {
let mut out = Hoisted::default();
let mut seen = HashSet::new();
@@ -259,6 +263,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;
@@ -366,7 +371,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)
@@ -1800,6 +1807,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,
@@ -1848,7 +1856,10 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc,
let params: Vec = f.params.iter().map(|p| key_of(&p.name)).collect();
let rest = f.rest.as_ref().map(|r| key_of(&r.name));
let all_params: Vec = params.iter().chain(&rest).cloned().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)?;
let param_init = !f.simple_params();
if param_init {
diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs
index ec09876731..a8a77b723b 100644
--- a/crates/js/src/es2015_tests.rs
+++ b/crates/js/src/es2015_tests.rs
@@ -138,6 +138,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");
@@ -286,6 +308,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'");
diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs
index e25bac7323..c59925c1bb 100644
--- a/crates/js/src/heap.rs
+++ b/crates/js/src/heap.rs
@@ -623,6 +623,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
+ code.functions.len()
+ code.params.len()
+ code.vars.len()
+ + code.annex_vars.len()
+ 2 * code.fun_decls.len()
+ code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::()
+ code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::();
@@ -641,7 +642,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
strings.add(pattern);
strings.add(flags);
}
- let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
+ let keys = code.names.iter().chain(&code.params).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);
}
diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs
index d7a0ef6481..b4fa731b76 100644
--- a/crates/js/src/interp.rs
+++ b/crates/js/src/interp.rs
@@ -92,6 +92,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,
@@ -115,6 +118,7 @@ impl Intrinsics {
Self {
object_proto: o,
function_proto: o,
+ function_ctor: o,
array_proto: o,
string_proto: o,
number_proto: o,
@@ -149,6 +153,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,
@@ -187,6 +192,9 @@ pub(crate) struct Frame {
/// 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.
async_promise: Option,
+ /// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not
+ /// declared: [`Op::AnnexB`] leaves them alone.
+ annex_off: Vec,
}
/// Where the exception being thrown was raised: the code and the instruction.
@@ -471,7 +479,13 @@ 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())))
+}
+
+/// The bytes the `let` and `const` names at the top of a script add to the global scope.
+fn global_lexical_bytes(code: &Code) -> usize {
+ let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets);
+ lets.iter().fold(0usize, |total, (name, _)| total.saturating_add(binding_bytes(name.len())))
}
/// A call to a function written in JavaScript, ready to enter.
@@ -2396,9 +2410,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) {
@@ -2952,6 +2970,7 @@ impl Interp {
completion: Value::Undefined,
boundary,
async_promise: None,
+ annex_off: Vec::new(),
});
// 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.
@@ -3278,14 +3297,16 @@ impl Interp {
(caller_env, caller_var_env)
};
self.stack.truncate(start);
- let env = self.instantiate_pending(&code, env, var_env, true)?;
- self.push_code_frame(code, env, var_env, this, false)
+ let (env, annex_off) = self.instantiate_pending(&code, env, var_env, true)?;
+ self.push_code_frame(code, env, var_env, this, false)?;
+ self.frame_mut()?.annex_off = annex_off;
+ Ok(())
}
/// [`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, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult {
+ fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> {
let mark = self.temp_envs.len();
self.temp_envs.push(env);
self.temp_codes.push(code.clone());
@@ -3311,9 +3332,15 @@ 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, is_eval: bool) -> JsResult<()> {
- self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
+ if self.frames.len() >= self.limits.frames {
+ return Err(Abrupt::Limit(LimitKind::Frames));
+ }
+ let lexical = if is_eval { 0 } else { global_lexical_bytes(&code) };
+ self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(lexical))?;
let (scope, global) = (self.global_scope(), self.global);
let (env, var_env) = if code.strict && is_eval {
let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
@@ -3321,8 +3348,10 @@ impl Interp {
} else {
(scope, self.global_env)
};
- 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`
@@ -3437,6 +3466,7 @@ impl Interp {
completion: Value::Undefined,
boundary,
async_promise: None,
+ annex_off: Vec::new(),
});
Ok(())
}
@@ -3446,8 +3476,9 @@ impl Interp {
///
/// Gives the environment the code runs in: `env`, or with [`Options::es2015`] eval code's own
/// environment of its `let` and `const` names. A script's `let` and `const` names go in the
- /// global scope ([`Self::declare_global_lexical`]).
- fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult {
+ /// global scope ([`Self::declare_global_lexical`]). Also gives the names of
+ /// [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not declare.
+ fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> {
let configurable = if is_eval { CONFIGURABLE } else { 0 };
if is_eval && !code.strict && self.options.es2015 {
self.check_eval_vars(code, env, var_env)?;
@@ -3492,7 +3523,47 @@ impl Interp {
self.global_vars.insert(v.clone());
}
}
- Ok(lex)
+ let mut annex_off = Vec::new();
+ for v in &code.annex_vars {
+ self.use_fuel()?;
+ if !self.annex_var_declarable(v, env, var_env)? {
+ annex_off.push(v.clone());
+ continue;
+ }
+ self.declare(var_env, v, None, configurable)?;
+ if on_global {
+ self.global_vars.insert(v.clone());
+ }
+ }
+ Ok((lex, 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, ): 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 {
+ 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)
}
/// A `var` or function that eval code outside strict mode code declares must not take the name
diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs
index 7121215b9d..9bb7c26cb8 100644
--- a/crates/js/src/interp/async_function.rs
+++ b/crates/js/src/interp/async_function.rs
@@ -147,6 +147,7 @@ impl Interp {
completion: a.completion,
boundary: true,
async_promise: Some(a.promise),
+ annex_off: Vec::new(),
});
Ok(())
}
diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs
index 4a281a7b2f..346c32983a 100644
--- a/crates/js/src/interp_tests.rs
+++ b/crates/js/src/interp_tests.rs
@@ -972,6 +972,7 @@ fn code(ops: Vec) -> Code {
params: Vec::new(),
vars: Vec::new(),
fun_decls: Vec::new(),
+ annex_vars: Vec::new(),
uses_arguments: false,
source,
span: (0, 0),
diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs
index 9478074e73..8a7cef804f 100644
--- a/crates/js/src/parser.rs
+++ b/crates/js/src/parser.rs
@@ -1130,6 +1130,8 @@ impl<'s> Parser<'s> {
let outer_strict = self.ctx.strict;
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 {
@@ -1138,6 +1140,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();
@@ -1553,7 +1556,8 @@ impl<'s> Parser<'s> {
if name == "await" {
self.awaits = self.awaits.saturating_add(1);
}
- if self.at_async() {
+ // 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);
diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs
index 8e03f2a136..fc6d927c70 100644
--- a/crates/js/src/promise_tests.rs
+++ b/crates/js/src/promise_tests.rs
@@ -78,7 +78,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) {
@@ -92,6 +92,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);
}
diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs
index 0fe3badb67..8cd87a33bb 100644
--- a/crates/js/tests/test262.rs
+++ b/crates/js/tests/test262.rs
@@ -30,7 +30,8 @@
//!
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
//! arrow functions, templates, default and rest parameters) without and with that option, and
-//! prints both counts; its failures with the option go to `es2015-failures.txt`.
+//! prints both counts; its failures with the option, and the runs without it that panicked, go to
+//! `es2015-failures.txt`.
//!
//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every
//! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset
@@ -42,8 +43,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`.
//!
//! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses
//! an `includes:` name that leaves the `harness/` folder, and refuses a file over
@@ -695,13 +696,25 @@ 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`] 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());
@@ -779,7 +792,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| {
@@ -869,11 +882,12 @@ fn promise_builtins_run() {
}
/// Runs one test that may be asynchronous in a new realm made with `options` and a global `print`
-/// that collects its output; an `async` test without a runtime negative passes when it prints
-/// `Test262:AsyncTestComplete`, and one with a runtime negative must throw that error.
+/// that collects its output; an `async` test without a runtime negative passes when one `print`
+/// call gives exactly `Test262:AsyncTestComplete` and none gives a value that starts with
+/// `Test262:AsyncTestFailure:`, 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(String::new()));
+ let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let out = printed.clone();
realm.define_function("print", move |args| {
let line = match args.first() {
@@ -881,18 +895,15 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool
Some(other) => format!("{other:?}"),
None => String::new(),
};
- out.borrow_mut().push_str(&line);
- out.borrow_mut().push('\n');
+ out.borrow_mut().push(line);
Ok(JsValue::Undefined)
});
let result = realm.run(script);
if asynchronous && result.is_ok() && negative_type.is_none() {
let printed = printed.borrow();
- return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") {
- Ok(())
- } else {
- Err(format!("printed {:?}", printed.trim()))
- };
+ let complete = printed.iter().any(|l| l == "Test262:AsyncTestComplete");
+ let failed = printed.iter().any(|l| l.starts_with("Test262:AsyncTestFailure:"));
+ return if complete && !failed { Ok(()) } else { Err(format!("printed {:?}", printed.join("\n"))) };
}
match (result, negative_type) {
(Ok(_), None) => Ok(()),
@@ -1014,7 +1025,8 @@ fn async_functions_run() {
/// [`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`] to `async-function-failures.txt`.
+/// 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"));
@@ -1092,7 +1104,7 @@ fn run_async_functions(dir: &Path) {
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, &after.failures) {
+ 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| {