diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs
index 4223d829ba..a024949a35 100644
--- a/crates/engine/src/script/include.rs
+++ b/crates/engine/src/script/include.rs
@@ -217,6 +217,15 @@ pub(crate) struct Files {
levels: usize,
/// The files `$.evalFile` is running, the script first.
frames: Vec ,
+ /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
+ es2015: bool,
+}
+
+/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
+/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
+/// ECMAScript 5.1 with the ExtendScript extensions.
+pub(crate) fn es2015_script(path: Option<&str>) -> bool {
+ path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -311,9 +320,15 @@ impl Files {
chain: real.into_iter().collect(),
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
+ es2015: es2015_script(path),
}
}
+ /// 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, ..Options::default() }
+ }
+
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
pub(crate) fn jsinclude_env() -> Vec {
#[cfg(test)]
@@ -456,7 +471,7 @@ impl Files {
return Ok(());
}
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
- let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
+ let options = Options { preprocessor_lines: true, ..self.options() };
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
let mut cursor = 0usize;
for d in &program.directives {
diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs
index 0e702c0076..a01453a627 100644
--- a/crates/engine/src/script/mod.rs
+++ b/crates/engine/src/script/mod.rs
@@ -1475,7 +1475,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { host.placed(error, f.file, f.line, f.column) } else { error }
})?;
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
- let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
+ let options = host.files.borrow().options();
if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) {
host.files.borrow_mut().end_eval();
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
@@ -1967,11 +1967,16 @@ impl Session {
// A realm made here gets the script extensions, `$` and the dialogs; a kept one has them
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
- let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
+ // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
+ // code the way the script does.
+ let es2015 = include::es2015_script(request.file.as_deref());
+ let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() };
let strict = options.strict;
+ // 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
}
None => {
diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs
index bf8154f9a7..7b0e4bc2f8 100644
--- a/crates/engine/src/tests/script_run.rs
+++ b/crates/engine/src/tests/script_run.rs
@@ -297,6 +297,40 @@ fn files_are_checked_before_they_are_read() {
let _ = std::fs::remove_dir_all(&dir);
}
+#[test]
+fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
+ let dir = fresh_folder("es2015");
+ 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});
+ write("lib.jsxinc", "const k = 2;\nvar twice = n => n * k;\n");
+ write("more.jsx", "let m = `m${k}`;\nm;\n");
+ let modern = "#include \"lib.jsxinc\"\nlet x = [1, ...[2]];\nvc.log(`${twice(x[1])}`);\nvc.log(eval('let e = 5; e'));\nvc.log(new Function('a = 6', 'return a')());\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n";
+ let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap();
+ assert_eq!(r["log"], json!(["4", 5, 6, "m2"]), "{r}");
+ let upper = s.execute("script.run", &path(&write("UPPER.JS", "let u = 1; vc.log(u);"))).unwrap();
+ assert_eq!(upper["log"], json!([1]), "{upper}");
+ for (name, text) in [("legacy.jsx", "let x = 1;"), ("arrow.jsx", "var f = () => 1;"), ("template.jsx", "vc.log(`t`);")] {
+ let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string();
+ assert!(e.contains("SyntaxError"), "{name}: {e}");
+ }
+ // Script text given without a file keeps the ExtendScript language.
+ assert!(run(&mut s, "const c = 1;").unwrap_err().to_string().contains("SyntaxError"));
+ // A named engine reads each run the way that run's script does.
+ s.execute("script.run", &path(&write("first.jsx", "#targetengine kept\nvar kept = 1;"))).unwrap();
+ let modern = s.execute("script.run", &path(&write("second.js", "#targetengine kept\nlet k2 = kept + 1;\nvc.log(k2);"))).unwrap();
+ assert_eq!(modern["log"], json!([2]), "{modern}");
+ let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;")));
+ assert!(legacy.unwrap_err().to_string().contains("SyntaxError"));
+ let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap();
+ assert_eq!(legacy["log"], json!([3]), "{legacy}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
/// A new empty folder for test `name`.
fn fresh_folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs
index 8d9ffc06c0..c015e3fa38 100644
--- a/crates/js/src/ast.rs
+++ b/crates/js/src/ast.rs
@@ -200,6 +200,40 @@ pub enum Expr {
object: ExprId,
predicate: ExprId,
},
+ /// An arrow function.
+ Arrow(FunctionId),
+ /// A template literal: its pieces (one more than its substitutions) and its substitutions,
+ /// in source order.
+ Template {
+ quasis: Vec,
+ exprs: Vec,
+ },
+ /// A tagged template (`` tag`a${b}c` ``): `tag` called with the template object and the
+ /// substitutions.
+ TaggedTemplate {
+ tag: ExprId,
+ quasis: Vec,
+ exprs: Vec,
+ },
+ /// `...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),
+}
+
+/// A piece of a template literal's text between its substitutions.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TemplatePiece {
+ /// The text with its escapes read.
+ pub cooked: Vec,
+ /// The text as written.
+ pub raw: Vec,
+}
+
+/// Which lexical declaration a name has.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LexKind {
+ Let,
+ Const,
}
/// A piece of an XML literal, in source order.
@@ -247,12 +281,17 @@ pub enum ForInTarget {
/// `for (var x in o)`, with the declaration's initializer if it has one.
Var(VarDecl),
Expr(ExprId),
+ /// `for (let x in o)` or `for (const x in o)`: a new binding for each name.
+ Lexical(LexKind, Name),
}
#[derive(Clone, Debug, PartialEq)]
pub enum ForInit {
Var(Vec),
Expr(ExprId),
+ /// `let` or `const` declarations, in a scope of the loop's own with a new copy of each `let`
+ /// binding for each iteration.
+ Lexical(LexKind, Vec),
}
#[derive(Clone, Debug, PartialEq)]
@@ -272,6 +311,8 @@ pub struct CatchClause {
#[derive(Clone, Debug, PartialEq)]
pub enum Stmt {
Var(Vec),
+ /// `let` or `const` declarations (a `const` always has an initializer).
+ Lexical(LexKind, Vec),
FunctionDecl(FunctionId),
Expr(ExprId),
Block(Vec),
@@ -334,13 +375,20 @@ pub enum FunctionKind {
Expression,
Getter,
Setter,
+ /// An arrow function; one with an expression body has a body of one `return` statement.
+ Arrow,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Function {
pub kind: FunctionKind,
pub name: Option,
+ /// The parameters before a rest parameter.
pub params: Vec,
+ /// Each parameter's default value, in the order of `params` (empty when none has one).
+ pub defaults: Vec>,
+ /// The rest parameter (`...name`).
+ pub rest: Option,
pub body: Vec,
/// The function's code is strict mode code: its own directive prologue holds `"use strict"`,
/// or the code around it is strict.
@@ -348,6 +396,13 @@ pub struct Function {
pub span: Span,
}
+impl Function {
+ /// The parameters are plain names: no default value and no rest parameter.
+ pub fn simple_params(&self) -> bool {
+ self.rest.is_none() && self.defaults.iter().all(Option::is_none)
+ }
+}
+
/// The arenas of a parsed script.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Ast {
@@ -412,6 +467,8 @@ pub struct Program {
/// Its preprocessor lines, in source order.
pub directives: Vec,
pub(crate) lines: crate::LineTable,
+ /// It was read with [`crate::Options::es2015`].
+ pub(crate) es2015: bool,
}
impl Program {
diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs
index 380d161ecf..f2c02bdf4c 100644
--- a/crates/js/src/builtins.rs
+++ b/crates/js/src/builtins.rs
@@ -503,7 +503,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)),
};
interp.charge_code(&code, 0)?;
- let env = interp.global_env;
+ let env = interp.global_scope();
interp.make_closure(code, env).map(Value::Object)
}
diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs
index 6992fd5606..28db7edf3d 100644
--- a/crates/js/src/bytecode.rs
+++ b/crates/js/src/bytecode.rs
@@ -178,6 +178,49 @@ pub(crate) enum Op {
ForEachValue(u32),
/// `value` → nothing: sets the default XML namespace of the running code.
SetDefaultNamespace,
+ /// Enters a block's environment: the `let` and `const` names of `scopes[i]`, not yet
+ /// initialized, and its function declarations.
+ PushBlock(u32),
+ /// Replaces the current environment with a copy of it, for a `for` loop's next iteration.
+ CopyEnv,
+ /// `value` → nothing: initializes the nearest binding of `names[i]`, a `let`, a `const` or
+ /// a parameter of a function with default or rest parameters.
+ InitVar(u32),
+ /// Pushes the value of the parameter `names[i]` of the running function, initialized or not.
+ LoadParam(u32),
+ /// Ends the parameters of a function with default or rest parameters: enters the environment
+ /// of its body's variables and function declarations, and of its `let` and `const` names.
+ BodyEnv,
+ /// `value` → nothing: assigns the function declared in a block outside strict mode code to
+ /// the variable `names[i]` of the running code (ECMA-262 2015 Annex B.3.3).
+ AnnexB(u32),
+ /// `array value` → `array`, with the elements of the value appended (spread).
+ ArraySpread,
+ /// `function this array` → result: a call with the array's elements as its arguments, a
+ /// direct eval when `eval` is true and the function is the global `eval`.
+ CallSpread(bool),
+ /// `function array` → the new object, constructed with the array's elements as arguments.
+ NewSpread,
+ /// `value` → its string (a template literal's substitution).
+ ToStr,
+ /// Pushes the template object of `templates[i]`, the same object for each evaluation.
+ TemplateObject(u32),
+}
+
+/// The names a block declares, entered with [`Op::PushBlock`].
+#[derive(Debug, Default)]
+pub(crate) struct BlockScope {
+ /// The `let` and `const` names, each with whether it is a `const`.
+ pub(crate) lets: Vec<(Key, bool)>,
+ /// The function declarations: their names and indices in `functions`.
+ pub(crate) funcs: Vec<(Key, u32)>,
+}
+
+/// A tagged template's strings: as read and as written.
+#[derive(Debug)]
+pub(crate) struct Template {
+ pub(crate) cooked: Vec,
+ pub(crate) raw: Vec,
}
/// What code is: a function body, a script, or eval code.
@@ -239,6 +282,23 @@ pub(crate) struct Code {
pub(crate) source: Rc,
/// Where the function's text starts and ends in the source.
pub(crate) span: (u32, u32),
+ /// The block scopes [`Op::PushBlock`] enters.
+ pub(crate) scopes: Vec,
+ /// The scope of the `let` and `const` names at the top of the body, script or eval code.
+ pub(crate) top_scope: Option,
+ /// The tagged templates [`Op::TemplateObject`] makes objects of.
+ pub(crate) templates: Vec,
+ /// The rest parameter's name.
+ pub(crate) rest: Option,
+ /// The function's `length`: its parameters before the first with a default value.
+ pub(crate) length: u32,
+ /// The code is an arrow function's.
+ pub(crate) arrow: bool,
+ /// The code reads `this` or calls `eval`, itself or in an arrow function inside it.
+ pub(crate) uses_this: bool,
+ /// The function has default or rest parameters: its parameters start uninitialized, its
+ /// code initializes them and then enters its body with [`Op::BodyEnv`].
+ pub(crate) param_init: bool,
}
impl Code {
@@ -315,6 +375,12 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result {
Op::XmlScopeRef => e(1, 2),
Op::ForEachValue(n) => e(n + 2, n + 3),
Op::SetDefaultNamespace => e(1, 0),
+ Op::PushBlock(_) | Op::CopyEnv | Op::BodyEnv => e(0, 0),
+ Op::InitVar(_) | Op::AnnexB(_) => e(1, 0),
+ Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1),
+ Op::ArraySpread | Op::NewSpread => e(2, 1),
+ Op::CallSpread(_) => e(3, 1),
+ Op::ToStr => e(1, 1),
})
}
@@ -341,8 +407,13 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> {
| Op::InitProp(i)
| Op::InitGetter(i)
| Op::InitSetter(i)
- | Op::PushCatch(i) => check(i, code.names.len(), "name"),
+ | Op::PushCatch(i)
+ | Op::InitVar(i)
+ | Op::LoadParam(i)
+ | Op::AnnexB(i) => check(i, code.names.len(), "name"),
Op::Closure(i) => check(i, code.functions.len(), "function"),
+ Op::PushBlock(i) => check(i, code.scopes.len(), "scope"),
+ Op::TemplateObject(i) => check(i, code.templates.len(), "template"),
Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"),
_ => Ok(()),
}
@@ -363,9 +434,15 @@ pub(crate) fn verify(code: &Code) -> Result {
return Err("a function declaration without a name".into());
}
}
- if code.fun_decls.iter().any(|(_, i)| *i as usize >= code.functions.len()) {
+ if code.fun_decls.iter().chain(code.scopes.iter().flat_map(|s| &s.funcs)).any(|(_, i)| *i as usize >= code.functions.len()) {
return Err("function declaration index out of range".into());
}
+ if code.top_scope.is_some_and(|i| i as usize >= code.scopes.len()) {
+ return Err("top scope out of range".into());
+ }
+ if code.templates.iter().any(|t| t.cooked.len() != t.raw.len()) {
+ return Err("a template whose strings do not match".into());
+ }
let mut depth: Vec> = vec![None; len];
let mut work: Vec<(u32, u32)> = vec![(0, 0)];
for h in &code.handlers {
diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs
index 3023e3b127..7563545715 100644
--- a/crates/js/src/compiler.rs
+++ b/crates/js/src/compiler.rs
@@ -17,10 +17,10 @@ use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use crate::ast::{
- AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LogicalOp, PropertyValue, Stmt, StmtId, UnaryOp, UpdateOp,
- VarDecl, XmlNamePart, XmlPart, XmlQualifier,
+ AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId,
+ TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
};
-use crate::bytecode::{Code, CodeKind, Handler, Op, Source, fallthrough_effect, verify};
+use crate::bytecode::{BlockScope, Code, CodeKind, Handler, Op, Source, Template, fallthrough_effect, verify};
use crate::error::{SyntaxError, TOO_DEEP};
use crate::heap::Key;
use crate::value::Str;
@@ -88,6 +88,17 @@ struct FnCompiler<'a> {
contexts: Vec,
uses_arguments: bool,
recursion: u32,
+ /// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own.
+ es2015: bool,
+ scopes: Vec,
+ templates: Vec,
+ uses_this: bool,
+ /// The function declarations at the top of the body, which are var-scoped.
+ top_funcs: HashSet,
+ /// The function declarations a block scope instantiates.
+ block_funcs: HashSet,
+ /// The names of functions declared in blocks that are also var-scoped (Annex B.3.3).
+ annex: HashSet,
}
/// The `var` names and function declarations a body hoists.
@@ -128,6 +139,13 @@ impl<'a> FnCompiler<'a> {
contexts: Vec::new(),
uses_arguments: false,
recursion,
+ es2015: false,
+ scopes: Vec::new(),
+ templates: Vec::new(),
+ uses_this: false,
+ top_funcs: HashSet::new(),
+ block_funcs: HashSet::new(),
+ annex: HashSet::new(),
}
}
@@ -222,59 +240,98 @@ impl<'a> FnCompiler<'a> {
/// Collects the `var` names and function declarations of a body, outside nested functions,
/// in source order, and compiles the functions.
- fn hoist(&mut self, body: &[StmtId]) -> CResult {
+ /// With [`crate::Options::es2015`], only the function declarations at the top of the body are
+ /// 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.
+ fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult {
let mut out = Hoisted::default();
let mut seen = HashSet::new();
- let mut work: Vec = body.iter().rev().copied().collect();
- let mut add_var = |out: &mut Hoisted, d: &VarDecl| {
- let k = key_of(&d.name.name);
+ // The `let` and `const` names of each statement list and loop the walk enters, with the
+ // index of the one around it; the body's are first.
+ let mut scopes: Vec<(Option, HashSet)> = vec![(None, self.lexical_names(body))];
+ let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
+ let mut add_var = |out: &mut Hoisted, k: Key| {
if seen.insert(k.clone()) {
out.vars.push(k);
}
};
- while let Some(id) = work.pop() {
+ let mut annex: Vec<(Key, usize)> = Vec::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;
+ let mut enter = |names: HashSet| {
+ scopes.push((Some(scope), names));
+ scopes.len() - 1
+ };
match stmt {
- Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, d)),
+ Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))),
+ Stmt::Lexical(..) => {}
Stmt::FunctionDecl(fid) => {
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
return internal("function declaration without a name");
};
let k = key_of(&name.name);
- let i = self.function(*fid)?;
- out.fun_decls.push((k, i));
- }
- Stmt::Block(list) => work.extend(list.iter().rev()),
- Stmt::If { consequent, alternate, .. } => {
- work.extend(alternate.iter());
- work.push(*consequent);
- }
- Stmt::DoWhile { body, .. } | Stmt::While { body, .. } | Stmt::With { body, .. } | Stmt::Labeled { body, .. } => work.push(*body),
- Stmt::For { init, body, .. } => {
- work.push(*body);
- if let Some(ForInit::Var(decls)) = init {
- decls.iter().for_each(|d| add_var(&mut out, d));
+ if self.es2015 && nested {
+ if !self.strict {
+ annex.push((k, scope));
+ }
+ } else {
+ let i = self.function(*fid)?;
+ out.fun_decls.push((k, i));
+ self.top_funcs.insert(id);
}
}
+ Stmt::Block(list) => {
+ let s = enter(self.lexical_names(list));
+ work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
+ }
+ Stmt::If { consequent, alternate, .. } => {
+ work.extend(alternate.iter().map(|&s| (s, nested || inner, scope)));
+ work.push((*consequent, nested || inner, scope));
+ }
+ Stmt::Labeled { body, .. } => work.push((*body, nested, scope)),
+ Stmt::DoWhile { body, .. } | Stmt::While { body, .. } | Stmt::With { body, .. } => work.push((*body, nested || inner, scope)),
+ Stmt::For { init, body, .. } => {
+ let s = match init {
+ Some(ForInit::Var(decls)) => {
+ decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name)));
+ scope
+ }
+ Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect()),
+ _ => scope,
+ };
+ work.push((*body, nested || inner, s));
+ }
Stmt::ForIn { target, body, .. } => {
- work.push(*body);
- if let ForInTarget::Var(d) = target {
- add_var(&mut out, d);
- }
+ let s = match target {
+ ForInTarget::Var(d) => {
+ add_var(&mut out, key_of(&d.name.name));
+ scope
+ }
+ ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)])),
+ ForInTarget::Expr(_) => scope,
+ };
+ work.push((*body, nested || inner, s));
}
Stmt::Switch { cases, .. } => {
+ let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
+ let s = enter(names);
for case in cases.iter().rev() {
- work.extend(case.body.iter().rev());
+ work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
}
}
Stmt::Try { block, handler, finalizer } => {
if let Some(f) = finalizer {
- work.extend(f.iter().rev());
+ let s = enter(self.lexical_names(f));
+ work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
}
if let Some(h) = handler {
- work.extend(h.body.iter().rev());
+ let s = enter(self.lexical_names(&h.body));
+ work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
}
- work.extend(block.iter().rev());
+ let s = enter(self.lexical_names(block));
+ work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
}
Stmt::Expr(_)
| Stmt::Empty
@@ -286,12 +343,99 @@ impl<'a> FnCompiler<'a> {
| Stmt::DefaultXmlNamespace(_) => {}
}
}
+ for (k, scope) in annex {
+ let mut cur = Some(scope);
+ let mut clash = params.contains(&k) || *k == *key_of("arguments");
+ while let Some((outer, names)) = cur.and_then(|i| scopes.get(i)).filter(|_| !clash) {
+ clash = names.contains(&k);
+ cur = *outer;
+ }
+ if !clash {
+ self.annex.insert(k.clone());
+ add_var(&mut out, k);
+ }
+ }
Ok(out)
}
+ /// The `let` and `const` names a statement list declares.
+ fn lexical_names(&self, list: &[StmtId]) -> HashSet {
+ list.iter()
+ .filter_map(|&s| match self.ast.stmt(s) {
+ Some(Stmt::Lexical(_, decls)) => Some(decls.iter().map(|d| key_of(&d.name.name))),
+ _ => None,
+ })
+ .flatten()
+ .collect()
+ }
+
+ /// The scope a statement list declares with [`crate::Options::es2015`]: its `let` and
+ /// `const` names, and (`functions`) its function declarations. `None` when it declares none.
+ fn list_scope(&mut self, list: &[StmtId], functions: bool) -> CResult> {
+ if !self.es2015 {
+ return Ok(None);
+ }
+ let mut scope = BlockScope::default();
+ for &s in list {
+ match self.ast.stmt(s) {
+ Some(Stmt::Lexical(kind, decls)) => scope.lets.extend(decls.iter().map(|d| (key_of(&d.name.name), *kind == LexKind::Const))),
+ Some(Stmt::FunctionDecl(fid)) if functions && !self.top_funcs.contains(&s) => {
+ let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
+ return internal("function declaration without a name");
+ };
+ let k = key_of(&name.name);
+ let i = self.function(*fid)?;
+ scope.funcs.push((k, i));
+ self.block_funcs.insert(s);
+ }
+ _ => {}
+ }
+ }
+ if scope.lets.is_empty() && scope.funcs.is_empty() {
+ return Ok(None);
+ }
+ Ok(Some(self.push_scope(scope)))
+ }
+
+ fn push_scope(&mut self, scope: BlockScope) -> u32 {
+ self.scopes.push(scope);
+ len_u32(self.scopes.len() - 1)
+ }
+
+ /// A block's statements, in an environment of their own when they declare `let`, `const` or
+ /// (with [`crate::Options::es2015`]) functions.
+ fn block(&mut self, list: &[StmtId]) -> CResult<()> {
+ let Some(scope) = self.list_scope(list, true)? else { return self.stmts(list) };
+ self.emit(Op::PushBlock(scope));
+ self.env_depth += 1;
+ self.stmts(list)?;
+ self.emit(Op::PopEnv);
+ self.env_depth -= 1;
+ Ok(())
+ }
+
+ /// `let` or `const` declarations: each binding initialized with its value or `undefined`.
+ fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
+ for d in decls {
+ match d.init {
+ Some(init) => self.expr(init)?,
+ None => self.emit(Op::Undefined),
+ }
+ self.at(d.name.span.start);
+ let n = self.var_name(&d.name.name);
+ self.emit(Op::InitVar(n));
+ }
+ Ok(())
+ }
+
/// Compiles a nested function and returns its index in the function table.
fn function(&mut self, fid: FunctionId) -> CResult {
- let code = compile_function(self.ast, fid, self.source, self.recursion, true)?;
+ let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?;
+ // An arrow function reads the `this` and `arguments` of the code around it.
+ if code.arrow {
+ self.uses_this |= code.uses_this;
+ self.uses_arguments |= code.uses_arguments;
+ }
self.functions.push(code);
Ok(u32::try_from(self.functions.len() - 1).unwrap_or(u32::MAX))
}
@@ -319,13 +463,15 @@ impl<'a> FnCompiler<'a> {
self.at(self.ast.stmt_span(id).start);
match stmt {
Stmt::Var(decls) => self.var_decls(decls),
- Stmt::FunctionDecl(_) | Stmt::Empty | Stmt::Debugger => Ok(()),
+ Stmt::Lexical(_, decls) => self.lexical_decls(decls),
+ Stmt::FunctionDecl(fid) => self.function_decl(id, *fid),
+ Stmt::Empty | Stmt::Debugger => Ok(()),
Stmt::Expr(e) => {
self.expr(*e)?;
self.emit(if self.kind == CodeKind::Function { Op::Pop } else { Op::SetCompletion });
Ok(())
}
- Stmt::Block(list) => self.stmts(list),
+ Stmt::Block(list) => self.block(list),
Stmt::If { .. } => self.if_chain(id),
Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. } => self.loop_stmt(id, Vec::new()),
Stmt::Continue(label) => self.jump_stmt(label.as_ref().map(|l| l.name.as_str()), true),
@@ -363,6 +509,30 @@ impl<'a> FnCompiler<'a> {
}
}
+ /// A function declaration where it stands. One at the top of the body was instantiated on
+ /// entry, and one in a block when the block was entered; outside strict mode code, one in a
+ /// block (or standing alone as an `if` branch) is also assigned to its variable here
+ /// (Annex B.3.3 and B.3.4).
+ fn function_decl(&mut self, id: StmtId, fid: FunctionId) -> CResult<()> {
+ if !self.es2015 || self.top_funcs.contains(&id) {
+ return Ok(());
+ }
+ let Some(name) = self.ast.function(fid).and_then(|f| f.name.as_ref()) else { return internal("function declaration without a name") };
+ let k = key_of(&name.name);
+ if !self.annex.contains(&k) {
+ return Ok(());
+ }
+ let n = self.name_key(k);
+ if self.block_funcs.contains(&id) {
+ self.emit(Op::GetVar(n));
+ } else {
+ let i = self.function(fid)?;
+ self.emit(Op::Closure(i));
+ }
+ self.emit(Op::AnnexB(n));
+ Ok(())
+ }
+
fn var_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
for d in decls {
if let Some(init) = d.init {
@@ -456,9 +626,13 @@ impl<'a> FnCompiler<'a> {
self.expr(*test)?;
self.jump(Op::JumpIfTrue, top);
}
+ Some(Stmt::For { init: Some(ForInit::Lexical(kind, decls)), test, update, body }) => {
+ return self.for_lexical(*kind, decls, *test, *update, *body, labels, brk, cont);
+ }
Some(Stmt::For { init, test, update, body }) => {
match init {
Some(ForInit::Var(decls)) => self.var_decls(decls)?,
+ Some(ForInit::Lexical(..)) => return internal("lexical for loop"),
Some(ForInit::Expr(e)) => {
self.expr(*e)?;
self.emit(Op::Pop);
@@ -486,7 +660,105 @@ impl<'a> FnCompiler<'a> {
Ok(())
}
+ /// `for (let …; test; update) body` or `for (const …; …)`: the declarations in a scope of the
+ /// loop's own, copied for each iteration of a `let` loop before the update runs, so a closure
+ /// made in one iteration keeps that iteration's bindings (ECMA-262 2015 section 13.7.4.7).
+ #[allow(clippy::too_many_arguments)]
+ fn for_lexical(
+ &mut self,
+ kind: LexKind,
+ decls: &[VarDecl],
+ test: Option,
+ update: Option,
+ body: StmtId,
+ labels: Vec,
+ brk: Label,
+ cont: Label,
+ ) -> CResult<()> {
+ let scope = BlockScope { lets: decls.iter().map(|d| (key_of(&d.name.name), kind == LexKind::Const)).collect(), funcs: Vec::new() };
+ let scope = self.push_scope(scope);
+ self.emit(Op::PushBlock(scope));
+ self.env_depth += 1;
+ self.lexical_decls(decls)?;
+ let per_iteration = kind == LexKind::Let;
+ if per_iteration {
+ self.emit(Op::CopyEnv);
+ }
+ let head = self.new_label();
+ self.bind(head);
+ if let Some(t) = test {
+ self.expr(t)?;
+ self.jump(Op::JumpIfFalse, brk);
+ }
+ self.loop_body(body, labels, brk, cont)?;
+ self.bind(cont);
+ if per_iteration {
+ self.emit(Op::CopyEnv);
+ }
+ if let Some(u) = update {
+ self.expr(u)?;
+ self.emit(Op::Pop);
+ }
+ self.jump(Op::Jump, head);
+ self.bind(brk);
+ self.emit(Op::PopEnv);
+ self.env_depth -= 1;
+ Ok(())
+ }
+
+ /// `for (let x in o)`, `for (const x in o)` and `for each` with them: the object read where
+ /// `x` is not yet initialized, then a new binding of `x` for each name.
+ fn for_in_lexical(
+ &mut self,
+ kind: LexKind,
+ name: &crate::ast::Name,
+ object: ExprId,
+ body: StmtId,
+ labels: Vec,
+ each: bool,
+ ) -> CResult<()> {
+ let scope = self.push_scope(BlockScope { lets: vec![(key_of(&name.name), kind == LexKind::Const)], funcs: Vec::new() });
+ self.emit(Op::PushBlock(scope));
+ self.env_depth += 1;
+ self.expr(object)?;
+ self.emit(Op::PopEnv);
+ self.env_depth -= 1;
+ self.emit(Op::ForInStart);
+ let iter_depth = self.depth;
+ let head = self.new_label();
+ let brk = self.new_label();
+ self.bind(head);
+ self.jump(Op::ForInNext, brk);
+ let outer_env = self.env_depth;
+ self.emit(Op::PushBlock(scope));
+ self.env_depth += 1;
+ self.at(name.span.start);
+ let n = self.var_name(&name.name);
+ if each {
+ // The value initializes the binding; the name under it goes next.
+ self.emit(Op::ForEachValue(0));
+ self.emit(Op::InitVar(n));
+ self.emit(Op::Pop);
+ } else {
+ self.emit(Op::InitVar(n));
+ }
+ self.contexts.push(Ctx::Jump { labels, is_loop: true, plain_break: true, brk, cont: Some(head), depth: self.depth, env_depth: outer_env });
+ let r = self.stmt(body);
+ self.contexts.pop();
+ r?;
+ self.emit(Op::PopEnv);
+ self.env_depth -= 1;
+ self.jump(Op::Jump, head);
+ self.bind(brk);
+ self.depth = iter_depth;
+ self.emit(Op::Pop);
+ Ok(())
+ }
+
fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec, each: bool) -> CResult<()> {
+ if let ForInTarget::Lexical(kind, name) = target {
+ return self.for_in_lexical(*kind, name, object, body, labels, each);
+ }
if let ForInTarget::Var(d) = target {
self.var_decls(std::slice::from_ref(d))?;
}
@@ -507,6 +779,7 @@ impl<'a> FnCompiler<'a> {
}
ForInTarget::Expr(e) if each => self.store_value_to(*e)?,
ForInTarget::Expr(e) => self.store_key_to(*e)?,
+ ForInTarget::Lexical(..) => return internal("lexical for-in loop"),
}
if each {
// The value; the name under it goes next.
@@ -607,6 +880,12 @@ impl<'a> FnCompiler<'a> {
fn switch_stmt(&mut self, id: StmtId, labels: Vec) -> CResult<()> {
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
self.expr(*discriminant)?;
+ let all: Vec = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
+ let scope = self.list_scope(&all, true)?;
+ if let Some(scope) = scope {
+ self.emit(Op::PushBlock(scope));
+ self.env_depth += 1;
+ }
let d = self.depth;
let brk = self.new_label();
let case_labels: Vec = cases.iter().map(|_| self.new_label()).collect();
@@ -632,6 +911,10 @@ impl<'a> FnCompiler<'a> {
self.contexts.pop();
self.bind(brk);
self.depth = d;
+ if scope.is_some() {
+ self.emit(Op::PopEnv);
+ self.env_depth -= 1;
+ }
self.emit(Op::Pop);
Ok(())
}
@@ -746,7 +1029,7 @@ impl<'a> FnCompiler<'a> {
self.contexts.push(Ctx::Finally { try_depth, env_depth, entry: fin_entry, exits: Vec::new() });
}
let start = self.pc();
- self.stmts(block)?;
+ self.block(block)?;
if let Some(h) = handler {
let after = self.new_label();
let catch = self.new_label();
@@ -759,7 +1042,7 @@ impl<'a> FnCompiler<'a> {
let n = self.var_name(&h.param.name);
self.emit(Op::PushCatch(n));
self.env_depth += 1;
- self.stmts(&h.body)?;
+ self.block(&h.body)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
self.bind(after);
@@ -779,7 +1062,7 @@ impl<'a> FnCompiler<'a> {
if keeps_completion {
self.emit(Op::GetCompletion);
}
- self.stmts(fin)?;
+ self.block(fin)?;
if keeps_completion {
self.emit(Op::SetCompletion);
}
@@ -822,7 +1105,10 @@ impl<'a> FnCompiler<'a> {
let Some(e) = self.ast.expr(id) else { return internal("expression out of range") };
self.at(self.ast.expr_span(id).start);
match e {
- Expr::This => self.emit(Op::This),
+ Expr::This => {
+ self.uses_this = true;
+ self.emit(Op::This);
+ }
Expr::Ident(name) => {
let n = self.var_name(name);
self.emit(Op::GetVar(n));
@@ -843,10 +1129,7 @@ impl<'a> FnCompiler<'a> {
self.emit(Op::NewArray);
for el in elements {
match el {
- Some(e) => {
- self.expr(*e)?;
- self.emit(Op::ArrayPush);
- }
+ Some(e) => self.array_element(*e)?,
None => self.emit(Op::ArrayHole),
}
}
@@ -857,12 +1140,25 @@ impl<'a> FnCompiler<'a> {
self.emit(Op::Closure(i));
}
Expr::Member { .. } | Expr::Index { .. } | Expr::Call { .. } => self.chain(id)?,
+ Expr::New { callee, args } if self.has_spread(args) => {
+ self.expr(*callee)?;
+ self.spread_args(args)?;
+ self.at(self.ast.expr_span(id).start);
+ self.emit(Op::NewSpread);
+ }
Expr::New { callee, args } => {
self.expr(*callee)?;
self.args(args)?;
self.at(self.ast.expr_span(id).start);
self.emit(Op::New(len_u32(args.len())));
}
+ Expr::Arrow(fid) => {
+ let i = self.function(*fid)?;
+ self.emit(Op::Closure(i));
+ }
+ Expr::Template { quasis, exprs } => self.template(quasis, exprs)?,
+ Expr::TaggedTemplate { .. } => self.chain(id)?,
+ Expr::Spread(_) => return internal("spread outside an array literal or argument list"),
Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?,
Expr::Unary { .. } => self.unary(id)?,
Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?,
@@ -985,6 +1281,62 @@ impl<'a> FnCompiler<'a> {
Ok(())
}
+ fn has_spread(&self, args: &[ExprId]) -> bool {
+ args.iter().any(|&a| matches!(self.ast.expr(a), Some(Expr::Spread(_))))
+ }
+
+ /// `array` → `array` with the element appended: a value, or a spread's elements.
+ fn array_element(&mut self, e: ExprId) -> CResult<()> {
+ if let Some(Expr::Spread(arg)) = self.ast.expr(e) {
+ self.expr(*arg)?;
+ self.at(self.ast.expr_span(e).start);
+ self.emit(Op::ArraySpread);
+ } else {
+ self.expr(e)?;
+ self.emit(Op::ArrayPush);
+ }
+ Ok(())
+ }
+
+ /// Pushes an array of the arguments, for a call or `new` with a spread among them.
+ fn spread_args(&mut self, args: &[ExprId]) -> CResult<()> {
+ self.emit(Op::NewArray);
+ for &a in args {
+ self.array_element(a)?;
+ }
+ Ok(())
+ }
+
+ /// A template literal: its pieces joined with the strings of its substitutions.
+ fn template(&mut self, quasis: &[TemplatePiece], exprs: &[ExprId]) -> CResult<()> {
+ let Some((first, rest)) = quasis.split_first() else { return internal("template without pieces") };
+ let i = self.string(&first.cooked);
+ self.emit(Op::String(i));
+ if rest.len() != exprs.len() {
+ return internal("template pieces do not match its substitutions");
+ }
+ for (piece, &e) in rest.iter().zip(exprs) {
+ self.expr(e)?;
+ self.at(self.ast.expr_span(e).start);
+ self.emit(Op::ToStr);
+ self.emit(Op::Binary(BinaryOp::Add));
+ if !piece.cooked.is_empty() {
+ let i = self.string(&piece.cooked);
+ self.emit(Op::String(i));
+ self.emit(Op::Binary(BinaryOp::Add));
+ }
+ }
+ Ok(())
+ }
+
+ /// Adds a tagged template's strings to the template table and returns their index.
+ fn template_entry(&mut self, quasis: &[TemplatePiece]) -> u32 {
+ let cooked = quasis.iter().map(|q| Str::from_units(q.cooked.clone())).collect();
+ let raw = quasis.iter().map(|q| Str::from_units(q.raw.clone())).collect();
+ self.templates.push(Template { cooked, raw });
+ len_u32(self.templates.len() - 1)
+ }
+
fn object_literal(&mut self, props: &[crate::ast::Property]) -> CResult<()> {
self.emit(Op::NewObject);
for p in props {
@@ -1022,14 +1374,15 @@ impl<'a> FnCompiler<'a> {
suffixes.push(cur);
cur = self.ast.unparenthesized(*object);
}
- Some(Expr::Call { callee, .. }) => {
+ Some(Expr::Call { callee, .. } | Expr::TaggedTemplate { tag: callee, .. }) => {
suffixes.push(cur);
cur = self.ast.unparenthesized(*callee);
}
_ => break,
}
}
- let is_call = |c: &Self, e: Option<&ExprId>| e.is_some_and(|&e| matches!(c.ast.expr(e), Some(Expr::Call { .. })));
+ let is_call =
+ |c: &Self, e: Option<&ExprId>| e.is_some_and(|&e| matches!(c.ast.expr(e), Some(Expr::Call { .. } | Expr::TaggedTemplate { .. })));
let first_is_call = is_call(self, suffixes.last());
let mut base_has_this = false;
let mut eval_call = false;
@@ -1068,7 +1421,7 @@ impl<'a> FnCompiler<'a> {
self.at(span.start);
self.xml_filter(*predicate)?;
}
- Some(Expr::Call { args, .. }) => {
+ Some(call @ (Expr::Call { .. } | Expr::TaggedTemplate { .. })) => {
let innermost = j + 1 == count;
let has_this = if innermost {
base_has_this
@@ -1078,14 +1431,37 @@ impl<'a> FnCompiler<'a> {
if !has_this {
self.emit(Op::Undefined);
}
- self.args(args)?;
- self.at(span.start);
- let n = len_u32(args.len());
- if innermost && eval_call {
- self.uses_arguments = true;
- self.emit(Op::CallEval(n));
- } else {
- self.emit(Op::Call(n));
+ let eval = match call {
+ Expr::TaggedTemplate { quasis, exprs, .. } => {
+ let t = self.template_entry(quasis);
+ self.at(span.start);
+ self.emit(Op::TemplateObject(t));
+ self.args(exprs)?;
+ self.at(span.start);
+ self.emit(Op::Call(len_u32(exprs.len()).saturating_add(1)));
+ continue;
+ }
+ Expr::Call { args, .. } => {
+ let eval = innermost && eval_call;
+ if eval {
+ self.uses_arguments = true;
+ self.uses_this = true;
+ }
+ if self.has_spread(args) {
+ self.spread_args(args)?;
+ self.at(span.start);
+ self.emit(Op::CallSpread(eval));
+ continue;
+ }
+ self.args(args)?;
+ self.at(span.start);
+ (eval, len_u32(args.len()))
+ }
+ _ => return internal("not a call"),
+ };
+ match eval {
+ (true, n) => self.emit(Op::CallEval(n)),
+ (false, n) => self.emit(Op::Call(n)),
}
}
_ => return internal("not a member or call"),
@@ -1379,6 +1755,14 @@ impl<'a> FnCompiler<'a> {
uses_arguments: self.uses_arguments,
source: self.source.clone(),
span: meta.span,
+ scopes: std::mem::take(&mut self.scopes),
+ top_scope: meta.top_scope,
+ templates: std::mem::take(&mut self.templates),
+ rest: meta.rest,
+ length: meta.length,
+ arrow: meta.arrow,
+ uses_this: self.uses_this,
+ param_init: meta.param_init,
};
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
Ok(Rc::new(code))
@@ -1392,6 +1776,11 @@ struct Meta {
decl_name: Option,
params: Vec,
span: (u32, u32),
+ top_scope: Option,
+ rest: Option,
+ length: u32,
+ arrow: bool,
+ param_init: bool,
}
fn len_u32(n: usize) -> u32 {
@@ -1399,23 +1788,63 @@ fn len_u32(n: usize) -> u32 {
}
/// Compiles function `fid` of `ast`. With `bind_name`, a function expression's name is bound
-/// inside it.
-pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, recursion: u32, bind_name: bool) -> CResult> {
+/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in.
+pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, recursion: u32, bind_name: bool, es2015: bool) -> CResult> {
let Some(f) = ast.function(fid) else { return internal("function out of range") };
let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion);
+ c.es2015 = es2015;
c.at(f.span.start);
c.enter()?;
- let hoisted = c.hoist(&f.body)?;
+ 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 top_scope = c.list_scope(&f.body, false)?;
+ let param_init = !f.simple_params();
+ if param_init {
+ // Each parameter is initialized in order, from its argument or, when that is
+ // `undefined`, its default value; then the body's environment is entered.
+ for (i, p) in f.params.iter().enumerate() {
+ c.at(p.span.start);
+ let n = c.var_name(&p.name);
+ c.emit(Op::LoadParam(n));
+ if let Some(Some(default)) = f.defaults.get(i) {
+ let skip = c.new_label();
+ c.emit(Op::Dup);
+ c.emit(Op::Undefined);
+ c.emit(Op::Binary(BinaryOp::StrictEq));
+ c.jump(Op::JumpIfFalse, skip);
+ c.emit(Op::Pop);
+ c.expr(*default)?;
+ c.bind(skip);
+ }
+ c.at(p.span.start);
+ c.emit(Op::InitVar(n));
+ }
+ if let Some(r) = &f.rest {
+ c.at(r.span.start);
+ let n = c.var_name(&r.name);
+ c.emit(Op::LoadParam(n));
+ c.emit(Op::InitVar(n));
+ }
+ c.emit(Op::BodyEnv);
+ }
c.stmts(&f.body)?;
c.at(f.span.end.saturating_sub(1));
c.emit(Op::Undefined);
c.emit(Op::Return);
let name = f.name.as_ref().map(|n| key_of(&n.name));
+ let length = f.defaults.iter().position(Option::is_some).unwrap_or(params.len());
let meta = Meta {
decl_name: if f.kind == FunctionKind::Declaration { name.clone() } else { None },
self_name: if bind_name && f.kind == FunctionKind::Expression { name } else { None },
- params: f.params.iter().map(|p| key_of(&p.name)).collect(),
+ params,
span: (f.span.start, f.span.end),
+ top_scope,
+ rest,
+ length: len_u32(length),
+ arrow: f.kind == FunctionKind::Arrow,
+ param_init,
};
c.finish(hoisted, meta)
}
@@ -1423,11 +1852,13 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc,
/// Compiles a script (`kind` [`CodeKind::Global`]) or eval code ([`CodeKind::Eval`]).
pub(crate) fn compile_program(program: &crate::Program, source: &Rc, kind: CodeKind) -> CResult> {
let mut c = FnCompiler::new(&program.ast, source, kind, program.strict, 0);
- let hoisted = c.hoist(&program.body)?;
+ c.es2015 = program.es2015;
+ let hoisted = c.hoist(&program.body, &[])?;
+ let top_scope = c.list_scope(&program.body, false)?;
c.stmts(&program.body)?;
c.emit(Op::ReturnCompletion);
let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX);
- c.finish(hoisted, Meta { span: (0, end), ..Meta::default() })
+ c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
}
/// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program
@@ -1438,5 +1869,5 @@ pub(crate) fn compile_constructed_function(program: &crate::Program, source: &Rc
let Some(Stmt::Expr(e)) = program.ast.stmt(*stmt) else { return Ok(None) };
let Some(Expr::Paren(inner)) = program.ast.expr(*e) else { return Ok(None) };
let Some(Expr::Function(fid)) = program.ast.expr(*inner) else { return Ok(None) };
- compile_function(&program.ast, *fid, source, 0, false).map(Some)
+ compile_function(&program.ast, *fid, source, 0, false, program.es2015).map(Some)
}
diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs
new file mode 100644
index 0000000000..a5d5d2acc0
--- /dev/null
+++ b/crates/js/src/es2015_tests.rs
@@ -0,0 +1,466 @@
+use proptest::prelude::*;
+
+use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind};
+
+fn es_options() -> Options {
+ Options { es2015: true, ..Options::default() }
+}
+
+fn es() -> Realm {
+ Realm::with_options(es_options(), Limits::default())
+}
+
+fn run(src: &str) -> JsValue {
+ match es().run(src) {
+ Ok(v) => v,
+ Err(e) => panic!("{src}\n{e:?}"),
+ }
+}
+
+fn truth(src: &str) {
+ assert_eq!(run(src), JsValue::Bool(true), "{src}");
+}
+
+fn string(src: &str) -> String {
+ match run(src) {
+ JsValue::String(s) => s,
+ other => panic!("{src}: {other:?}"),
+ }
+}
+
+/// The script throws an error whose message starts with `name`.
+fn throws(src: &str, name: &str) {
+ match es().run(src) {
+ Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"),
+ other => panic!("{src}: {other:?}"),
+ }
+}
+
+/// The script does not parse.
+fn syntax(src: &str) {
+ match es().run(src) {
+ Err(RunError { kind: RunErrorKind::Syntax, .. }) => {}
+ other => panic!("{src}: {other:?}"),
+ }
+}
+
+// ---- let and const ----
+
+#[test]
+fn let_and_const_are_scoped_to_their_block() {
+ truth("let x = 1; { let x = 2; } x === 1");
+ truth("var r = []; { const c = 3; r.push(c); } r[0] === 3 && typeof c === 'undefined'");
+ truth("function f() { if (true) { let y = 5; } return typeof y; } f() === 'undefined'");
+ truth("let a = 1, b = a + 1; b === 2");
+ truth("switch (0) { case 0: let s = 6; case 1: s += 1; } typeof s === 'undefined'");
+ // The cases share one scope, so a case that skips the declaration finds the binding uninitialized.
+ throws("switch (1) { case 0: let s = 0; break; case 1: s = 7; }", "ReferenceError");
+ truth("try { throw 1 } catch (e) { let e2 = e + 1; } typeof e2 === 'undefined'");
+}
+
+#[test]
+fn a_binding_is_unusable_before_its_declaration_runs() {
+ throws("x; let x = 1;", "ReferenceError");
+ throws("{ x = 2; let x; }", "ReferenceError");
+ throws("typeof x; const x = 1;", "ReferenceError");
+ throws("function f() { return v; } f(); let v = 1;", "ReferenceError");
+ throws("let q = q;", "ReferenceError");
+ throws("for (let k in k) {}", "ReferenceError");
+ // A declaration without an initializer initializes to undefined where it stands.
+ truth("let u; u === undefined");
+ // A function that runs after the declaration sees the binding.
+ truth("function g() { return w; } let w = 4; g() === 4");
+}
+
+#[test]
+fn assigning_a_const_is_a_type_error_in_any_code() {
+ throws("const c = 1; c = 2;", "TypeError");
+ throws("'use strict'; const c = 1; c = 2;", "TypeError");
+ throws("const c = 1; c++;", "TypeError");
+ throws("const c = 1; c += 1;", "TypeError");
+ throws("for (const i = 0; i < 2; i++) {}", "TypeError");
+ truth("const o = {}; o.x = 1; o.x === 1");
+}
+
+#[test]
+fn redeclarations_and_bad_declarations_are_syntax_errors() {
+ syntax("let a; let a;");
+ syntax("let a; var a;");
+ syntax("var a; let a;");
+ syntax("const a = 1; function a() {}");
+ syntax("{ let a; { var a; } }");
+ syntax("function f(p) { let p; }");
+ syntax("try {} catch (e) { let e; }");
+ syntax("const c;");
+ syntax("let let = 1;");
+ syntax("let [a] = [1];");
+ syntax("'use strict'; { function f() {} function f() {} }");
+ syntax("for (let x = 1 in {}) {}");
+ syntax("if (1) let x = 1;");
+ // Outside strict mode code `let` is still a name where no declaration can start.
+ truth("var let = 3; let === 3");
+ truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
+}
+
+#[test]
+fn a_let_loop_gives_each_iteration_its_own_binding() {
+ truth("var fs = []; for (let i = 0; i < 3; i++) { fs.push(function() { return i; }); } fs[0]() === 0 && fs[1]() === 1 && fs[2]() === 2");
+ truth("var fs = []; for (let i = 0; i < 3; i++) { fs.push(() => i); i += 0; } fs.map(function(f) { return f(); }).join() === '0,1,2'");
+ truth("var fs = []; for (let k in {a: 1, b: 2}) { fs.push(function() { return k; }); } fs[0]() === 'a' && fs[1]() === 'b'");
+ truth("var fs = []; for (const k in {a: 1, b: 2}) { fs.push(() => k); } fs[0]() + fs[1]() === 'ab'");
+ // `continue` and `break` leave the iteration's environment.
+ truth("var s = 0; for (let i = 0; i < 5; i++) { if (i === 1) continue; if (i === 3) break; s += i; } s === 2");
+ truth("var s = ''; for (let k in {a: 1, b: 2, c: 3}) { if (k === 'b') continue; s += k; } s === 'ac'");
+ truth("var i = 'outer'; for (let i = 0; i < 1; i++) {} i === 'outer'");
+}
+
+#[test]
+fn functions_declared_in_blocks_are_scoped_to_the_block() {
+ truth("'use strict'; { function f() { return 1; } } typeof f === 'undefined'");
+ // Outside strict mode code the name is also a variable, assigned when the declaration runs.
+ truth("var before = typeof f; { function f() { return 1; } } before === 'undefined' && f() === 1");
+ truth("{ let x = 2; function g() { return x; } } g() === 2");
+ truth("function h() { if (true) { function inner() { return 'i'; } } return inner(); } h() === 'i'");
+ // Only a `let` or `const` around the declaration, or a parameter, keeps the name from being a variable.
+ truth("function f() { { let g; } { function g() {} } return typeof g; } f() === 'function'");
+ truth("function f() { let g = 1; { function g() {} } return g; } f() === 1");
+ truth("function f() { { let g = 1; { function g() {} } } return typeof g; } f() === 'undefined'");
+ truth("function f() { for (let g = 0; g < 1; g++) { function g() {} } return typeof g; } f() === 'undefined'");
+ truth("function f(g) { { function g() {} } return g; } f(5) === 5");
+}
+
+#[test]
+fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
+ let mut realm = es();
+ assert_eq!(realm.run("let kept = 5; const fixed = 1; kept"), Ok(JsValue::Number(5.0)));
+ assert_eq!(realm.run("kept + fixed"), Ok(JsValue::Number(6.0)));
+ assert_eq!(realm.run("this.kept === undefined"), Ok(JsValue::Bool(true)));
+ let again = realm.run("let kept = 6;");
+ assert!(matches!(&again, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{again:?}");
+ let var = realm.run("var fixed;");
+ assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}");
+ assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0)));
+ let restricted = realm.run("let undefined = 1;");
+ assert!(restricted.is_err(), "{restricted:?}");
+}
+
+#[test]
+fn eval_code_keeps_its_let_and_const_to_itself() {
+ truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'");
+ truth("function f() { eval('var v = 2; let l = 3;'); return v + typeof l; } f() === '2undefined'");
+ truth("let outer = 4; eval('outer') === 4");
+ truth("(0, eval)('let g = 5; g') === 5");
+ // A variable eval code declares cannot take the name of a `let` or `const` around it.
+ throws("let x; eval('var x;');", "SyntaxError");
+ throws("let x; (0, eval)('var x;');", "SyntaxError");
+ throws("function f() { let y; { eval('var y;'); } } f();", "SyntaxError");
+ throws("{ let z; eval('function z() {}'); }", "SyntaxError");
+ throws("{ function w() {} eval('var w;'); }", "SyntaxError");
+ truth("function f() { let y; return eval(\"'use strict'; var y = 1; y\"); } f() === 1");
+ truth("try { throw 1; } catch (e) { eval('var e = 2;'); } true");
+ truth("function f() { { let v; } eval('var v = 3;'); return v; } f() === 3");
+ // Nor, in a default parameter's value, the name of a parameter; the body can.
+ throws("var n = 0; function f(a = eval('var a = 1')) { n++; } try { f(); } finally { n === 0 || ok; }", "SyntaxError");
+ truth("function f(a = eval('var b = 1; b')) { return a; } f() === 1");
+ truth("function f(a = 0) { eval('var a = 2;'); return a; } f() === 2");
+ // Nothing is declared when the check fails.
+ truth("let a; try { eval('var b; var a;'); } catch (e) {} typeof b === 'undefined'");
+}
+
+// ---- arrow functions ----
+
+#[test]
+fn arrow_functions_take_this_and_arguments_from_around_them() {
+ truth("var o = { v: 1, f: function() { return () => this.v; } }; o.f()() === 1");
+ truth("var o = { v: 1, f: function() { return () => () => this.v; } }; o.f()()() === 1");
+ truth("function f() { return (() => arguments[0])(); } f(7) === 7");
+ truth("var o = { v: 2, f: function() { var g = () => this.v; return g.call({ v: 3 }); } }; o.f() === 2");
+ truth("var o = { f: function() { return () => eval('this'); } }; o.f()() === o");
+ truth("(() => this)() === this");
+}
+
+#[test]
+fn arrow_functions_have_expression_and_block_bodies() {
+ truth("var f = x => x * 2; f(4) === 8");
+ truth("var f = (a, b) => a + b; f(1, 2) === 3");
+ truth("var f = () => { return 3; }; f() === 3");
+ truth("var f = () => ({ a: 1 }); f().a === 1");
+ truth("var f = (a = 2, ...r) => a + r.length; f(undefined, 1, 2) === 4");
+ truth("var f = x => y => x + y; f(1)(2) === 3");
+ truth("var t = true ? () => 1 : () => 2; t() === 1");
+ truth("[1, 2, 3].map(x => x + 1).join() === '2,3,4'");
+ truth("var f = (x) => x in { a: 1 }; f('a')");
+ truth("var f = a => {}; f() === undefined");
+}
+
+#[test]
+fn arrow_functions_cannot_be_constructed() {
+ truth("var f = () => 1; f.prototype === undefined && f.length === 0 && !f.hasOwnProperty('prototype')");
+ throws("var f = () => 1; new f();", "TypeError");
+ throws("var f = () => 1; var b = f.bind(null); new b();", "TypeError");
+ truth("((a, b) => 0).length === 2");
+}
+
+#[test]
+fn bad_arrow_functions_are_syntax_errors() {
+ syntax("var f = x\n=> x;");
+ syntax("var f = (x, x) => 1;");
+ syntax("var f = (a, ...b, c) => 1;");
+ syntax("var f = ((a)) => 1;");
+ syntax("var f = (a + 1) => 1;");
+ syntax("var f = (...a);");
+ syntax("var f = ();");
+ syntax("'use strict'; var f = eval => 1;");
+ syntax("var f = (a = 1) => { 'use strict'; };");
+ syntax("1 + () => 2;");
+}
+
+// ---- template literals ----
+
+#[test]
+fn template_literals_join_their_pieces_and_substitutions() {
+ assert_eq!(string("`a${1 + 1}b${'c'}`"), "a2bc");
+ assert_eq!(string("``"), "");
+ assert_eq!(string("`${'x'}`"), "x");
+ assert_eq!(string("var o = { toString: function() { return 'T'; }, valueOf: function() { return 'V'; } }; `${o}`"), "T");
+ assert_eq!(string("`a${`b${'c'}d`}e`"), "abcde");
+ assert_eq!(string("`line\nnext`"), "line\nnext");
+ assert_eq!(string("`cr\r\nlf`"), "cr\nlf");
+ assert_eq!(string("`\\u{41}\\x42\\u0043`"), "ABC");
+ assert_eq!(string("`a\\\nb`"), "ab");
+ assert_eq!(string("`{${1}}`"), "{1}");
+ assert_eq!(string("`$`"), "$");
+ assert_eq!(string("`\\${1}`"), "${1}");
+ // Substitutions run left to right.
+ assert_eq!(string("var s = ''; `${s += 'a'}${s += 'b'}`; s"), "ab");
+}
+
+#[test]
+fn tagged_templates_get_one_frozen_strings_object_for_each_site() {
+ truth("function tag(s, a, b) { return s.length === 3 && s[0] === 'x' && s[1] === '' && s[2] === 'y' && a === 1 && b === 2; } tag`x${1}${2}y`");
+ truth("function tag(s) { return s.raw[0]; } tag`a\\nb` === 'a\\\\nb'");
+ truth("function tag(s) { return s[0]; } tag`a\\nb` === 'a\\nb'");
+ truth("function tag(s) { return s; } function f() { return tag`k`; } f() === f()");
+ truth("function tag(s) { return s; } tag`k` !== tag`k`");
+ truth(
+ "function tag(s) { return Object.isFrozen(s) && Object.isFrozen(s.raw) && !Object.getOwnPropertyDescriptor(s, 'raw').enumerable; } tag`a${0}b`",
+ );
+ truth("var o = { v: 1, m: function(s) { return this.v; } }; o.m`x` === 1");
+ truth("function tag(s) { return s.raw.join('|'); } tag`a\r\nb${0}\\\r\nc` === 'a\\nb|\\\\\\nc'");
+}
+
+#[test]
+fn bad_template_literals_are_syntax_errors() {
+ syntax("`abc");
+ syntax("`${1`");
+ syntax("`\\01`");
+ syntax("`\\1`");
+ syntax("`\\xZ`");
+ syntax("`\\u{110000}`");
+ syntax("function t() {} t`\\u`");
+}
+
+// ---- default and rest parameters ----
+
+#[test]
+fn default_parameters_apply_to_undefined_arguments_in_order() {
+ truth("function f(a, b = a + 1) { return b; } f(1) === 2 && f(1, 5) === 5 && f(1, undefined) === 2 && f(1, null) === null");
+ truth("var n = 0; function f(a = ++n, b = ++n) { return [a, b].join(); } f() === '1,2' && f(9) === '9,3'");
+ throws("function f(a = b, b) {} f();", "ReferenceError");
+ throws("function f(a = a) {} f();", "ReferenceError");
+ truth("function f(a, b = 1, c) {} f.length === 1");
+ truth("function f(a, ...r) {} f.length === 1");
+ // A function with defaults has an arguments object that does not follow the parameters.
+ truth("function f(a = 0) { a = 9; return arguments[0]; } f(1) === 1");
+ truth("function f(a = 0) { arguments[0] = 9; return a; } f(1) === 1");
+ // The body's variables start with the parameter's value and are kept apart from it.
+ truth("function f(a = 1) { var a; return a; } f() === 1");
+ truth("function f(a = 1, g = () => a) { var a = 2; return g(); } f() === 1");
+ truth("var x = 'outer'; function f(a = () => x) { var x = 'inner'; return a(); } f() === 'outer'");
+}
+
+#[test]
+fn rest_parameters_collect_the_remaining_arguments() {
+ truth("function f(a, ...r) { return Array.isArray(r) && r.length === 2 && r[0] === 2 && r[1] === 3; } f(1, 2, 3)");
+ truth("function f(...r) { return r.length; } f() === 0");
+ truth("function f(...r) { r.push(1); return r.length; } f(0) === 2");
+ syntax("function f(...r, a) {}");
+ syntax("function f(...r = []) {}");
+ syntax("function f(a, a = 1) {}");
+ syntax("function f(...a) { 'use strict'; }");
+ // Already strict mode code too.
+ syntax("'use strict'; function f(a = 1) { 'use strict'; }");
+ syntax("'use strict'; var f = (...a) => { 'use strict'; };");
+ syntax("var o = { set s(...v) {} };");
+}
+
+// ---- spread ----
+
+#[test]
+fn spread_expands_arrays_strings_and_array_like_objects() {
+ truth("var a = [1, 2]; var b = [0, ...a, 3]; b.join() === '0,1,2,3' && b.length === 4");
+ truth("var b = [...'a\\uD83D\\uDE00b']; b.length === 3 && b[1] === '\\uD83D\\uDE00'");
+ truth("var b = [...{ length: 2, 0: 'x', 1: 'y' }]; b.join() === 'x,y'");
+ truth("var b = [...[1, , 3]]; b.length === 3 && 1 in b && b[1] === undefined");
+ truth("var b = [, ...[1]]; b.length === 2 && !(0 in b)");
+ truth("function f() { return arguments.length; } f(...[1, 2], 3, ...[]) === 3");
+ truth("function f(a, b) { return a + b; } f(...[1, 2]) === 3");
+ truth("var o = { v: 1, m: function(x) { return this.v + x; } }; o.m(...[1]) === 2");
+ truth("function C(a, b) { this.s = a + b; } new C(...[1, 2]).s === 3");
+ truth("Math.max(...[1, 5, 2]) === 5");
+ truth("var s = ''; function f() {} f((s += 'a', 0), ...(s += 'b', []), (s += 'c', 0)); s === 'abc'");
+ truth("function f() { return arguments; } var a = f(...'ab'); a[0] === 'a' && a[1] === 'b'");
+ truth("eval(...['1 + 1']) === 2");
+}
+
+#[test]
+fn spreading_other_values_is_a_type_error() {
+ throws("[...1];", "TypeError");
+ throws("[...null];", "TypeError");
+ throws("[...undefined];", "TypeError");
+ throws("[...{}];", "TypeError");
+ throws("Math.max(...true);", "TypeError");
+ throws("new Array(...{ a: 1 });", "TypeError");
+}
+
+#[test]
+fn spread_and_templates_stay_within_the_limits() {
+ let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
+ let e = realm.run("[...{ length: 4294967294 }]").unwrap_err();
+ assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
+ let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: 4 << 20, ..Limits::default() });
+ let e = realm.run("var s = 'x'; for (var i = 0; i < 22; i++) s += s; [...s]").unwrap_err();
+ assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}");
+ throws("function f() {} f(...{ length: 100000 });", "RangeError");
+ throws("var a = []; a.length = 4294967294; [0, ...a];", "RangeError");
+}
+
+#[test]
+fn new_scopes_survive_collections_while_they_are_made() {
+ // Heaps just big enough make the collector run while function bodies and blocks set up their
+ // scopes; each run gives the right total or stops at the heap limit.
+ let src = "var total = 0; \
+ function f(a = 1, ...r) { let x = a + r.length; const y = 1; function g() { return x + y; } function h() { return g(); } var junk = [a, a, a]; return h(); } \
+ for (var i = 0; i < 300; i++) { { let b = i; function k() { return b; } function m() { return k(); } total += f(1, 2) + m() - i; } } total";
+ let mut completed = 0;
+ for kib in (16..400).step_by(2) {
+ let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: kib << 10, ..Limits::default() });
+ match realm.run(src) {
+ Ok(v) => {
+ assert_eq!(v, JsValue::Number(900.0), "{kib} KiB");
+ completed += 1;
+ }
+ Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{kib} KiB: {e:?}"),
+ }
+ }
+ assert!(completed > 0);
+}
+
+#[test]
+fn nested_arrows_and_templates_stay_within_the_depth_limit() {
+ let deep = format!("{}0", "x => ".repeat(400));
+ let e = es().run(&deep).unwrap_err();
+ assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
+ let deep = format!("{}1{}", "`${".repeat(300), "}`".repeat(300));
+ let e = es().run(&deep).unwrap_err();
+ assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
+ assert_eq!(string(&format!("{}1{}", "`${".repeat(50), "}`".repeat(50))), "1");
+}
+
+#[test]
+fn for_each_takes_let_and_const_with_e4x() {
+ let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default());
+ let src = "var fs = []; for each (let v in [1, 2]) { fs.push(() => v); } \
+ var s = 0; for each (const w in { a: 3, b: 4 }) { s += w; } \
+ fs[0]() + fs[1]() + s === 10 && typeof v === 'undefined'";
+ assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
+ let e = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()).run("for each (let a = 1 in []) {}").unwrap_err();
+ assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
+}
+
+// ---- the language mode ----
+
+#[test]
+fn without_the_option_the_new_forms_are_syntax_errors() {
+ for src in ["let x = 1; x", "const c = 1;", "var f = x => x;", "`t`", "function f(a = 1) {}", "function f(...r) {}", "f(...a)", "[...a]"] {
+ let r = Realm::new().run(src);
+ assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
+ }
+ // `let` stays a name outside strict mode code.
+ assert_eq!(Realm::new().run("var let = 1; let"), Ok(JsValue::Number(1.0)));
+}
+
+#[test]
+fn code_made_at_run_time_reads_the_realm_s_language() {
+ truth("eval('let a = 1; `${a}`') === '1'");
+ truth("new Function('a = 2', 'return a')() === 2");
+ truth("Function('...r', 'return r.length')(1, 2) === 2");
+ let legacy = Realm::new().run("eval('let a = 1;')");
+ assert!(matches!(&legacy, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{legacy:?}");
+}
+
+// ---- robustness ----
+
+const FRAGMENTS: &[&str] = &[
+ "let ",
+ "const ",
+ "var ",
+ "x",
+ "y",
+ "=",
+ "=>",
+ "(",
+ ")",
+ "{",
+ "}",
+ "[",
+ "]",
+ "...",
+ ",",
+ ";",
+ "`",
+ "${",
+ "a",
+ "1",
+ "+",
+ "function ",
+ "f",
+ "return ",
+ "for (",
+ " in ",
+ "if (",
+ "this",
+ "arguments",
+ "new ",
+ "\n",
+ "'use strict';",
+ ".",
+ "?",
+ ":",
+ "\\",
+ "switch (",
+ "case ",
+ "default:",
+ "break;",
+];
+
+proptest! {
+ #![proptest_config(ProptestConfig::with_cases(256))]
+
+ #[test]
+ fn arbitrary_es2015_fragment_programs_never_panic(parts in proptest::collection::vec(0..FRAGMENTS.len(), 0..60)) {
+ let src: String = parts.iter().map(|&i| FRAGMENTS[i]).collect();
+ let mut realm = Realm::with_options(es_options(), Limits { fuel: 20_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 });
+ if let Err(e) = realm.run(&src) {
+ prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}");
+ }
+ }
+
+ #[test]
+ fn arbitrary_es2015_text_never_panics(src in "[`$\\{\\}=>.()a-c1 ;,\\[\\]\\\\\n]{0,80}") {
+ let mut realm = Realm::with_options(es_options(), Limits { fuel: 20_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 });
+ if let Err(e) = realm.run(&src) {
+ prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}");
+ }
+ }
+}
diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs
index f612b00138..0750204403 100644
--- a/crates/js/src/heap.rs
+++ b/crates/js/src/heap.rs
@@ -345,6 +345,26 @@ pub(crate) struct Binding {
pub(crate) value: Value,
pub(crate) mutable: bool,
pub(crate) deletable: bool,
+ /// A `let`, `const` or parameter binding not yet initialized: reading or writing it is a
+ /// `ReferenceError` (its temporal dead zone).
+ pub(crate) uninitialized: bool,
+ /// A `const` binding: writing it is a `TypeError`, in strict mode code or not.
+ pub(crate) constant: bool,
+ /// A `let` or `const` binding, or a function declared in a block: a `var` that eval code
+ /// declares cannot take its name.
+ pub(crate) lexical: bool,
+}
+
+impl Binding {
+ /// An initialized binding.
+ pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self {
+ Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false }
+ }
+
+ /// A `let` (or with `constant`, a `const`) binding not yet initialized.
+ pub(crate) fn lexical(constant: bool) -> Self {
+ Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true }
+ }
}
/// An environment record (section 10.2.1) with its outer environment.
@@ -596,7 +616,9 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
+ code.functions.len()
+ code.params.len()
+ code.vars.len()
- + 2 * code.fun_decls.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::();
let tables = code.finally_tables.iter().map(|t| 24 + 4 * t.len()).sum::();
strings.bytes += CODE_BYTES
+ size_of::() * code.ops.len()
@@ -613,9 +635,15 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
strings.add(flags);
}
let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
- for k in keys.chain(&code.self_name).chain(&code.decl_name) {
+ for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) {
strings.add_key(k);
}
+ for scope in &code.scopes {
+ scope.lets.iter().map(|(k, _)| k).chain(scope.funcs.iter().map(|(k, _)| k)).for_each(|k| strings.add_key(k));
+ }
+ for t in &code.templates {
+ t.cooked.iter().chain(&t.raw).for_each(|s| strings.add(s));
+ }
stack.extend(code.functions.iter().map(|f| &**f));
}
}
diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs
index 24c33d2fc5..d0cf12bcfd 100644
--- a/crates/js/src/interp.rs
+++ b/crates/js/src/interp.rs
@@ -44,6 +44,10 @@ pub(crate) enum Abrupt {
pub(crate) type JsResult = Result;
+/// The binding that holds an arrow function's `this` in the environment it closes over. It starts
+/// with a NUL, which no identifier holds.
+const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73];
+
fn internal(message: &str) -> JsResult {
Err(Abrupt::Internal(message.into()))
}
@@ -219,8 +223,16 @@ pub(crate) struct Interp {
pub(crate) frames: Vec ,
/// Values native code holds while it may run JavaScript.
pub(crate) temp_roots: Vec,
+ /// Environments native code is still building.
+ temp_envs: Vec,
pub(crate) global: ObjId,
pub(crate) global_env: EnvId,
+ /// With [`Options::es2015`], the declarative environment inside `global_env` that holds the
+ /// `let` and `const` names of the scripts the realm runs.
+ pub(crate) global_lex: Option,
+ /// 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, ObjId)>,
pub(crate) intrinsics: Intrinsics,
pub(crate) limits: Limits,
pub(crate) options: Options,
@@ -491,13 +503,17 @@ impl Interp {
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 });
+ let global_lex = options.es2015.then(|| heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(global_env) }));
let mut interp = Self {
heap,
stack: Vec::new(),
frames: Vec::new(),
temp_roots: Vec::new(),
+ temp_envs: Vec::new(),
global,
global_env,
+ global_lex,
+ template_objects: std::collections::HashMap::new(),
intrinsics: Intrinsics::placeholder(),
fuel: u64::MAX,
// The built-ins are installed without limits; the realm's limits apply from the
@@ -775,6 +791,11 @@ impl Interp {
roots.objects.extend(self.intrinsics.all());
roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects));
roots.envs.push(self.global_env);
+ roots.envs.extend(self.global_lex);
+ roots.envs.extend(self.temp_envs.iter().copied());
+ // A template object stays while its code can still run.
+ self.template_objects.retain(|_, (code, _)| Rc::strong_count(code) > 1);
+ roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
self.heap.collect(&roots);
// The collection counts the live total again, so bytes already released are not in it.
self.held.released.set(0);
@@ -1057,6 +1078,21 @@ impl Interp {
Op::XmlFilterEnd => self.op_xml_filter_end(),
Op::ForEachValue(n) => self.op_for_each_value(n as usize),
Op::SetDefaultNamespace => self.op_set_default_namespace(),
+ Op::PushBlock(i) => self.op_push_block(i),
+ Op::CopyEnv => self.op_copy_env(),
+ Op::InitVar(n) => self.op_init_var(n),
+ Op::LoadParam(n) => self.op_load_param(n),
+ Op::BodyEnv => self.op_body_env(),
+ Op::AnnexB(n) => self.op_annex_b(n),
+ Op::ArraySpread => self.op_array_spread(),
+ Op::CallSpread(eval) => self.op_call_spread(eval),
+ Op::NewSpread => self.op_new_spread(),
+ Op::ToStr => {
+ let v = self.peek(0)?;
+ let s = self.to_str(&v)?;
+ self.replace(1, Value::String(s))
+ }
+ Op::TemplateObject(i) => self.op_template_object(i),
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
}
}
@@ -1172,6 +1208,16 @@ impl Interp {
self.throw(ErrorType::Reference, &format!("{ident} is not defined"))
}
+ /// The binding `name` of the declarative environment `env` is in its temporal dead zone.
+ fn uninitialized(&self, env: EnvId, name: &[u16]) -> bool {
+ matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
+ }
+
+ fn not_initialized(&mut self, name: &[u16]) -> Abrupt {
+ let ident = String::from_utf16_lossy(name);
+ self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized"))
+ }
+
fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> {
let r = self.resolve(name)?;
self.get_resolved(r, name)
@@ -1180,6 +1226,7 @@ impl Interp {
/// GetValue of a reference whose base was resolved earlier (section 8.7.1).
fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> {
match r {
+ Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
Resolved::Obj { object, with_this } => {
let v = self.get_value(&Value::Object(object), name)?;
@@ -1198,6 +1245,11 @@ impl Interp {
fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> {
let strict = self.strict();
match r {
+ Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
+ Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => {
+ let ident = String::from_utf16_lossy(name);
+ Err(self.type_error(&format!("assignment to the constant '{ident}'")))
+ }
Resolved::Decl(e) => {
let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(e) else { return internal("not a declarative environment") };
match bindings.get_mut(name) {
@@ -2013,8 +2065,19 @@ impl Interp {
fn op_closure(&mut self, i: u32) -> JsResult<()> {
let frame = self.frame()?;
- let env = frame.env;
+ let (env, this) = (frame.env, frame.this.clone());
let Some(code) = frame.code.functions.get(i as usize).cloned() else { return internal("function out of range") };
+ // An arrow function keeps the `this` of the code it is made in (ECMA-262 2015 section
+ // 14.2.16), in an environment of its own that only the call reads.
+ let env = if code.arrow && code.uses_this {
+ self.reserve_heap(ENV_BYTES + binding_bytes(ARROW_THIS.len()))?;
+ let mut bindings = PropMap::default();
+ bindings.insert(Rc::from(ARROW_THIS), Binding::new(this, false, false));
+ self.heap.bytes += string_bytes(ARROW_THIS.len());
+ self.heap.alloc_env(Env::Decl { bindings, outer: Some(env) })
+ } else {
+ env
+ };
let f = self.make_closure(code, env)?;
self.push(Value::Object(f))
}
@@ -2026,11 +2089,16 @@ impl Interp {
None => env,
};
let proto = self.intrinsics.function_proto;
- let params = code.params.len();
+ let length = code.length;
let strict = code.strict;
+ let arrow = code.arrow;
let self_name = code.self_name.clone();
let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto)));
- self.define(f, key("length"), Prop::Data { value: Value::Number(params as f64), flags: 0 })?;
+ self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?;
+ // An arrow function has no `prototype` and cannot be constructed (section 14.2.16).
+ if arrow {
+ 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 })?;
@@ -2041,7 +2109,7 @@ impl Interp {
}
}
if let Some(name) = self_name {
- self.env_insert(env, name, Binding { value: Value::Object(f), mutable: false, deletable: false })?;
+ self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?;
}
Ok(f)
}
@@ -2083,7 +2151,7 @@ impl Interp {
let outer = self.frame()?.env;
let mut bindings = PropMap::default();
let name_bytes = string_bytes(name.len());
- bindings.insert(name, Binding { value: v, mutable: true, deletable: false });
+ bindings.insert(name, Binding::new(v, true, false));
let env = self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) });
self.heap.bytes += name_bytes;
let frame = self.frame_mut()?;
@@ -2104,6 +2172,276 @@ impl Interp {
Ok(())
}
+ fn op_push_block(&mut self, i: u32) -> JsResult<()> {
+ let frame = self.frame()?;
+ let (code, outer) = (frame.code.clone(), frame.env);
+ let env = self.block_env(&code, i, outer)?;
+ let frame = self.frame_mut()?;
+ frame.env = env;
+ frame.env_depth += 1;
+ Ok(())
+ }
+
+ /// A copy of the current environment's bindings in a new environment with the same outer
+ /// one (ECMA-262 2015 section 13.7.4.9). Each binding takes a unit of fuel.
+ fn op_copy_env(&mut self) -> JsResult<()> {
+ let env = self.frame()?.env;
+ let Some(Env::Decl { bindings, outer }) = self.heap.env(env) else { return internal("not a declarative environment") };
+ let (count, outer) = (bindings.len(), *outer);
+ let bytes = bindings.iter().map(|(k, _)| binding_bytes(k.len())).sum::();
+ for _ in 0..count {
+ self.use_fuel()?;
+ }
+ self.reserve_heap(ENV_BYTES.saturating_add(bytes))?;
+ let Some(Env::Decl { bindings, .. }) = self.heap.env(env) else { return internal("not a declarative environment") };
+ let copy = bindings.clone();
+ let name_bytes = copy.iter().map(|(k, _)| string_bytes(k.len())).sum::();
+ let new = self.heap.alloc_env(Env::Decl { bindings: copy, outer });
+ self.heap.bytes += name_bytes;
+ self.frame_mut()?.env = new;
+ Ok(())
+ }
+
+ /// The nearest declarative binding of `name` from the current environment out.
+ fn find_binding(&self, name: &[u16]) -> JsResult> {
+ let mut cur = Some(self.frame()?.env);
+ while let Some(e) = cur {
+ match self.heap.env(e) {
+ Some(Env::Decl { bindings, outer }) => {
+ if bindings.contains(name) {
+ return Ok(Some(e));
+ }
+ cur = *outer;
+ }
+ Some(Env::Obj { outer, .. }) => cur = *outer,
+ None => return internal("environment out of range"),
+ }
+ }
+ Ok(None)
+ }
+
+ fn op_init_var(&mut self, n: u32) -> JsResult<()> {
+ let name = self.name(n)?;
+ let v = self.pop()?;
+ let Some(env) = self.find_binding(&name)? else { return internal("initializing a binding that was not declared") };
+ let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) else { return internal("not a declarative environment") };
+ let Some(b) = bindings.get_mut(&name) else { return internal("binding missing") };
+ b.value = v;
+ b.uninitialized = false;
+ Ok(())
+ }
+
+ fn op_load_param(&mut self, n: u32) -> JsResult<()> {
+ let name = self.name(n)?;
+ let Some(env) = self.find_binding(&name)? else { return internal("parameter missing") };
+ let v = self.binding_value(env, &name)?;
+ self.push(v)
+ }
+
+ /// Enters the body of a function with default or rest parameters: a variable environment
+ /// inside the parameters' one, whose variables start with the value of a parameter of the
+ /// same name (ECMA-262 2015 section 9.2.12, step 28), and the body's function declarations
+ /// and `let` and `const` names.
+ fn op_body_env(&mut self) -> JsResult<()> {
+ let frame = self.frame()?;
+ let (code, params) = (frame.code.clone(), frame.env);
+ // Each new environment is in the frame, where the collector finds it, before the next
+ // allocation.
+ let var_env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(params) });
+ self.frame_mut()?.var_env = var_env;
+ let lex = self.top_env(&code, var_env)?;
+ self.frame_mut()?.env = lex;
+ for (name, fi) in &code.fun_decls {
+ self.use_fuel()?;
+ let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
+ let f = self.make_closure(fcode, lex)?;
+ self.temp_roots.push(Value::Object(f));
+ let r = self.env_insert(var_env, name.clone(), Binding::new(Value::Object(f), true, false));
+ self.temp_roots.pop();
+ r?;
+ }
+ for v in &code.vars {
+ self.use_fuel()?;
+ if matches!(self.heap.env(var_env), Some(Env::Decl { bindings, .. }) if bindings.contains(v)) {
+ continue;
+ }
+ let initial = match self.heap.env(params) {
+ Some(Env::Decl { bindings, .. }) => bindings.get(v).map_or(Value::Undefined, |b| b.value.clone()),
+ _ => Value::Undefined,
+ };
+ self.env_insert(var_env, v.clone(), Binding::new(initial, true, false))?;
+ }
+ Ok(())
+ }
+
+ /// Assigns a function declared in a block to the variable of the same name.
+ fn op_annex_b(&mut self, n: u32) -> JsResult<()> {
+ let name = self.name(n)?;
+ let v = self.peek(0)?;
+ let var_env = self.frame()?.var_env;
+ match self.heap.env(var_env) {
+ Some(Env::Decl { .. }) => self.env_insert(var_env, name, Binding::new(v, true, false))?,
+ Some(&Env::Obj { object, .. }) => self.put(object, name, v, false)?,
+ None => return internal("environment out of range"),
+ }
+ self.pop().map(drop)
+ }
+
+ // ---- ECMAScript 2015 spread and templates ----
+
+ /// Appends the elements of the value on top to the array under it: an array's elements by
+ /// index (holes read as `undefined`), a string's characters by code point, and an object with
+ /// a `length` by index. Any other value is a `TypeError`. Each element takes a unit of fuel.
+ fn op_array_spread(&mut self) -> JsResult<()> {
+ let v = self.peek(0)?;
+ let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") };
+ let items: Vec = match &v {
+ Value::String(s) => {
+ let units = s.flat();
+ let mut out = Vec::new();
+ let mut held = HeldBytes::new(self);
+ let mut i = 0;
+ while let Some(&u) = units.get(i) {
+ self.use_fuel()?;
+ held.add(self, PROP_BYTES)?;
+ let pair = (0xD800..0xDC00).contains(&u) && units.get(i + 1).is_some_and(|n| (0xDC00..0xE000).contains(n));
+ let len = if pair { 2 } else { 1 };
+ out.push(Value::String(Str::from_units(units.get(i..i + len).unwrap_or_default().to_vec())));
+ i += len;
+ }
+ out
+ }
+ Value::Object(o) if self.has_property(*o, &key("length"))? => {
+ let o = *o;
+ let len = self.get_from(o, &key("length"), &v)?;
+ let n = to_uint32(self.to_number(&len)?);
+ let current = match &self.object(a)?.class {
+ Class::Array { length, .. } => *length,
+ _ => return internal("spread into something that is not an array"),
+ };
+ if u64::from(current) + u64::from(n) >= u64::from(u32::MAX) {
+ return Err(self.throw(ErrorType::Range, "array literal too long"));
+ }
+ // The elements read so far stay reachable while a getter runs.
+ // The list is counted against the heap limit as it grows.
+ let mark = self.temp_roots.len();
+ let mut held = HeldBytes::new(self);
+ let mut read = || -> JsResult<()> {
+ for i in 0..n {
+ self.use_fuel()?;
+ held.add(self, PROP_BYTES)?;
+ let item = self.get_from(o, &index_key(i), &v)?;
+ self.temp_roots.push(item);
+ }
+ Ok(())
+ };
+ let r = read();
+ drop(held);
+ let out = self.temp_roots.split_off(mark.min(self.temp_roots.len()));
+ r?;
+ out
+ }
+ _ => {
+ let what = self.describe(&v);
+ return Err(self.type_error(&format!("{what} cannot be spread")));
+ }
+ };
+ let o = self.object_mut(a)?;
+ let Class::Array { length, .. } = &mut o.class else { return internal("spread into something that is not an array") };
+ let start = *length;
+ let Some(end) = u32::try_from(items.len()).ok().and_then(|n| start.checked_add(n)).filter(|&e| e < u32::MAX) else {
+ return Err(self.throw(ErrorType::Range, "array literal too long"));
+ };
+ *length = end;
+ for (i, item) in (start..end).zip(items) {
+ self.define(a, index_key(i), Prop::Data { value: item, flags: OPEN })?;
+ }
+ self.pop().map(drop)
+ }
+
+ /// Takes the array of a call's or `new`'s arguments off the stack and pushes its elements.
+ fn unpack_args(&mut self) -> JsResult {
+ let Value::Object(a) = self.peek(0)? else { return internal("arguments are not an array") };
+ let length = match &self.object(a)?.class {
+ Class::Array { length, .. } => *length,
+ _ => return internal("arguments are not an array"),
+ };
+ if length as usize > MAX_APPLY_ARGS {
+ return Err(self.throw(ErrorType::Range, "too many arguments"));
+ }
+ let mut args = Vec::with_capacity(length as usize);
+ for i in 0..length {
+ args.push(
+ self.get_own_property(a, &index_key(i))?
+ .and_then(|p| if let Prop::Data { value, .. } = p { Some(value) } else { None })
+ .unwrap_or(Value::Undefined),
+ );
+ }
+ self.pop()?;
+ self.stack.extend(args);
+ Ok(length)
+ }
+
+ fn op_call_spread(&mut self, eval: bool) -> JsResult<()> {
+ let n = self.unpack_args()?;
+ self.op_call(n, eval)
+ }
+
+ fn op_new_spread(&mut self) -> JsResult<()> {
+ let n = self.unpack_args()?;
+ self.op_new(n)
+ }
+
+ /// The template object of `templates[i]` of the running code: a frozen array of the cooked
+ /// strings whose `raw` property is a frozen array of the raw strings, made once for each
+ /// site (ECMA-262 2015 section 12.2.9.3).
+ fn op_template_object(&mut self, i: u32) -> JsResult<()> {
+ let code = self.frame()?.code.clone();
+ let site = (Rc::as_ptr(&code) as usize, i);
+ if let Some(&(_, id)) = self.template_objects.get(&site) {
+ return self.push(Value::Object(id));
+ }
+ let Some(t) = code.templates.get(i as usize) else { return internal("template out of range") };
+ let strings = t.cooked.len().saturating_add(t.raw.len());
+ self.reserve_heap(OBJECT_BYTES.saturating_mul(2).saturating_add(strings.saturating_mul(PROP_BYTES)))?;
+ let raw = self.frozen_array(&t.raw)?;
+ // The raw array stays reachable while the template object is made.
+ self.push(Value::Object(raw))?;
+ let cooked = self.frozen_array(&t.cooked)?;
+ self.push(Value::Object(cooked))?;
+ self.define(cooked, key("raw"), Prop::Data { value: Value::Object(raw), flags: 0 })?;
+ if let Some(o) = self.heap.object_mut(cooked) {
+ o.extensible = false;
+ }
+ // The template object replaces the raw array under it on the stack.
+ self.pop()?;
+ self.pop()?;
+ self.template_objects.insert(site, (code, cooked));
+ self.push(Value::Object(cooked))
+ }
+
+ fn frozen_array(&mut self, strings: &[Str]) -> JsResult {
+ let proto = self.intrinsics.array_proto;
+ let length = u32::try_from(strings.len()).map_err(|_| self.throw(ErrorType::Range, "template too long"))?;
+ let a = self.heap.alloc_object(Object::new(Class::Array { length, length_writable: false }, Some(proto)));
+ // The array stays reachable while it is filled.
+ self.temp_roots.push(Value::Object(a));
+ let mut fill = || -> JsResult<()> {
+ for (i, s) in strings.iter().enumerate() {
+ self.use_fuel()?;
+ self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: Value::String(s.clone()), flags: ENUMERABLE })?;
+ }
+ Ok(())
+ };
+ let r = fill();
+ self.temp_roots.pop();
+ r?;
+ if let Some(o) = self.heap.object_mut(a) {
+ o.extensible = false;
+ }
+ Ok(a)
+ }
+
// ---- for-in ----
/// The names `for-in` visits (section 12.6.4): the enumerable properties of the object and
@@ -2353,6 +2691,7 @@ impl Interp {
f = Value::Object(target);
}
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, env }) => {
let Some(callee) = f.as_object() else { return internal("callee is not an object") };
let proto = match self.get_from(callee, &key("prototype"), &f)? {
@@ -2396,7 +2735,9 @@ impl Interp {
self.temp_roots.truncate(mark);
reserved?;
}
- let this = if code.strict {
+ let this = if code.arrow {
+ if code.uses_this { self.binding_value(env, ARROW_THIS)? } else { Value::Undefined }
+ } else if code.strict {
this
} else {
match this {
@@ -2405,14 +2746,14 @@ impl Interp {
prim => Value::Object(self.to_object(&prim)?),
}
};
- let fenv = self.instantiate_function(&code, env, &args, callee)?;
+ let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?;
let base = self.stack.len();
self.frames.push(Frame {
code,
pc: 0,
base,
env: fenv,
- var_env: fenv,
+ var_env,
env_depth: 0,
this,
callee: Some(callee),
@@ -2425,39 +2766,122 @@ impl Interp {
/// Declaration binding instantiation for function code (section 10.5). Each parameter and
/// declaration takes a unit of fuel.
- fn instantiate_function(&mut self, code: &Rc, outer: EnvId, args: &[Value], callee: ObjId) -> JsResult {
+ /// Gives the environment the body runs in and its variable environment. A function with
+ /// default or rest parameters gets its parameters uninitialized, and its code enters the
+ /// body's environments with [`Op::BodyEnv`] once they are initialized (ECMA-262 2015 section
+ /// 9.2.12).
+ fn instantiate_function(&mut self, code: &Rc, outer: EnvId, args: &[Value], callee: ObjId) -> JsResult<(EnvId, EnvId)> {
let mut bindings = PropMap::default();
for (i, p) in code.params.iter().enumerate() {
self.use_fuel()?;
- bindings.insert(p.clone(), Binding { value: args.get(i).cloned().unwrap_or(Value::Undefined), mutable: true, deletable: false });
+ let mut b = Binding::new(args.get(i).cloned().unwrap_or(Value::Undefined), true, false);
+ b.uninitialized = code.param_init;
+ b.lexical = code.param_init;
+ bindings.insert(p.clone(), b);
+ }
+ if let Some(rest) = &code.rest {
+ let extra = args.get(code.params.len()..).unwrap_or_default();
+ let a = self.array_of(extra)?;
+ let mut b = Binding::new(Value::Object(a), true, false);
+ b.uninitialized = code.param_init;
+ b.lexical = code.param_init;
+ bindings.insert(rest.clone(), b);
}
let name_bytes = bindings.iter().map(|(k, _)| string_bytes(k.len())).sum::();
let env = self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) });
self.heap.bytes += name_bytes;
+ let has = |interp: &Self, name: &[u16]| matches!(interp.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.contains(name));
+ let needs_arguments = code.uses_arguments && !code.arrow;
+ if code.param_init {
+ if needs_arguments && !has(self, &key("arguments")) {
+ let a = self.create_arguments(code, env, args, callee)?;
+ self.env_insert(env, key("arguments"), Binding::new(Value::Object(a), !code.strict, false))?;
+ }
+ return Ok((env, env));
+ }
+ // The environment stays reachable while the body's scope, which can collect, is made.
+ self.temp_envs.push(env);
+ let lex = self.top_env(code, env);
+ self.temp_envs.pop();
+ let lex = lex?;
for (name, fi) in &code.fun_decls {
self.use_fuel()?;
let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
- let f = self.make_closure(fcode, env)?;
- self.env_insert(env, name.clone(), Binding { value: Value::Object(f), mutable: true, deletable: false })?;
+ let f = self.make_closure(fcode, lex)?;
+ self.env_insert(env, name.clone(), Binding::new(Value::Object(f), true, false))?;
}
- let has = |interp: &Self, name: &[u16]| matches!(interp.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.contains(name));
- if code.uses_arguments && !has(self, &key("arguments")) {
+ if needs_arguments && !has(self, &key("arguments")) {
let a = self.create_arguments(code, env, args, callee)?;
- self.env_insert(env, key("arguments"), Binding { value: Value::Object(a), mutable: !code.strict, deletable: false })?;
+ self.env_insert(env, key("arguments"), Binding::new(Value::Object(a), !code.strict, false))?;
}
for v in &code.vars {
self.use_fuel()?;
if !has(self, v) {
- self.env_insert(env, v.clone(), Binding { value: Value::Undefined, mutable: true, deletable: false })?;
+ self.env_insert(env, v.clone(), Binding::new(Value::Undefined, true, false))?;
}
}
- Ok(env)
+ Ok((lex, env))
}
- /// The `arguments` object (section 10.6).
+ /// The environment of the `let` and `const` names at the top of `code`, inside `outer`, or
+ /// `outer` when it has none.
+ fn top_env(&mut self, code: &Code, outer: EnvId) -> JsResult {
+ match code.top_scope {
+ Some(i) => self.block_env(code, i, outer),
+ None => Ok(outer),
+ }
+ }
+
+ /// A new environment for `code.scopes[i]` inside `outer`: its `let` and `const` names not yet
+ /// initialized and its function declarations made. Each name takes a unit of fuel.
+ fn block_env(&mut self, code: &Code, i: u32, outer: EnvId) -> JsResult {
+ let Some(scope) = code.scopes.get(i as usize) else { return internal("scope out of range") };
+ let funcs = scope.funcs.iter().map(|(_, fi)| code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f))).sum::();
+ let names = scope.lets.iter().map(|(k, _)| k).chain(scope.funcs.iter().map(|(k, _)| k)).map(|k| binding_bytes(k.len())).sum::();
+ self.reserve_heap(ENV_BYTES.saturating_add(funcs).saturating_add(names))?;
+ let mut bindings = PropMap::default();
+ for (name, constant) in &scope.lets {
+ self.use_fuel()?;
+ bindings.insert(name.clone(), Binding::lexical(*constant));
+ }
+ let name_bytes = bindings.iter().map(|(k, _)| string_bytes(k.len())).sum::();
+ let env = self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) });
+ self.heap.bytes += name_bytes;
+ // The environment and each closure stay reachable while the next one is made.
+ self.temp_envs.push(env);
+ let mark = self.temp_roots.len();
+ let mut fill = || -> JsResult<()> {
+ for (name, fi) in &scope.funcs {
+ self.use_fuel()?;
+ let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
+ let f = self.make_closure(fcode, env)?;
+ self.temp_roots.push(Value::Object(f));
+ self.env_insert(env, name.clone(), Binding { lexical: true, ..Binding::new(Value::Object(f), true, false) })?;
+ }
+ Ok(())
+ };
+ let r = fill();
+ self.temp_roots.truncate(mark);
+ self.temp_envs.pop();
+ r.map(|()| env)
+ }
+
+ /// An array of `values`, in order.
+ pub(crate) fn array_of(&mut self, values: &[Value]) -> JsResult {
+ let proto = self.intrinsics.array_proto;
+ let length = u32::try_from(values.len()).map_err(|_| self.throw(ErrorType::Range, "array too long"))?;
+ let a = self.heap.alloc_object(Object::new(Class::Array { length, length_writable: true }, Some(proto)));
+ for (i, v) in values.iter().enumerate() {
+ self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: v.clone(), flags: OPEN })?;
+ }
+ Ok(a)
+ }
+
+ /// The `arguments` object (section 10.6). Its elements follow the parameters only outside
+ /// strict mode code in a function with plain parameters (ECMA-262 2015 section 9.2.12).
fn create_arguments(&mut self, code: &Code, env: EnvId, args: &[Value], callee: ObjId) -> JsResult {
let mut names = vec![None; args.len()];
- if !code.strict {
+ if !code.strict && !code.param_init {
let mut mapped = std::collections::HashSet::new();
for (i, p) in code.params.iter().enumerate().take(args.len()).rev() {
if mapped.insert(p.clone())
@@ -2473,7 +2897,7 @@ impl Interp {
self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: v.clone(), flags: OPEN })?;
}
self.define(a, key("length"), Prop::Data { value: Value::Number(args.len() as f64), flags: HIDDEN })?;
- if code.strict {
+ if code.strict || code.param_init {
let thrower = Some(self.intrinsics.throw_type_error);
for name in ["callee", "caller"] {
self.define(a, key(name), Prop::Accessor { get: thrower, set: thrower, flags: 0 })?;
@@ -2624,7 +3048,7 @@ impl Interp {
(caller_env, caller_var_env)
};
self.stack.truncate(start);
- self.instantiate_global(&code, var_env, true)?;
+ let env = self.instantiate_global(&code, env, var_env, true)?;
self.push_code_frame(code, env, var_env, this, false)
}
@@ -2647,17 +3071,63 @@ impl Interp {
/// Declares `code`'s variables and functions and pushes its boundary frame, ready to run.
pub(crate) fn enter_global(&mut self, code: Rc, is_eval: bool) -> JsResult<()> {
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
- let (env, global) = (self.global_env, self.global);
+ 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(env) });
+ let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
(e, e)
} else {
- (env, env)
+ (scope, self.global_env)
};
- self.instantiate_global(&code, var_env, is_eval)?;
+ let env = self.instantiate_global(&code, env, var_env, is_eval)?;
self.push_code_frame(code, env, var_env, Value::Object(global), true)
}
+ /// The environment global code runs in: with [`Options::es2015`], the one that holds the
+ /// scripts' `let` and `const` names, inside the global object's.
+ pub(crate) fn global_scope(&self) -> EnvId {
+ self.global_lex.unwrap_or(self.global_env)
+ }
+
+ /// Sets [`Options::es2015`], making the environment of the scripts' `let` and `const` names
+ /// the first time it is turned on.
+ pub(crate) fn set_es2015(&mut self, es2015: bool) {
+ self.options.es2015 = es2015;
+ if es2015 && self.global_lex.is_none() {
+ let outer = Some(self.global_env);
+ self.global_lex = Some(self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer }));
+ }
+ }
+
+ /// Declares a script's top-level `let` and `const` names in the global scope, uninitialized
+ /// (ECMA-262 2015 section 15.1.8): a name another script declared with `let` or `const`, a
+ /// non-configurable property of the global object (a `var` or a function another script
+ /// declared, or a built-in such as `undefined`) or a `var` or function of this script that
+ /// another script declared with `let` or `const` is a `SyntaxError`, and nothing is declared.
+ fn declare_global_lexical(&mut self, code: &Code, lex: EnvId) -> JsResult<()> {
+ let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets);
+ let in_lex = |interp: &Self, name: &[u16]| matches!(interp.heap.env(lex), Some(Env::Decl { bindings, .. }) if bindings.contains(name));
+ let global = self.global;
+ for (name, _) in lets {
+ self.use_fuel()?;
+ let restricted = self.get_own_property(global, name)?.is_some_and(|p| !p.configurable());
+ if in_lex(self, name) || restricted {
+ let ident = String::from_utf16_lossy(name);
+ return Err(self.throw(ErrorType::Syntax, &format!("redeclaration of '{ident}'")));
+ }
+ }
+ for name in code.vars.iter().chain(code.fun_decls.iter().map(|(k, _)| k)) {
+ if in_lex(self, name) {
+ let ident = String::from_utf16_lossy(name);
+ return Err(self.throw(ErrorType::Syntax, &format!("redeclaration of '{ident}'")));
+ }
+ }
+ for (name, constant) in lets {
+ let b = Binding::lexical(*constant);
+ self.env_insert(lex, name.clone(), b)?;
+ }
+ Ok(())
+ }
+
fn push_code_frame(&mut self, code: Rc, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> {
if self.frames.len() >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
@@ -2681,18 +3151,65 @@ impl Interp {
/// Declaration binding instantiation for global and eval code (section 10.5). The caller has
/// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel.
- fn instantiate_global(&mut self, code: &Rc, var_env: EnvId, is_eval: bool) -> JsResult<()> {
+ ///
+ /// 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 {
let configurable = if is_eval { CONFIGURABLE } else { 0 };
+ if is_eval && !code.strict && self.options.es2015 {
+ self.check_eval_vars(code, env, var_env)?;
+ }
+ let lex = match code.top_scope {
+ _ if !is_eval && Some(env) == self.global_lex => {
+ self.declare_global_lexical(code, env)?;
+ env
+ }
+ Some(i) => self.block_env(code, i, env)?,
+ None => env,
+ };
+ // Functions close over the code's own environment with ES2015's scoping, and over its
+ // variable environment otherwise (ECMA-262 5.1 section 13).
+ let scope = if self.options.es2015 { lex } else { var_env };
for (name, fi) in &code.fun_decls {
self.use_fuel()?;
let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
- let f = self.make_closure(fcode, var_env)?;
+ let f = self.make_closure(fcode, scope)?;
self.declare(var_env, name, Some(Value::Object(f)), configurable)?;
}
for v in &code.vars {
self.use_fuel()?;
self.declare(var_env, v, None, configurable)?;
}
+ Ok(lex)
+ }
+
+ /// A `var` or function that eval code outside strict mode code declares must not take the name
+ /// of a `let`, a `const` or a block's function from the code's environment `env` out to the
+ /// variable environment it declares them in (ECMA-262 2015 section 18.2.1.2, step 5), nor, in
+ /// a default parameter's value, the name of a parameter (ECMA-262 2017 section 18.2.1.3): that
+ /// is a `SyntaxError`, and nothing is declared. A `catch` parameter does not count (Annex
+ /// B.3.5). Each name and each environment passed takes a unit of fuel.
+ fn check_eval_vars(&mut self, code: &Code, env: EnvId, var_env: EnvId) -> JsResult<()> {
+ for name in code.vars.iter().chain(code.fun_decls.iter().map(|(k, _)| k)) {
+ self.use_fuel()?;
+ let mut cur = Some(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) {
+ let ident = String::from_utf16_lossy(name);
+ return Err(self.throw(ErrorType::Syntax, &format!("redeclaration of '{ident}'")));
+ }
+ *outer
+ }
+ Some(Env::Obj { outer, .. }) => *outer,
+ None => return internal("environment out of range"),
+ }
+ .filter(|_| e != var_env);
+ }
+ }
Ok(())
}
@@ -2702,10 +3219,8 @@ impl Interp {
Some(Env::Decl { bindings, .. }) => {
let exists = bindings.contains(name);
match value {
- Some(v) => self.env_insert(env, name.clone(), Binding { value: v, mutable: true, deletable: configurable != 0 }),
- None if !exists => {
- self.env_insert(env, name.clone(), Binding { value: Value::Undefined, mutable: true, deletable: configurable != 0 })
- }
+ Some(v) => self.env_insert(env, name.clone(), Binding::new(v, true, configurable != 0)),
+ None if !exists => self.env_insert(env, name.clone(), Binding::new(Value::Undefined, true, configurable != 0)),
None => Ok(()),
}
}
diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs
index bfe358bc20..d0bed32c1d 100644
--- a/crates/js/src/interp_tests.rs
+++ b/crates/js/src/interp_tests.rs
@@ -975,6 +975,14 @@ fn code(ops: Vec) -> Code {
uses_arguments: false,
source,
span: (0, 0),
+ scopes: Vec::new(),
+ top_scope: None,
+ templates: Vec::new(),
+ rest: None,
+ length: 0,
+ arrow: false,
+ uses_this: false,
+ param_init: false,
}
}
diff --git a/crates/js/src/lexer.rs b/crates/js/src/lexer.rs
index a2a7153dc1..4d5432c4a9 100644
--- a/crates/js/src/lexer.rs
+++ b/crates/js/src/lexer.rs
@@ -30,6 +30,8 @@ const BACKSLASH: u32 = b'\\' as u32;
const SLASH: u32 = b'/' as u32;
const STAR: u32 = b'*' as u32;
const DOT: u32 = b'.' as u32;
+const BACKTICK: u32 = b'`' as u32;
+const DOLLAR: u32 = b'$' as u32;
const CR: u32 = 0x0D;
const LF: u32 = 0x0A;
@@ -49,13 +51,15 @@ pub struct Lexer<'s> {
max_depth: usize,
/// Read the E4X punctuators `..`, `::` and `@`.
e4x: bool,
+ /// Read `=>`, `...` and template literals.
+ es2015: bool,
}
impl<'s> Lexer<'s> {
/// A lexer of `src`. `preprocessor_lines` turns on the reading of preprocessor lines;
/// `max_depth` limits how deeply a regular expression literal's groups may nest.
pub fn new(src: &'s [u16], preprocessor_lines: bool, max_depth: usize) -> Self {
- Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth, e4x: false }
+ Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth, e4x: false, es2015: false }
}
/// The same lexer, reading the E4X punctuators when `e4x` is true.
@@ -64,6 +68,12 @@ impl<'s> Lexer<'s> {
self
}
+ /// The same lexer, reading `=>`, `...` and template literals when `es2015` is true.
+ pub fn with_es2015(mut self, es2015: bool) -> Self {
+ self.es2015 = es2015;
+ self
+ }
+
/// Moves to source offset `pos`, at the given line and column (both from 1), after the parser
/// has read an XML literal up to there.
pub(crate) fn seek(&mut self, pos: usize, line: u32, column: u32) {
@@ -149,6 +159,9 @@ impl<'s> Lexer<'s> {
self.string(start, line, column)?
} else if c == SLASH && goal == Goal::RegExp {
self.regexp(start, line, column)?
+ } else if c == BACKTICK && self.es2015 {
+ self.pos += 1;
+ self.template(start, line, column)?
} else {
let punct = self.punct().ok_or_else(|| self.error_at(start, unexpected_character(c)))?;
self.token(TokenKind::Punct(punct), start, line, column, false)
@@ -172,6 +185,83 @@ impl<'s> Lexer<'s> {
Ok(regexp)
}
+ /// Reads the token `token`, a `}` that ends a template literal's substitution, again as the
+ /// template's next piece.
+ pub(crate) fn rescan_template(&mut self, token: &Token) -> Result {
+ let start = usize::try_from(token.span.start).unwrap_or(usize::MAX);
+ self.pos = start + 1;
+ self.line = token.line;
+ self.line_start = start.saturating_sub(usize::try_from(token.column.saturating_sub(1)).unwrap_or(0));
+ self.blank_line = false;
+ let mut piece = self.template(start, token.line, token.column)?;
+ piece.newline_before = token.newline_before;
+ Ok(piece)
+ }
+
+ /// Reads a template literal's characters after its backtick or `}` up to `${` or the closing
+ /// backtick (ECMA-262 2015 sections 11.8.6 and 11.8.6.1): the cooked text, with escapes read
+ /// as a string literal's are except that octal escapes are errors, and the raw text as written,
+ /// with each line terminator sequence (CR LF, CR or LF) read as LF in both, and a line
+ /// continuation left out of the cooked text.
+ fn template(&mut self, start: usize, line: u32, column: u32) -> Result {
+ let at = (start, line, column);
+ let mut cooked = Vec::new();
+ let mut raw = Vec::new();
+ let tail = loop {
+ match self.peek() {
+ None => return Err(Self::error_from(at, "unterminated template literal")),
+ Some(BACKTICK) => {
+ self.pos += 1;
+ break true;
+ }
+ Some(DOLLAR) if self.peek_at(1) == Some(u32::from(b'{')) => {
+ self.pos += 2;
+ break false;
+ }
+ Some(BACKSLASH) => {
+ let begin = self.pos;
+ let begin_line = self.line;
+ self.template_escape(&mut cooked)?;
+ // The raw text keeps the escape as written, its line terminator read as LF.
+ if self.line != begin_line {
+ let terminator = self.unit(begin + 1).unwrap_or(LF);
+ raw.push(BACKSLASH as u16);
+ raw.push(if terminator == CR { LF as u16 } else { terminator as u16 });
+ } else {
+ raw.extend_from_slice(self.src.get(begin..self.pos).unwrap_or_default());
+ }
+ }
+ Some(c) if is_line_terminator(c) => {
+ let unit = if c == CR { LF as u16 } else { c as u16 };
+ self.line_terminator();
+ cooked.push(unit);
+ raw.push(unit);
+ }
+ Some(c) => {
+ cooked.push(c as u16);
+ raw.push(c as u16);
+ self.pos += 1;
+ }
+ }
+ };
+ Ok(self.token(TokenKind::Template { cooked, raw, tail }, start, line, column, false))
+ }
+
+ /// Reads an escape in a template literal into `cooked`. A line continuation adds nothing; an
+ /// octal escape (`\1`, `\00`), `\8` and `\9` are errors, as are malformed `\x` and `\u` escapes.
+ fn template_escape(&mut self, cooked: &mut Vec) -> Result<(), SyntaxError> {
+ let at = self.pos;
+ match self.peek_at(1).and_then(char::from_u32) {
+ Some('0') if !self.peek_at(2).is_some_and(is_decimal_digit) => {
+ self.pos += 2;
+ cooked.push(0);
+ Ok(())
+ }
+ Some('0'..='9') => Err(self.error_at(at, "octal escape sequences are not allowed in template literals")),
+ _ => self.string_escape(cooked).map(drop),
+ }
+ }
+
fn token(&self, kind: TokenKind, start: usize, line: u32, column: u32, newline_before: bool) -> Token {
Token {
kind,
@@ -598,6 +688,9 @@ impl<'s> Lexer<'s> {
if !self.e4x && matches!(punct, Punct::DotDot | Punct::ColonColon | Punct::At) {
continue;
}
+ if !self.es2015 && matches!(punct, Punct::Arrow | Punct::Ellipsis) {
+ continue;
+ }
let bytes = spelling.as_bytes();
if rest.len() >= bytes.len() && rest.iter().zip(bytes).all(|(&u, &b)| u == u16::from(b)) {
self.pos += bytes.len();
diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs
index 1561d71dfe..5d48ec2d7a 100644
--- a/crates/js/src/lib.rs
+++ b/crates/js/src/lib.rs
@@ -46,6 +46,16 @@
//! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and
//! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each
//! node.
+//!
+//! With [`Options::es2015`], the parser and the realm also read and run a part of ECMAScript 2015
+//! ( ): block-scoped `let` and `const` declarations with
+//! their temporal dead zone (section 13.3.1), a new `let` binding for each iteration of a `for`
+//! loop, function declarations in blocks scoped to the block (Annex B.3.3 in sloppy code), arrow
+//! functions (section 14.2), template literals and tagged templates (sections 12.2.9 and
+//! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and
+//! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays, strings (by code point) and objects
+//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, classes,
+//! generators and modules stay syntax errors.
#![forbid(unsafe_code)]
pub mod ast;
@@ -75,8 +85,8 @@ mod xml_builtins;
mod xpath;
pub use ast::{
- AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LogicalOp, Name, Program, Property,
- PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
+ AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name, Program,
+ Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
};
pub use builtins::extensions::Localization;
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
@@ -100,11 +110,16 @@ pub struct Options {
pub max_source_units: usize,
/// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins.
pub e4x: bool,
+ /// Read and run the ECMAScript 2015 forms this engine has: `let` and `const`, arrow functions,
+ /// template literals (tagged ones included), default and rest parameters, and spread in array
+ /// literals, calls and `new`. Off, they are syntax errors and the language is ES5.1's. Code a
+ /// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
+ pub es2015: bool,
}
impl Default for Options {
fn default() -> Self {
- Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false }
+ Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false }
}
}
@@ -203,6 +218,8 @@ impl LineTable {
#[cfg(test)]
mod builtins_tests;
#[cfg(test)]
+mod es2015_tests;
+#[cfg(test)]
mod extension_tests;
#[cfg(test)]
mod host_tests;
diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs
index fa201c58ff..db034d1e2d 100644
--- a/crates/js/src/parser.rs
+++ b/crates/js/src/parser.rs
@@ -13,8 +13,8 @@ use std::collections::{HashMap, HashSet};
use crate::LineTable;
use crate::ast::{
- AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LogicalOp, Name, Program, Property,
- PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl,
+ AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LexKind, LogicalOp, Name, Program, Property,
+ PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl,
};
use crate::error::{SyntaxError, TOO_DEEP};
use crate::lexer::{Goal, Lexer};
@@ -34,8 +34,32 @@ struct Context {
loops: u32,
/// Iteration and `switch` statements open in the current function.
breakables: u32,
+ /// The current function body's directive prologue has a `"use strict"` directive.
+ use_strict: bool,
}
+/// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations
+/// (sections 13.2.1, 13.12.1, 13.15.1, 14.1.2 and 15.1.1). Kept only with
+/// [`crate::Options::es2015`].
+#[derive(Default)]
+struct Scope {
+ /// The `let`, `const` and (in a block) function declarations, each with whether it is a
+ /// function declaration.
+ lexical: HashMap,
+ /// The `var` names declared in this scope or in a block inside it.
+ vars: HashSet,
+ /// Names a lexical declaration here must not take: a function's parameters, or a catch
+ /// clause's parameter.
+ params: HashSet,
+ /// A function body or the script: `var` names go no further out, and function declarations
+ /// here are var-scoped.
+ function: bool,
+}
+
+/// The parameters of a function as they are read: plain names, each name's default value, and a
+/// rest parameter.
+type Params = (Vec, Vec>, Option);
+
/// A binary operator, with the logical ones apart.
#[derive(Clone, Copy, Debug)]
enum BinKind {
@@ -73,11 +97,15 @@ pub(crate) struct Parser<'s> {
in_list: bool,
/// Read E4X syntax.
e4x: bool,
+ /// Read the ECMAScript 2015 forms of [`crate::Options::es2015`].
+ es2015: bool,
+ /// The scopes open around the current token, outermost first (only with `es2015`).
+ scopes: Vec,
}
impl<'s> Parser<'s> {
pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result {
- let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x);
+ let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(options.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 {
@@ -95,6 +123,8 @@ 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() },
};
parser.tok = parser.next_significant()?;
Ok(parser)
@@ -108,7 +138,7 @@ impl<'s> Parser<'s> {
if let Some(tokens) = &mut self.tokens {
tokens.push(self.tok.clone());
}
- let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines };
+ let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines, es2015: self.es2015 };
Ok((program, self.tokens.unwrap_or_default()))
}
@@ -254,6 +284,122 @@ impl<'s> Parser<'s> {
Ok(Name { name, span: token.span })
}
+ // ---- scopes (ECMAScript 2015) ----
+
+ /// Opens a scope; `params` are the names a lexical declaration in it must not take.
+ fn push_scope(&mut self, function: bool, params: impl IntoIterator- ) {
+ if self.es2015 {
+ self.scopes.push(Scope { function, params: params.into_iter().collect(), ..Scope::default() });
+ }
+ }
+
+ fn pop_scope(&mut self) {
+ if self.es2015 {
+ self.scopes.pop();
+ }
+ }
+
+ fn redeclared(&self, name: &Name) -> SyntaxError {
+ self.error_at_offset(name.span.start, format!("redeclaration of '{}'", name.name))
+ }
+
+ /// Declares a `let`, a `const` or (`function`) a function declaration in a block, in the
+ /// innermost scope. A name may be declared there once, and not as a `var` or a parameter too;
+ /// outside strict mode code a function declaration may repeat another (Annex B.3.3.4).
+ fn declare_lexical(&mut self, name: &Name, function: bool) -> Result<()> {
+ let strict = self.ctx.strict;
+ let Some(scope) = self.scopes.last_mut() else { return Ok(()) };
+ let clash = match scope.lexical.get(&name.name) {
+ Some(&was_function) => !(function && was_function && !strict),
+ None => false,
+ } || scope.vars.contains(&name.name)
+ || scope.params.contains(&name.name);
+ if clash {
+ return Err(self.redeclared(name));
+ }
+ scope.lexical.insert(name.name.clone(), function);
+ Ok(())
+ }
+
+ /// Declares a `var` name: in each scope out to the function's, where no lexical declaration
+ /// may have it.
+ fn declare_var(&mut self, name: &Name) -> Result<()> {
+ let mut clash = false;
+ for scope in self.scopes.iter_mut().rev() {
+ if scope.lexical.contains_key(&name.name) {
+ clash = true;
+ break;
+ }
+ scope.vars.insert(name.name.clone());
+ if scope.function {
+ break;
+ }
+ }
+ if clash { Err(self.redeclared(name)) } else { Ok(()) }
+ }
+
+ /// 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) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) };
+ match self.scopes.last_mut() {
+ Some(scope) if scope.function => {
+ if scope.lexical.contains_key(&name.name) {
+ return Err(self.redeclared(&name));
+ }
+ scope.vars.insert(name.name);
+ Ok(())
+ }
+ Some(_) => self.declare_lexical(&name, true),
+ None => Ok(()),
+ }
+ }
+
+ /// The current token starts a `let` or `const` declaration in a statement list: `const`, or a
+ /// `let` written without escapes and followed by a name, `[` or `{` (ECMA-262 2015 section
+ /// 13.3.1; a `let` followed by anything else is an identifier outside strict mode code).
+ fn at_lexical_declaration(&self) -> Option
{
+ if !self.es2015 {
+ return None;
+ }
+ if self.at_keyword(Keyword::Const) {
+ return Some(LexKind::Const);
+ }
+ if self.tok.ident() == Some("let") && !self.tok.escaped {
+ let next = self.peek()?;
+ if matches!(next.kind, TokenKind::Ident(_)) || next.is_punct(Punct::LBracket) || next.is_punct(Punct::LBrace) {
+ return Some(LexKind::Let);
+ }
+ }
+ None
+ }
+
+ /// `let` or `const` declarations after the keyword: each name declared in the innermost scope.
+ /// `no_in` leaves `in` to a `for (… in …)` around them, where a `const` may go without an
+ /// initializer.
+ fn parse_lexical_decls(&mut self, kind: LexKind, no_in: bool) -> Result> {
+ let mut decls = Vec::new();
+ loop {
+ if self.at(Punct::LBracket) || self.at(Punct::LBrace) {
+ return Err(self.error_at_token(&self.tok, "destructuring declarations are not supported"));
+ }
+ let name = self.binding_identifier()?;
+ if name.name == "let" {
+ return Err(self.error_at_offset(name.span.start, "'let' cannot be the name of a let or const declaration"));
+ }
+ self.declare_lexical(&name, false)?;
+ let init = if self.eat(Punct::Eq)? { Some(self.parse_assignment(no_in)?) } else { None };
+ let in_head = no_in && self.at_keyword(Keyword::In) && decls.is_empty();
+ if kind == LexKind::Const && init.is_none() && !in_head {
+ return Err(self.error_at_offset(name.span.start, format!("const '{}' needs an initializer", name.name)));
+ }
+ decls.push(VarDecl { name, init });
+ if !self.eat(Punct::Comma)? {
+ return Ok(decls);
+ }
+ }
+ }
+
// ---- program and function bodies ----
/// Reads source elements up to `}` (in a function body) or the end of the source, reading the
@@ -275,6 +421,7 @@ impl<'s> Parser<'s> {
}
if self.is_use_strict(&first) {
self.ctx.strict = true;
+ self.ctx.use_strict = true;
if let Some(octal) = &octal {
return Err(self.error_at_token(octal, "octal escape sequences are not allowed in strict mode"));
}
@@ -314,7 +461,20 @@ impl<'s> Parser<'s> {
self.enter()?;
let result = self.parse_function_declaration();
self.leave();
- return result;
+ let id = result?;
+ if let Some(Stmt::FunctionDecl(fid)) = self.ast.stmt(id) {
+ self.declare_function(*fid)?;
+ }
+ return Ok(id);
+ }
+ if let Some(kind) = self.at_lexical_declaration() {
+ let start = self.bump()?.span;
+ self.enter()?;
+ let decls = self.parse_lexical_decls(kind, false);
+ self.leave();
+ let decls = decls?;
+ self.semicolon()?;
+ return Ok(self.ast.push_stmt(Stmt::Lexical(kind, decls), self.span_from(start)));
}
self.in_list = true;
self.parse_statement()
@@ -407,7 +567,22 @@ impl<'s> Parser<'s> {
/// `{ … }`: its statements.
fn parse_block(&mut self) -> Result> {
+ self.parse_block_with(None)
+ }
+
+ /// `{ … }`, a scope of its own; `param` is a catch clause's parameter, which a lexical
+ /// declaration in the block must not take.
+ fn parse_block_with(&mut self, param: Option<&str>) -> Result> {
self.expect(Punct::LBrace)?;
+ self.push_scope(false, param.map(str::to_string));
+ let body = self.block_items();
+ self.pop_scope();
+ let body = body?;
+ self.bump()?;
+ Ok(body)
+ }
+
+ fn block_items(&mut self) -> Result> {
let mut body = Vec::new();
while !self.at(Punct::RBrace) {
if self.tok.kind == TokenKind::Eof {
@@ -415,7 +590,6 @@ impl<'s> Parser<'s> {
}
body.push(self.parse_statement_item()?);
}
- self.bump()?;
Ok(body)
}
@@ -424,6 +598,7 @@ impl<'s> Parser<'s> {
let mut decls = Vec::new();
loop {
let name = self.binding_identifier()?;
+ self.declare_var(&name)?;
let init = if self.eat(Punct::Eq)? { Some(self.parse_assignment(no_in)?) } else { None };
decls.push(VarDecl { name, init });
if !self.eat(Punct::Comma)? {
@@ -502,6 +677,13 @@ impl<'s> Parser<'s> {
if each {
return self.parse_for_each(start);
}
+ if let Some(kind) = self.at_lexical_declaration() {
+ self.bump()?;
+ self.push_scope(false, std::iter::empty());
+ let result = self.parse_for_lexical(kind, start);
+ self.pop_scope();
+ return result;
+ }
let init = if self.at(Punct::Semicolon) {
None
} else if self.at_keyword(Keyword::Var) {
@@ -525,6 +707,11 @@ impl<'s> Parser<'s> {
}
Some(ForInit::Expr(expr))
};
+ self.parse_for_rest(init, start)
+ }
+
+ /// The rest of `for (init; test; update) body`, from the first `;`.
+ fn parse_for_rest(&mut self, init: Option, start: Span) -> Result {
self.expect(Punct::Semicolon)?;
let test = if self.at(Punct::Semicolon) { None } else { Some(self.parse_expression(false)?) };
self.expect(Punct::Semicolon)?;
@@ -534,6 +721,19 @@ impl<'s> Parser<'s> {
Ok(self.ast.push_stmt(Stmt::For { init, test, update, body }, self.span_from(start)))
}
+ /// `for (let …` or `for (const …`, after the keyword, in the loop's own scope.
+ fn parse_for_lexical(&mut self, kind: LexKind, start: Span) -> Result {
+ let mut decls = self.parse_lexical_decls(kind, true)?;
+ if decls.len() == 1 && self.at_keyword(Keyword::In) {
+ let Some(decl) = decls.pop() else { return Err(self.unexpected()) };
+ if decl.init.is_some() {
+ return Err(self.error_at_token(&self.tok, "a for-in variable declared with let or const cannot have an initializer"));
+ }
+ return self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, false);
+ }
+ self.parse_for_rest(Some(ForInit::Lexical(kind, decls)), start)
+ }
+
/// The rest of `for (target in object) body`, from `in`.
fn parse_for_in(&mut self, target: ForInTarget, start: Span, each: bool) -> Result {
self.expect_keyword(Keyword::In)?;
@@ -553,11 +753,31 @@ impl<'s> Parser<'s> {
};
return self.parse_for_in(ForInTarget::Var(decl), start, true);
}
+ if let Some(kind) = self.at_lexical_declaration() {
+ self.bump()?;
+ self.push_scope(false, std::iter::empty());
+ let result = self.parse_for_each_lexical(kind, start);
+ self.pop_scope();
+ return result;
+ }
let expr = self.parse_expression(true)?;
self.check_target(expr, "invalid left-hand side in for each loop")?;
self.parse_for_in(ForInTarget::Expr(expr), start, true)
}
+ /// `for each (let x in object) body` or `for each (const x in object) body`, after `let` or
+ /// `const`.
+ fn parse_for_each_lexical(&mut self, kind: LexKind, start: Span) -> Result {
+ let mut decls = self.parse_lexical_decls(kind, true)?;
+ let (Some(decl), true) = (decls.pop(), decls.is_empty()) else {
+ return Err(self.error_at_token(&self.tok, "for each takes one variable"));
+ };
+ if decl.init.is_some() {
+ return Err(self.error_at_token(&self.tok, "a for-in variable declared with let or const cannot have an initializer"));
+ }
+ self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, true)
+ }
+
/// `break` or `continue`, with an optional label on the same line, which must name a label
/// around it in the same function (an iteration statement's, for `continue`).
fn parse_jump(&mut self, is_break: bool, start: Span) -> Result {
@@ -621,7 +841,9 @@ impl<'s> Parser<'s> {
self.expect(Punct::RParen)?;
self.expect(Punct::LBrace)?;
self.ctx.breakables += 1;
+ self.push_scope(false, std::iter::empty());
let cases = self.parse_cases();
+ self.pop_scope();
self.ctx.breakables -= 1;
let cases = cases?;
Ok(self.ast.push_stmt(Stmt::Switch { discriminant, cases }, self.span_from(start)))
@@ -678,9 +900,13 @@ impl<'s> Parser<'s> {
let handler = if self.at_keyword(Keyword::Catch) {
self.bump()?;
self.expect(Punct::LParen)?;
+ if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
+ return Err(self.error_at_token(&self.tok, "destructuring catch parameters are not supported"));
+ }
let param = self.binding_identifier()?;
self.expect(Punct::RParen)?;
- Some(CatchClause { param, body: self.parse_block()? })
+ let body = self.parse_block_with(Some(¶m.name))?;
+ Some(CatchClause { param, body })
} else {
None
};
@@ -761,11 +987,23 @@ impl<'s> Parser<'s> {
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result {
self.expect(Punct::LParen)?;
- let mut params: Vec<(Name, Token)> = Vec::new();
+ let mut params: Vec = Vec::new();
+ let mut defaults: Vec> = Vec::new();
+ let mut rest = None;
if !self.at(Punct::RParen) {
loop {
- let (param, token) = self.function_name_or_param()?;
- params.push((param, token));
+ if self.es2015 && self.at(Punct::Ellipsis) {
+ self.bump()?;
+ rest = Some(self.function_name_or_param()?.0);
+ if !self.at(Punct::RParen) {
+ return Err(self.error_at_token(&self.tok, "a rest parameter must be the last parameter"));
+ }
+ break;
+ }
+ let (param, _) = self.function_name_or_param()?;
+ let default = if self.es2015 && self.eat(Punct::Eq)? { Some(self.parse_assignment(false)?) } else { None };
+ params.push(param);
+ defaults.push(default);
if !self.eat(Punct::Comma)? {
break;
}
@@ -773,29 +1011,97 @@ impl<'s> Parser<'s> {
}
let close = self.expect(Punct::RParen)?;
match kind {
- FunctionKind::Getter if !params.is_empty() => return Err(self.error_at_token(&close, "a getter must not have parameters")),
- FunctionKind::Setter if params.len() != 1 => return Err(self.error_at_token(&close, "a setter must have exactly one parameter")),
+ FunctionKind::Getter if !params.is_empty() || rest.is_some() => {
+ return Err(self.error_at_token(&close, "a getter must not have parameters"));
+ }
+ FunctionKind::Setter if params.len() != 1 || rest.is_some() => {
+ return Err(self.error_at_token(&close, "a setter must have exactly one parameter"));
+ }
_ => {}
}
+ if defaults.iter().all(Option::is_none) {
+ defaults.clear();
+ }
self.expect(Punct::LBrace)?;
- let inner = Context { strict: self.ctx.strict, in_function: true, ..Context::default() };
+ let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
+ let outer_strict = self.ctx.strict;
+ let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
+ self.push_scope(true, names);
let body = self.parse_body(true);
- let strict = self.ctx.strict;
+ self.pop_scope();
+ let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict);
self.ctx = outer;
let body = body?;
self.expect(Punct::RBrace)?;
- if strict {
- self.check_strict_function(name.as_ref(), ¶ms)?;
+ let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) };
+ 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 {
+ if self.tok.newline_before {
+ return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'"));
}
- Ok(self.ast.push_function(Function {
- kind,
- name: name.map(|(n, _)| n),
- params: params.into_iter().map(|(n, _)| n).collect(),
- body,
- strict,
- span: self.span_from(start),
- }))
+ self.expect(Punct::Arrow)?;
+ self.enter()?;
+ let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
+ let outer_strict = self.ctx.strict;
+ let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
+ let outer = std::mem::replace(&mut self.ctx, inner);
+ self.push_scope(true, names);
+ let block = self.at(Punct::LBrace);
+ let body = if block {
+ self.bump().and_then(|_| self.parse_body(true))
+ } else {
+ self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))])
+ };
+ self.pop_scope();
+ let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict);
+ self.ctx = outer;
+ self.leave();
+ let body = body?;
+ if block {
+ self.expect(Punct::RBrace)?;
+ }
+ let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults };
+ let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) };
+ self.check_params(&function, use_strict)?;
+ let id = self.ast.push_function(function);
+ Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start)))
+ }
+
+ /// The parameters an arrow function's parenthesized head `expr` gives (ECMA-262 2015 section
+ /// 14.2.1): names, names with `= default`, and a last `...name`, each written bare.
+ fn arrow_params(&self, expr: ExprId) -> Result {
+ let invalid = |at: ExprId| self.error_at_offset(self.ast.expr_span(at).start, "invalid arrow function parameters");
+ let Some(Expr::Paren(inner)) = self.ast.expr(expr) else { return Err(invalid(expr)) };
+ let items = match self.ast.expr(*inner) {
+ Some(Expr::Sequence(list)) => list.clone(),
+ _ => vec![*inner],
+ };
+ let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None);
+ let name_of = |id: ExprId| match self.ast.expr(id) {
+ Some(Expr::Ident(n)) => Some(Name { name: n.clone(), span: self.ast.expr_span(id) }),
+ _ => None,
+ };
+ let count = items.len();
+ for (i, item) in items.into_iter().enumerate() {
+ match self.ast.expr(item) {
+ Some(Expr::Ident(_)) => {
+ params.push(name_of(item).ok_or_else(|| invalid(item))?);
+ defaults.push(None);
+ }
+ Some(Expr::Assign { op: None, target, value }) => {
+ params.push(name_of(*target).ok_or_else(|| invalid(item))?);
+ defaults.push(Some(*value));
+ }
+ Some(Expr::Spread(arg)) if i + 1 == count => rest = Some(name_of(*arg).ok_or_else(|| invalid(item))?),
+ _ => return Err(invalid(item)),
+ }
+ }
+ Ok((params, defaults, rest))
}
/// A parameter's name.
@@ -809,21 +1115,39 @@ impl<'s> Parser<'s> {
Ok((Name { name, span: token.span }, token))
}
- /// The rules strict mode code sets for a function's name and parameters (Annex C): neither
- /// `eval`, `arguments` nor a strict-mode reserved word, and no parameter name twice.
- fn check_strict_function(&self, name: Option<&(Name, Token)>, params: &[(Name, Token)]) -> Result<()> {
- for (n, token) in name.into_iter().chain(params) {
- if is_eval_or_arguments(&n.name) {
- return Err(self.error_at_token(token, format!("'{}' cannot be declared in strict mode", n.name)));
- }
- if strict_reserved(&n.name) {
- return Err(self.error_at_token(token, format!("'{}' is a reserved word in strict mode", n.name)));
+ /// The rules for a function's name and parameters. Strict mode code (Annex C): neither `eval`,
+ /// `arguments` nor a strict-mode reserved word, and no parameter name twice. An arrow function
+ /// or a function with a default or rest parameter has no parameter name twice either (ECMA-262
+ /// 2015 sections 14.1.2 and 14.2.1), and its body cannot start with `"use strict"`
+ /// (`body_strict`; ECMA-262 2016 section 14.1.2).
+ fn check_params(&self, function: &Function, body_strict: bool) -> Result<()> {
+ let params = || function.params.iter().chain(&function.rest);
+ let simple = function.simple_params() && function.kind != FunctionKind::Arrow;
+ if body_strict && !function.simple_params() {
+ let at = function.body.first().map_or(function.span.start, |&s| self.ast.stmt_span(s).start);
+ return Err(self.error_at_offset(at, "\"use strict\" is not allowed in a function with default or rest parameters"));
+ }
+ if function.strict {
+ for n in function.name.iter().chain(params()) {
+ if is_eval_or_arguments(&n.name) {
+ return Err(self.error_at_offset(n.span.start, format!("'{}' cannot be declared in strict mode", n.name)));
+ }
+ if strict_reserved(&n.name) {
+ return Err(self.error_at_offset(n.span.start, format!("'{}' is a reserved word in strict mode", n.name)));
+ }
}
}
- let mut seen = HashSet::new();
- for (p, token) in params {
- if !seen.insert(p.name.as_str()) {
- return Err(self.error_at_token(token, format!("duplicate parameter name '{}' is not allowed in strict mode", p.name)));
+ if function.strict || !simple {
+ let mut seen = HashSet::new();
+ for p in params() {
+ if !seen.insert(p.name.as_str()) {
+ let message = if function.strict {
+ format!("duplicate parameter name '{}' is not allowed in strict mode", p.name)
+ } else {
+ format!("duplicate parameter name '{}'", p.name)
+ };
+ return Err(self.error_at_offset(p.span.start, message));
+ }
}
}
Ok(())
@@ -857,7 +1181,10 @@ impl<'s> Parser<'s> {
fn assignment(&mut self, no_in: bool) -> Result {
let mut targets: Vec<(ExprId, AssignOp)> = Vec::new();
loop {
- let expr = self.parse_conditional(no_in)?;
+ let mut expr = self.parse_conditional(no_in)?;
+ if self.es2015 && self.at(Punct::Arrow) {
+ expr = self.arrow_from(expr, no_in)?;
+ }
let Some(op) = assign_op(&self.tok) else {
let mut value = expr;
while let Some((target, op)) = targets.pop() {
@@ -872,6 +1199,18 @@ impl<'s> Parser<'s> {
}
}
+ /// The arrow function whose head is `expr`, read before the current `=>`: a name standing
+ /// alone, or parameters in parentheses.
+ fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result {
+ let start = self.ast.expr_span(expr);
+ let params = match self.ast.expr(expr) {
+ Some(Expr::Ident(name)) => (vec![Name { name: name.clone(), span: start }], vec![None], None),
+ Some(Expr::Paren(_)) => self.arrow_params(expr)?,
+ _ => return Err(self.unexpected()),
+ };
+ self.parse_arrow(start, params, no_in)
+ }
+
/// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code
/// neither `eval` nor `arguments`), a property, an E4X name standing alone (`@a`, `ns::a`;
/// ECMA-357 section 11.1), or outside strict mode code a call (assigning to its result fails
@@ -1006,6 +1345,11 @@ impl<'s> Parser<'s> {
let span = self.ast.expr_span(expr).to(close.span);
expr = self.ast.push_expr(Expr::Index { object: expr, index }, span);
}
+ TokenKind::Template { .. } => {
+ let (quasis, exprs) = self.parse_template()?;
+ let span = Span::new(self.ast.expr_span(expr).start, self.prev_end);
+ expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span);
+ }
TokenKind::Punct(Punct::LParen) => {
let args = self.parse_arguments()?;
let span = Span::new(self.ast.expr_span(expr).start, self.prev_end);
@@ -1024,12 +1368,23 @@ impl<'s> Parser<'s> {
Ok(expr)
}
+ /// An element of an array literal or an argument list: an assignment expression, or with
+ /// [`crate::Options::es2015`] a spread (`...expression`).
+ fn parse_element(&mut self) -> Result {
+ if self.es2015 && self.at(Punct::Ellipsis) {
+ let start = self.bump()?.span;
+ let arg = self.parse_assignment(false)?;
+ return Ok(self.ast.push_expr(Expr::Spread(arg), self.span_from(start)));
+ }
+ self.parse_assignment(false)
+ }
+
fn parse_arguments(&mut self) -> Result> {
self.expect(Punct::LParen)?;
let mut args = Vec::new();
if !self.at(Punct::RParen) {
loop {
- args.push(self.parse_assignment(false)?);
+ args.push(self.parse_element()?);
if !self.eat(Punct::Comma)? {
break;
}
@@ -1081,12 +1436,17 @@ impl<'s> Parser<'s> {
}
TokenKind::Punct(Punct::LBracket) => return self.parse_array(),
TokenKind::Punct(Punct::LBrace) => return self.parse_object(),
+ TokenKind::Punct(Punct::LParen) if self.es2015 => return self.parse_paren_or_arrow_head(),
TokenKind::Punct(Punct::LParen) => {
self.bump()?;
let inner = self.parse_expression(false)?;
self.expect(Punct::RParen)?;
return Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start)));
}
+ TokenKind::Template { .. } => {
+ let (quasis, exprs) = self.parse_template()?;
+ return Ok(self.ast.push_expr(Expr::Template { quasis, exprs }, self.span_from(start)));
+ }
TokenKind::Punct(Punct::Lt) if self.e4x => return self.parse_xml_literal(),
TokenKind::Punct(Punct::At | Punct::Star) if self.e4x => return self.parse_xml_scope_name(),
_ => return Err(self.unexpected()),
@@ -1099,6 +1459,68 @@ impl<'s> Parser<'s> {
Ok(id)
}
+ /// `( … )` 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 `=>`.
+ fn parse_paren_or_arrow_head(&mut self) -> Result {
+ let start = self.expect(Punct::LParen)?.span;
+ let mut items = Vec::new();
+ let mut head_only = self.at(Punct::RParen);
+ while !self.at(Punct::RParen) {
+ if self.at(Punct::Ellipsis) {
+ let spread_start = self.bump()?.span;
+ let name = self.binding_identifier()?;
+ let arg = self.ast.push_expr(Expr::Ident(name.name), name.span);
+ items.push(self.ast.push_expr(Expr::Spread(arg), self.span_from(spread_start)));
+ head_only = true;
+ break;
+ }
+ items.push(self.parse_assignment(false)?);
+ if !self.eat(Punct::Comma)? {
+ break;
+ }
+ if self.at(Punct::RParen) {
+ return Err(self.unexpected());
+ }
+ }
+ self.expect(Punct::RParen)?;
+ if head_only && !self.at(Punct::Arrow) {
+ return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok))));
+ }
+ let inner = match items.as_slice() {
+ [one] => *one,
+ _ => {
+ let span = self.span_from(start);
+ self.ast.push_expr(Expr::Sequence(items), span)
+ }
+ };
+ Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start)))
+ }
+
+ /// A template literal from its first piece (the current token): its pieces and substitutions.
+ fn parse_template(&mut self) -> Result<(Vec, Vec)> {
+ let mut quasis = Vec::new();
+ let mut exprs = Vec::new();
+ loop {
+ let TokenKind::Template { cooked, raw, tail } = &self.tok.kind else { return Err(self.unexpected()) };
+ let tail = *tail;
+ quasis.push(TemplatePiece { cooked: cooked.clone(), raw: raw.clone() });
+ if tail {
+ self.bump()?;
+ return Ok((quasis, exprs));
+ }
+ self.bump()?;
+ self.enter()?;
+ let expr = self.parse_expression(false);
+ self.leave();
+ exprs.push(expr?);
+ if !self.at(Punct::RBrace) {
+ return Err(self.error_at_token(&self.tok, format!("expected '}}' but found {}", describe(&self.tok))));
+ }
+ let piece = self.lex.rescan_template(&self.tok)?;
+ self.tok = piece;
+ }
+ }
+
fn parse_function_expression(&mut self) -> Result {
let start = self.expect_keyword(Keyword::Function)?.span;
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None };
@@ -1118,7 +1540,7 @@ impl<'s> Parser<'s> {
elements.push(None);
continue;
}
- elements.push(Some(self.parse_assignment(false)?));
+ elements.push(Some(self.parse_element()?));
if !self.at(Punct::RBracket) {
self.expect(Punct::Comma)?;
}
@@ -1276,5 +1698,6 @@ fn describe(token: &Token) -> String {
TokenKind::RegExp { .. } => "regular expression".into(),
TokenKind::Directive(_) => "preprocessor line".into(),
TokenKind::XmlLiteral => "XML literal".into(),
+ TokenKind::Template { .. } => "template literal".into(),
}
}
diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs
index d675e82ec7..e6c6ba484f 100644
--- a/crates/js/src/realm.rs
+++ b/crates/js/src/realm.rs
@@ -215,6 +215,12 @@ impl Realm {
self.interp.reset_gc_threshold();
}
+ /// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and
+ /// `const` names earlier runs declared stay visible when it is turned off.
+ pub fn set_es2015(&mut self, es2015: bool) {
+ self.interp.set_es2015(es2015);
+ }
+
/// 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())
diff --git a/crates/js/src/token.rs b/crates/js/src/token.rs
index 304ea0e0ab..608d4c1240 100644
--- a/crates/js/src/token.rs
+++ b/crates/js/src/token.rs
@@ -210,12 +210,17 @@ pub enum Punct {
ColonColon,
/// `@`, read only with [`crate::Options::e4x`].
At,
+ /// `=>`, read only with [`crate::Options::es2015`].
+ Arrow,
+ /// `...`, read only with [`crate::Options::es2015`].
+ Ellipsis,
}
impl Punct {
/// Punctuators by spelling, longest first, so the first that matches is the longest.
pub(crate) const ALL: &'static [(&'static str, Punct)] = &[
(">>>=", Punct::UShrEq),
+ ("...", Punct::Ellipsis),
("===", Punct::EqEqEq),
("!==", Punct::NotEqEq),
(">>>", Punct::UShr),
@@ -223,6 +228,7 @@ impl Punct {
(">>=", Punct::ShrEq),
("<=", Punct::LtEq),
(">=", Punct::GtEq),
+ ("=>", Punct::Arrow),
("==", Punct::EqEq),
("!=", Punct::NotEq),
("++", Punct::PlusPlus),
@@ -354,6 +360,15 @@ pub enum TokenKind {
Directive(Directive),
/// An XML or XMLList literal; the tokens of its embedded expressions follow it.
XmlLiteral,
+ /// A piece of a template literal (read only with [`crate::Options::es2015`]): from its
+ /// backtick, or from the `}` that ends a substitution, to the next `${` or the closing
+ /// backtick (`tail`). `cooked` is the text with its escapes read and `raw` the text as written,
+ /// both with each line terminator sequence read as a line feed.
+ Template {
+ cooked: Vec,
+ raw: Vec,
+ tail: bool,
+ },
}
/// A token, with where it is and the facts the grammar's rules need about it.
diff --git a/crates/js/src/xml.rs b/crates/js/src/xml.rs
index f49c94eb46..bb311cf1a8 100644
--- a/crates/js/src/xml.rs
+++ b/crates/js/src/xml.rs
@@ -573,7 +573,7 @@ impl Interp {
let env = self.frame()?.var_env;
if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) {
let value = Value::String(Str::from_rc(uri));
- bindings.insert(Rc::from(DEFAULT_NS_BINDING), Binding { value, mutable: true, deletable: false });
+ bindings.insert(Rc::from(DEFAULT_NS_BINDING), Binding::new(value, true, false));
} else {
self.xml_default_uri = uri;
}
diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs
index bf32bcfcd6..c1b86051cb 100644
--- a/crates/js/tests/test262.rs
+++ b/crates/js/tests/test262.rs
@@ -27,6 +27,10 @@
//! an ES5 section apart from the other tests without a feature tag; its failures go to
//! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness
//! or test file cannot be read, or when no ES5 test runs.
+//!
+//! 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`.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
@@ -254,9 +258,14 @@ fn missing_builtins<'a>(provided: &[&str]) -> HashSet<&'a str> {
/// in `this["Map"]`), and as a word in any string literal when one of the sources can run a string
/// as code. Comments, and strings that only mention the name in a message, do not count.
fn needs_missing_builtin(sources: &[&str], missing: &HashSet<&str>) -> bool {
+ needs_missing_builtin_in(sources, missing, &Options::default())
+}
+
+/// [`needs_missing_builtin`] for sources read with `options`.
+fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: &Options) -> bool {
let mut lists = Vec::with_capacity(sources.len());
for source in sources {
- let Ok(tokens) = tokenize(source, &Options::default()) else { return true };
+ let Ok(tokens) = tokenize(source, options) else { return true };
lists.push(tokens);
}
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
@@ -288,9 +297,9 @@ fn runs_strings_as_code(tokens: &[Token]) -> bool {
})
}
-/// Runs one test in a new realm; `Err` describes a failure.
-fn run_one(script: &str, negative_type: Option<&str>) -> Result<(), String> {
- let mut realm = Realm::with_options(Options::default(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
+/// Runs one test in a new realm made with `options`; `Err` describes a failure.
+fn run_one(script: &str, negative_type: Option<&str>, options: &Options) -> Result<(), String> {
+ let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
match (realm.run(script), negative_type) {
(Ok(_), None) => Ok(()),
(Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")),
@@ -476,7 +485,7 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> (
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"));
- let outcome = std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref()));
+ let outcome = std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), &Options::default()));
match outcome {
Ok(Ok(())) => counts.passed += 1,
Ok(Err(why)) => {
@@ -494,6 +503,156 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> (
(es5_counts, later_counts)
}
+/// The folders under `test/language/` that hold tests of the ECMAScript 2015 forms
+/// [`Options::es2015`] reads.
+const ES2015_FOLDERS: &[&str] = &[
+ "block-scope",
+ "statements/let",
+ "statements/const",
+ "expressions/arrow-function",
+ "expressions/template-literal",
+ "expressions/tagged-template",
+ "rest-parameters",
+];
+
+/// The feature tags of the forms [`Options::es2015`] reads.
+const ES2015_FEATURES: &[&str] = &["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters"];
+
+#[test]
+fn es2015_subset_runs() {
+ let Some(dir) = suite_dir() else {
+ println!("test262 ES2015 subset: SKIPPED (no suite; run cargo xtask test262)");
+ return;
+ };
+ let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015(&dir)).unwrap();
+ handle.join().unwrap();
+}
+
+/// The counts of the ES2015 subset read with one setting of [`Options::es2015`].
+#[derive(Default)]
+struct Es2015Counts {
+ parse_passed: usize,
+ parse_failed: usize,
+ run_passed: usize,
+ run_failed: usize,
+ panicked: usize,
+ failures: String,
+}
+
+/// 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`.
+fn run_es2015(dir: &Path) {
+ let language = dir.join("test").join("language");
+ assert!(language.is_dir(), "{} is not a test262 checkout", dir.display());
+ let harness_dir = dir.join("harness");
+ let read = |p: &Path| {
+ let bytes = std::fs::read(p).map_err(|e| format!("cannot read {}: {e}", p.display()));
+ assert!(bytes.is_ok(), "{}", bytes.as_ref().err().map_or("", String::as_str));
+ String::from_utf8_lossy(&bytes.unwrap_or_default()).into_owned()
+ };
+ let prelude = format!("{}\n{}\n", read(&harness_dir.join("assert.js")), read(&harness_dir.join("sta.js")));
+ let missing = missing_builtins(&[TEXT_BUILTINS]);
+ let modern = Options { es2015: true, ..Options::default() };
+ let editions = [Options::default(), modern.clone()];
+ let mut counts = [Es2015Counts::default(), Es2015Counts::default()];
+ let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize);
+ for path in test_files(&language) {
+ let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
+ let in_folder = ES2015_FOLDERS.iter().any(|f| rel.starts_with(&format!("test/language/{f}/")));
+ let source = read(&path);
+ let meta = meta(&source);
+ let tags_in_set = meta.features.iter().all(|f| ES2015_FEATURES.contains(&f.as_str()));
+ if !(in_folder || !meta.features.is_empty()) {
+ continue;
+ }
+ if !tags_in_set {
+ if in_folder {
+ other_features += 1;
+ }
+ continue;
+ }
+ let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
+ if has("module") || has("async") || meta.negative_phase.as_deref() == Some("resolution") {
+ skipped += 1;
+ continue;
+ }
+ let expect_error = meta.negative_phase.as_deref() == Some("parse");
+ let includes: String = meta.includes.iter().map(|i| read(&harness_dir.join(i)) + "\n").collect();
+ if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &modern) {
+ skipped += 1;
+ continue;
+ }
+ selected += 1;
+ let modes: &[bool] = if has("raw") || has("noStrict") {
+ &[false]
+ } else if has("onlyStrict") {
+ &[true]
+ } else {
+ &[false, true]
+ };
+ for (options, counts) in editions.iter().zip(counts.iter_mut()) {
+ for &strict in modes {
+ let mode = if strict { "strict" } else { "sloppy" };
+ let outcome = if expect_error {
+ let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() };
+ let result = parse(&text, options);
+ if result.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_one(&script, negative_type.as_deref(), 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 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) {
+ 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 ES2015 subset: {selected} tests. Without Options::es2015: {}. With it: {}. Skipped {skipped} module, asynchronous \
+ or missing-built-in tests and {other_features} tests in the folders 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();
diff --git a/docs/mcp.md b/docs/mcp.md
index 5032690fc6..967c464c57 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -2609,7 +2609,15 @@ https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-act
describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is
not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and
-`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the
+`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in
+`.js` (in any case) also reads these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and
+`const` with block scope and their temporal dead zone, a new `let` binding for each `for` loop iteration, function
+declarations scoped to their block, arrow functions, template literals and tagged templates, default and rest
+parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects
+with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own
+until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and
+an engine that `#targetengine` keeps reads each run the way that run's script does. A
+`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the
app through the global object `vc`, and writes to the Script Console and runs other files through `$`:
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index f8a3dc84a0..3f196a4bcc 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -1075,6 +1075,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`.
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
+ - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions of later editions. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
- 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 ]` 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`.