JavaScript: for-of loops and destructuring in ES2015 realms

With Options::es2015, vectorcraft-js reads and runs for-of loops and
array and object destructuring (ECMA-262 11th edition, sections 13.7.5,
12.15.5 and 13.3.3) in var, let and const declarations, assignments,
function and arrow parameters and catch clauses, with defaults, holes
and rest elements. Object literals take shorthand and computed names.

for-of, spread and array patterns use the iterator protocol and call
the iterator's return method when a loop or pattern stops early.
Destructuring undefined or null throws a TypeError. Object rest
properties (ECMAScript 2018) stay syntax errors. A realm switched to
ES2015 without Symbol.iterator walks arrays, arguments objects and
strings by index.

Each step takes fuel, a rest element or spread reserves the whole size
of each new element against the heap limit, and nested patterns count
against Options::max_depth. The test262 runner reads the for-of and
dstr folders: 609 of 617 runs pass (529 before).
This commit is contained in:
dotCooCoo committed 2026-11-22 06:03:10 -08:00
1 parent 3a4c15f5d7
commit 1bf1001a90
17 files changed
+1885 -267

No files matched your search

+10
View File
@@ -328,6 +328,16 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
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}");
// `for`-`of` and destructuring, in a new engine and in one a `.jsx` script made.
let loops = "var s = 0;\nfor (const [a, { b = 1 }] of [[1, {}], [2, { b: 3 }]]) s += a + b;\nvar { p, q: [r] } = { p: 4, q: [5] };\nvc.log(s);\nvc.log(p + r);\nvc.log(typeof Symbol);";
let r = s.execute("script.run", &path(&write("loops.js", loops))).unwrap();
assert_eq!(r["log"], json!([7, 9, "function"]), "{r}");
let kept = s
.execute("script.run", &path(&write("fifth.js", "#targetengine kept\nfor (const [i, ...j] of [[kept, 'x', 'y']]) vc.log(i + j.join(''));")))
.unwrap();
assert_eq!(kept["log"], json!(["1xy"]), "{kept}");
let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string();
assert!(e.contains("SyntaxError"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
+61 -10
View File
@@ -80,15 +80,19 @@ pub enum PropertyKey {
Ident(String),
String(Vec<u16>),
Number(f64),
/// `[expression]` with [`crate::Options::es2015`]: the key is the expression's value.
Computed(ExprId),
}
impl PropertyKey {
/// The key as the string a property is stored under (a number through ToString).
/// The key as the string a property is stored under (a number through ToString); empty for
/// a computed key, whose string is known only at run time.
pub fn to_utf16(&self) -> Vec<u16> {
match self {
PropertyKey::Ident(name) => name.encode_utf16().collect(),
PropertyKey::String(s) => s.clone(),
PropertyKey::Number(n) => crate::number::to_string(*n).encode_utf16().collect(),
PropertyKey::Computed(_) => Vec::new(),
}
}
}
@@ -269,20 +273,33 @@ pub enum XmlNamePart {
Computed(ExprId),
}
/// What a declaration, a parameter or a catch clause binds: a name, or with
/// [`crate::Options::es2015`] a destructuring pattern (ECMA-262 11th edition, section 13.3.3).
///
/// A pattern is an [`Expr::Array`] or an [`Expr::Object`] whose targets are [`Expr::Ident`]
/// names or nested patterns; an [`Expr::Assign`] with no operator gives a target its default
/// value, and an [`Expr::Spread`] as the last element of an array pattern is its rest element.
#[derive(Clone, Debug, PartialEq)]
pub enum Binding {
Name(Name),
Pattern(ExprId),
}
#[derive(Clone, Debug, PartialEq)]
pub struct VarDecl {
pub name: Name,
pub target: Binding,
pub init: Option<ExprId>,
}
/// What a `for (… in …)` statement assigns each property name to.
/// What a `for (… in …)` or `for (… of …)` statement assigns each property name or value to.
#[derive(Clone, Debug, PartialEq)]
pub enum ForInTarget {
/// `for (var x in o)`, with the declaration's initializer if it has one.
Var(VarDecl),
/// An assignment target, or with [`crate::Options::es2015`] an assignment pattern.
Expr(ExprId),
/// `for (let x in o)` or `for (const x in o)`: a new binding for each name.
Lexical(LexKind, Name),
Lexical(LexKind, Binding),
}
#[derive(Clone, Debug, PartialEq)]
@@ -304,7 +321,7 @@ pub struct SwitchCase {
#[derive(Clone, Debug, PartialEq)]
pub struct CatchClause {
pub param: Name,
pub param: Binding,
pub body: Vec<StmtId>,
}
@@ -343,6 +360,12 @@ pub enum Stmt {
body: StmtId,
each: bool,
},
/// `for (… of …)` with [`crate::Options::es2015`] (ECMA-262 11th edition, section 13.7.5).
ForOf {
target: ForInTarget,
iterable: ExprId,
body: StmtId,
},
/// `default xml namespace = expression;`.
DefaultXmlNamespace(ExprId),
Continue(Option<Name>),
@@ -384,11 +407,11 @@ pub struct Function {
pub kind: FunctionKind,
pub name: Option<Name>,
/// The parameters before a rest parameter.
pub params: Vec<Name>,
pub params: Vec<Binding>,
/// Each parameter's default value, in the order of `params` (empty when none has one).
pub defaults: Vec<Option<ExprId>>,
/// The rest parameter (`...name`).
pub rest: Option<Name>,
/// The rest parameter (`...name` or `...[pattern]`).
pub rest: Option<Binding>,
pub body: Vec<StmtId>,
/// The function's code is strict mode code: its own directive prologue holds `"use strict"`,
/// or the code around it is strict.
@@ -397,9 +420,9 @@ pub struct Function {
}
impl Function {
/// The parameters are plain names: no default value and no rest parameter.
/// The parameters are plain names: no pattern, no default value and no rest parameter.
pub fn simple_params(&self) -> bool {
self.rest.is_none() && self.defaults.iter().all(Option::is_none)
self.rest.is_none() && self.defaults.iter().all(Option::is_none) && self.params.iter().all(|p| matches!(p, Binding::Name(_)))
}
}
@@ -432,6 +455,34 @@ impl Ast {
self.functions.get(id.0 as usize)
}
/// The names a binding binds, in source order.
pub fn bound_names(&self, binding: &Binding) -> Vec<Name> {
match binding {
Binding::Name(n) => vec![n.clone()],
Binding::Pattern(p) => self.pattern_names(*p),
}
}
/// The names a destructuring pattern binds, in source order, walked without recursion.
pub fn pattern_names(&self, pattern: ExprId) -> Vec<Name> {
let mut out = Vec::new();
let mut work = vec![pattern];
while let Some(id) = work.pop() {
match self.expr(id) {
Some(Expr::Ident(n)) => out.push(Name { name: n.clone(), span: self.expr_span(id) }),
Some(Expr::Array(elements)) => work.extend(elements.iter().rev().flatten().copied()),
Some(Expr::Object(props)) => work.extend(props.iter().rev().filter_map(|p| match p.value {
PropertyValue::Init(e) => Some(e),
_ => None,
})),
Some(Expr::Assign { target, .. }) => work.push(*target),
Some(Expr::Spread(arg)) => work.push(*arg),
_ => {}
}
}
out
}
/// The expression with any parentheses around it removed.
pub fn unparenthesized(&self, mut id: ExprId) -> ExprId {
while let Some(Expr::Paren(inner)) = self.expr(id) {
+33 -3
View File
@@ -205,6 +205,26 @@ pub(crate) enum Op {
ToStr,
/// Pushes the template object of `templates[i]`, the same object for each evaluation.
TemplateObject(u32),
/// `value` → its Iterator Record (GetIterator, ECMA-262 11th edition section 7.4.1).
GetIterator,
/// `record` → `record value`, or jumps with `record` when the iterator is done.
IterStep(u32),
/// `record x₁…xₙ` → `record x₁…xₙ value`: the next value, `undefined` once it is done.
IterValue(u32),
/// `record x₁…xₙ` → `record x₁…xₙ array`: the values left, in an array.
IterRest(u32),
/// `record` → nothing: closes the iterator unless it is done (IteratorClose).
IterClose,
/// `record exception` → throws the exception after closing the iterator unless it is done.
IterCloseThrow,
/// `value` → `value`: a `TypeError` when it is `undefined` or `null`.
RequireObjectCoercible,
/// `object key x₁…xₙ` → `object key x₁…xₙ object[key]`: an object pattern's property.
PatternGet(u32),
/// `object key value` → `object`: a property with a computed name.
InitIndex,
/// `object key function` → `object`: a getter (`true`) or a setter with a computed name.
InitAccessorIndex(bool),
}
/// The names a block declares, entered with [`Op::PushBlock`].
@@ -296,9 +316,13 @@ pub(crate) struct Code {
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`].
/// The function has default, rest or destructured parameters: its parameters start
/// uninitialized, its code initializes them and then enters its body with [`Op::BodyEnv`].
pub(crate) param_init: bool,
/// The names the destructured parameters bind, which start uninitialized beside the
/// parameters. A destructured parameter's own entry in `params` is a name no script can
/// write.
pub(crate) pattern_names: Vec<Key>,
}
impl Code {
@@ -380,7 +404,13 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1),
Op::ArraySpread | Op::NewSpread => e(2, 1),
Op::CallSpread(_) => e(3, 1),
Op::ToStr => e(1, 1),
Op::ToStr | Op::GetIterator | Op::RequireObjectCoercible => e(1, 1),
Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] },
Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?),
Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?),
Op::IterClose => e(1, 0),
Op::IterCloseThrow => end(2),
Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1),
})
}
+157 -65
View File
@@ -13,17 +13,20 @@
//! chains and labels are compiled with loops; every other kind of nesting is counted, and code
//! nested deeper than [`MAX_DEPTH`] gives a `SyntaxError` instead of exhausting the stack.
mod pattern;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use crate::ast::{
AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId,
TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
AssignOp, Ast, BinaryOp, Binding, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyKey, PropertyValue,
Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
};
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;
use pattern::Mode;
/// How deeply the compiler may recurse: past the parser's default nesting limit, and shallow
/// enough for a 1 MiB stack.
@@ -61,6 +64,9 @@ enum Ctx {
Jump { labels: Vec<String>, is_loop: bool, plain_break: bool, brk: Label, cont: Option<Label>, depth: u32, env_depth: u32 },
/// The protected part (and catch clause) of a `try` with a `finally` block.
Finally { try_depth: u32, env_depth: u32, entry: Label, exits: Vec<Exit> },
/// The body of a `for-of` loop, whose Iterator Record is the top value at `depth`: a jump
/// out of the loop closes the iterator.
Iterator { depth: u32, env_depth: u32 },
}
struct FnCompiler<'a> {
@@ -265,7 +271,7 @@ impl<'a> FnCompiler<'a> {
scopes.len() - 1
};
match stmt {
Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))),
Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))),
Stmt::Lexical(..) => {}
Stmt::FunctionDecl(fid) => {
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
@@ -295,21 +301,23 @@ impl<'a> FnCompiler<'a> {
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)));
decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name)));
scope
}
Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect()),
Some(ForInit::Lexical(_, decls)) => {
enter(decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).map(|n| key_of(&n.name)).collect())
}
_ => scope,
};
work.push((*body, nested || inner, s));
}
Stmt::ForIn { target, body, .. } => {
Stmt::ForIn { target, body, .. } | Stmt::ForOf { target, body, .. } => {
let s = match target {
ForInTarget::Var(d) => {
add_var(&mut out, key_of(&d.name.name));
self.ast.bound_names(&d.target).iter().for_each(|n| add_var(&mut out, key_of(&n.name)));
scope
}
ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)])),
ForInTarget::Lexical(_, binding) => enter(self.ast.bound_names(binding).iter().map(|n| key_of(&n.name)).collect()),
ForInTarget::Expr(_) => scope,
};
work.push((*body, nested || inner, s));
@@ -362,7 +370,7 @@ impl<'a> FnCompiler<'a> {
fn lexical_names(&self, list: &[StmtId]) -> HashSet<Key> {
list.iter()
.filter_map(|&s| match self.ast.stmt(s) {
Some(Stmt::Lexical(_, decls)) => Some(decls.iter().map(|d| key_of(&d.name.name))),
Some(Stmt::Lexical(_, decls)) => Some(decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).map(|n| key_of(&n.name))),
_ => None,
})
.flatten()
@@ -378,7 +386,9 @@ impl<'a> FnCompiler<'a> {
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::Lexical(kind, decls)) => {
scope.lets.extend(decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).map(|n| (key_of(&n.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");
@@ -417,13 +427,12 @@ impl<'a> FnCompiler<'a> {
/// `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),
match (d.init, &d.target) {
(Some(init), _) => self.expr(init)?,
(None, Binding::Name(_)) => self.emit(Op::Undefined),
(None, Binding::Pattern(_)) => return internal("a destructuring declaration without an initializer"),
}
self.at(d.name.span.start);
let n = self.var_name(&d.name.name);
self.emit(Op::InitVar(n));
self.bind_to(&d.target, Mode::Lexical)?;
}
Ok(())
}
@@ -473,7 +482,7 @@ impl<'a> FnCompiler<'a> {
}
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::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. } | Stmt::ForOf { .. } => self.loop_stmt(id, Vec::new()),
Stmt::Continue(label) => self.jump_stmt(label.as_ref().map(|l| l.name.as_str()), true),
Stmt::Break(label) => self.jump_stmt(label.as_ref().map(|l| l.name.as_str()), false),
Stmt::Return(value) => {
@@ -536,10 +545,7 @@ impl<'a> FnCompiler<'a> {
for d in decls {
if let Some(init) = d.init {
self.expr(init)?;
self.at(d.name.span.start);
let n = self.var_name(&d.name.name);
self.emit(Op::SetVar(n));
self.emit(Op::Pop);
self.bind_to(&d.target, Mode::Var)?;
}
}
Ok(())
@@ -581,7 +587,9 @@ impl<'a> FnCompiler<'a> {
cur = *body;
}
match self.ast.stmt(cur) {
Some(Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. }) => self.loop_stmt(cur, labels),
Some(Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. } | Stmt::ForOf { .. }) => {
self.loop_stmt(cur, labels)
}
Some(Stmt::Switch { .. }) => self.switch_stmt(cur, labels),
_ => {
let brk = self.new_label();
@@ -653,6 +661,7 @@ impl<'a> FnCompiler<'a> {
self.jump(Op::Jump, head);
}
Some(Stmt::ForIn { target, object, body, each }) => return self.for_in(target, *object, *body, labels, *each),
Some(Stmt::ForOf { target, iterable, body }) => return self.for_of(target, *iterable, *body, labels),
_ => return internal("not a loop"),
}
self.bind(brk);
@@ -674,7 +683,8 @@ impl<'a> FnCompiler<'a> {
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 lets = decls.iter().flat_map(|d| self.bound_keys(&d.target)).map(|k| (k, kind == LexKind::Const)).collect();
let scope = BlockScope { lets, funcs: Vec::new() };
let scope = self.push_scope(scope);
self.emit(Op::PushBlock(scope));
self.env_depth += 1;
@@ -707,16 +717,9 @@ impl<'a> FnCompiler<'a> {
/// `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<String>,
each: bool,
) -> CResult<()> {
let scope = self.push_scope(BlockScope { lets: vec![(key_of(&name.name), kind == LexKind::Const)], funcs: Vec::new() });
fn for_in_lexical(&mut self, kind: LexKind, binding: &Binding, object: ExprId, body: StmtId, labels: Vec<String>, each: bool) -> CResult<()> {
let lets = self.bound_keys(binding).into_iter().map(|k| (k, kind == LexKind::Const)).collect();
let scope = self.push_scope(BlockScope { lets, funcs: Vec::new() });
self.emit(Op::PushBlock(scope));
self.env_depth += 1;
self.expr(object)?;
@@ -731,15 +734,13 @@ impl<'a> FnCompiler<'a> {
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.bind_to(binding, Mode::Lexical)?;
self.emit(Op::Pop);
} else {
self.emit(Op::InitVar(n));
self.bind_to(binding, Mode::Lexical)?;
}
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);
@@ -755,8 +756,8 @@ impl<'a> FnCompiler<'a> {
}
fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec<String>, each: bool) -> CResult<()> {
if let ForInTarget::Lexical(kind, name) = target {
return self.for_in_lexical(*kind, name, object, body, labels, each);
if let ForInTarget::Lexical(kind, binding) = target {
return self.for_in_lexical(*kind, binding, object, body, labels, each);
}
if let ForInTarget::Var(d) = target {
self.var_decls(std::slice::from_ref(d))?;
@@ -770,11 +771,19 @@ impl<'a> FnCompiler<'a> {
self.jump(Op::ForInNext, brk);
match target {
ForInTarget::Var(d) => {
let n = self.var_name(&d.name.name);
if each {
self.emit(Op::ForEachValue(0));
}
self.emit(Op::SetVar(n));
// The target takes a copy; the name or value stays for the pops below.
self.emit(Op::Dup);
self.bind_to(&d.target, Mode::Var)?;
}
ForInTarget::Expr(e) if self.is_pattern(*e) => {
if each {
self.emit(Op::ForEachValue(0));
}
self.emit(Op::Dup);
self.destructure(*e, Mode::Assign)?;
}
ForInTarget::Expr(e) if each => self.store_value_to(*e)?,
ForInTarget::Expr(e) => self.store_key_to(*e)?,
@@ -928,7 +937,7 @@ impl<'a> FnCompiler<'a> {
};
hit.then_some(i)
}
Ctx::Finally { .. } => None,
Ctx::Finally { .. } | Ctx::Iterator { .. } => None,
});
match target {
Some(i) => self.emit_exit(if is_continue { Exit::Continue(i) } else { Exit::Break(i) }),
@@ -967,6 +976,21 @@ impl<'a> FnCompiler<'a> {
self.route_through_finally(i, exit, try_depth, env_depth, entry)?;
break;
}
Some(&Ctx::Iterator { depth, env_depth }) => {
// The loop is left: its iterator is closed, a `return` keeping its value.
if exit == Exit::Return {
let Some(under) = self.depth.checked_sub(1 + depth) else { return internal("stack below a for-of loop") };
if under > 0 {
self.emit(Op::PopUnder(under));
}
self.pop_envs(env_depth)?;
self.emit(Op::Swap);
} else {
self.unwind_to(depth, env_depth)?;
}
self.emit(Op::IterClose);
self.env_depth = env_depth;
}
None => return internal("context out of range"),
}
}
@@ -1037,13 +1061,34 @@ impl<'a> FnCompiler<'a> {
self.handlers.push((start, end, catch, try_depth, env_depth));
self.bind(catch);
self.depth = try_depth + 1;
self.at(h.param.span.start);
let n = self.var_name(&h.param.name);
self.emit(Op::PushCatch(n));
self.env_depth += 1;
self.block(&h.body)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
match &h.param {
Binding::Name(name) => {
self.at(name.span.start);
let n = self.var_name(&name.name);
self.emit(Op::PushCatch(n));
self.env_depth += 1;
self.block(&h.body)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
}
Binding::Pattern(p) => {
// The exception is bound to a name no script can write, then destructured
// into the pattern's names (ECMA-262 11th edition section 13.15.7).
self.at(self.ast.expr_span(*p).start);
let n = self.name_key(key_of("\u{0}catch"));
self.emit(Op::PushCatch(n));
self.emit(Op::GetVar(n));
let lets = self.bound_keys(&h.param).into_iter().map(|k| (k, false)).collect();
let scope = self.push_scope(BlockScope { lets, funcs: Vec::new() });
self.emit(Op::PushBlock(scope));
self.env_depth += 2;
self.destructure(*p, Mode::Lexical)?;
self.block(&h.body)?;
self.emit(Op::PopEnv);
self.emit(Op::PopEnv);
self.env_depth -= 2;
}
}
self.bind(after);
}
let Some(fin) = finalizer else { return Ok(()) };
@@ -1339,6 +1384,10 @@ impl<'a> FnCompiler<'a> {
fn object_literal(&mut self, props: &[crate::ast::Property]) -> CResult<()> {
self.emit(Op::NewObject);
for p in props {
if let PropertyKey::Computed(k) = p.key {
self.computed_property(k, &p.value)?;
continue;
}
let n = self.name_key(p.key.to_utf16().into());
match &p.value {
PropertyValue::Init(e) => {
@@ -1360,6 +1409,25 @@ impl<'a> FnCompiler<'a> {
Ok(())
}
/// `object` → `object`, with a property whose name is the value of `key` (ECMA-262 11th
/// edition section 12.2.6.8).
fn computed_property(&mut self, key: ExprId, value: &PropertyValue) -> CResult<()> {
self.expr(key)?;
self.emit(Op::ToKey);
match value {
PropertyValue::Init(e) => {
self.expr(*e)?;
self.emit(Op::InitIndex);
}
PropertyValue::Get(f) | PropertyValue::Set(f) => {
let i = self.function(*f)?;
self.emit(Op::Closure(i));
self.emit(Op::InitAccessorIndex(matches!(value, PropertyValue::Get(_))));
}
}
Ok(())
}
/// A run of member accesses and calls (`a.b[c](d).e`), compiled from the innermost object out
/// with a loop.
fn chain(&mut self, id: ExprId) -> CResult<()> {
@@ -1612,6 +1680,9 @@ impl<'a> FnCompiler<'a> {
/// Pushes what an assignment to `target` needs before its value: the object and key, and the
/// current value for a compound assignment.
fn assign_target(&mut self, op: AssignOp, target: ExprId) -> CResult<()> {
if op.is_none() && self.es2015 && self.is_pattern(target) {
return Ok(());
}
match self.ast.expr(target) {
Some(Expr::Ident(name)) => {
let n = self.var_name(name);
@@ -1658,6 +1729,11 @@ impl<'a> FnCompiler<'a> {
}
fn store(&mut self, target: ExprId) -> CResult<()> {
if self.es2015 && self.is_pattern(target) {
// The assignment's value is the value assigned (ECMA-262 11th edition section 12.15.4).
self.emit(Op::Dup);
return self.destructure(target, Mode::Assign);
}
match self.ast.expr(target) {
Some(Expr::Ident(name)) => {
let n = self.var_name(name);
@@ -1718,6 +1794,7 @@ impl<'a> FnCompiler<'a> {
| Op::JumpIfFalseKeep(t)
| Op::JumpIfTrueKeep(t)
| Op::ForInNext(t)
| Op::IterStep(t)
| Op::XmlFilterNext(t),
) => *t = target,
_ => return internal("patching an instruction that is not a jump"),
@@ -1762,6 +1839,7 @@ impl<'a> FnCompiler<'a> {
arrow: meta.arrow,
uses_this: self.uses_this,
param_init: meta.param_init,
pattern_names: meta.pattern_names,
};
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
Ok(Rc::new(code))
@@ -1780,6 +1858,7 @@ struct Meta {
length: u32,
arrow: bool,
param_init: bool,
pattern_names: Vec<Key>,
}
fn len_u32(n: usize) -> u32 {
@@ -1794,37 +1873,49 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
c.es2015 = es2015;
c.at(f.span.start);
c.enter()?;
let params: Vec<Key> = 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<Key> = params.iter().chain(&rest).cloned().collect();
// A destructured parameter has a binding of its own under a name no script can write, which
// holds its argument until the pattern takes it.
let param_key = |c: &FnCompiler, i: usize, p: &Binding| match p {
Binding::Name(n) => key_of(&n.name),
Binding::Pattern(_) => c.hidden_param(i),
};
let params: Vec<Key> = f.params.iter().enumerate().map(|(i, p)| param_key(&c, i, p)).collect();
let rest = f.rest.as_ref().map(|r| param_key(&c, f.params.len(), r));
let pattern_names: Vec<Key> = f.params.iter().chain(&f.rest).filter(|p| matches!(p, Binding::Pattern(_))).flat_map(|p| c.bound_keys(p)).collect();
let all_params: Vec<Key> = f.params.iter().chain(&f.rest).flat_map(|p| c.bound_keys(p)).collect();
let hoisted = c.hoist(&f.body, &all_params)?;
let 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);
let all = f.params.iter().enumerate().map(|(i, p)| (p, f.defaults.get(i).copied().flatten())).chain(f.rest.iter().map(|r| (r, None)));
for (i, (p, default)) in all.enumerate() {
let k = params.get(i).or(rest.as_ref()).cloned().unwrap_or_default();
let n = c.name_key(k);
c.at(match p {
Binding::Name(name) => name.span.start,
Binding::Pattern(e) => ast.expr_span(*e).start,
});
c.emit(Op::LoadParam(n));
if let Some(Some(default)) = f.defaults.get(i) {
if let Some(default) = default {
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.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));
match p {
Binding::Name(name) => {
c.at(name.span.start);
let n = c.var_name(&name.name);
c.emit(Op::InitVar(n));
}
Binding::Pattern(e) => c.destructure(*e, Mode::Lexical)?,
}
}
c.emit(Op::BodyEnv);
}
@@ -1844,6 +1935,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
length: len_u32(length),
arrow: f.kind == FunctionKind::Arrow,
param_init,
pattern_names,
};
c.finish(hoisted, meta)
}
+288
View File
@@ -0,0 +1,288 @@
//! Destructuring and `for (… of …)` (ECMA-262 11th edition,
//! <https://262.ecma-international.org/11.0/>, sections 12.15.5, 13.3.3 and 13.7.5).
//!
//! A pattern takes the value on top of the stack. An array pattern steps the value's iterator
//! once for each element and closes it when the pattern ends with the iterator not done, and when
//! anything in the pattern throws (an exception handler around the elements). An object pattern
//! reads each property by name. A target that is not a pattern is written as an assignment
//! (`[a.b] = …`), a `var` or a `let`, `const`, parameter or catch binding, as [`Mode`] says.
use super::{CResult, Ctx, FnCompiler, internal, key_of, len_u32};
use crate::ast::{Binding, Expr, ExprId, ForInTarget, LexKind, Property, PropertyKey, PropertyValue, StmtId};
use crate::bytecode::{BlockScope, CodeKind, Op};
use crate::heap::Key;
/// How a pattern's targets are written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Mode {
/// An assignment: each target is evaluated as an assignment's target is.
Assign,
/// `var`: the variable is assigned.
Var,
/// `let`, `const`, a parameter or a catch clause: the binding is initialized.
Lexical,
}
impl FnCompiler<'_> {
/// Whether `id`, without parentheses, is an array or object pattern.
pub(super) fn is_pattern(&self, id: ExprId) -> bool {
matches!(self.ast.expr(self.ast.unparenthesized(id)), Some(Expr::Array(_) | Expr::Object(_)))
}
/// The names a binding binds, as keys.
pub(super) fn bound_keys(&self, binding: &Binding) -> Vec<Key> {
self.ast.bound_names(binding).iter().map(|n| key_of(&n.name)).collect()
}
/// `value` → nothing: writes the value to the targets of the pattern `pattern`.
pub(super) fn destructure(&mut self, pattern: ExprId, mode: Mode) -> CResult<()> {
self.enter()?;
let pattern = self.ast.unparenthesized(pattern);
self.at(self.ast.expr_span(pattern).start);
let r = match self.ast.expr(pattern) {
Some(Expr::Array(elements)) => self.array_pattern(elements, mode),
Some(Expr::Object(properties)) => self.object_pattern(properties, mode),
_ => internal("not a destructuring pattern"),
};
self.leave();
r
}
/// `value` → nothing: writes the value to a name binding or a pattern.
pub(super) fn bind_to(&mut self, binding: &Binding, mode: Mode) -> CResult<()> {
match binding {
Binding::Pattern(p) => self.destructure(*p, mode),
Binding::Name(name) => {
self.at(name.span.start);
let n = self.var_name(&name.name);
if mode == Mode::Lexical {
self.emit(Op::InitVar(n));
} else {
self.emit(Op::SetVar(n));
self.emit(Op::Pop);
}
Ok(())
}
}
}
/// An element's target and its default value.
fn split_default(&self, element: ExprId) -> (ExprId, Option<ExprId>) {
match self.ast.expr(element) {
Some(Expr::Assign { op: None, target, value }) => (*target, Some(*value)),
_ => (element, None),
}
}
/// Pushes what writing to `target` needs before its value, and gives how many values that is:
/// an assignment's object and key; nothing for a binding or a pattern.
fn target_refs(&mut self, target: ExprId, mode: Mode) -> CResult<u32> {
if mode != Mode::Assign || self.is_pattern(target) {
return Ok(0);
}
let before = self.depth;
self.assign_target(None, self.ast.unparenthesized(target))?;
Ok(self.depth.saturating_sub(before))
}
/// `refs… value` → nothing: writes the value to `target`.
fn write_target(&mut self, target: ExprId, mode: Mode) -> CResult<()> {
let target = self.ast.unparenthesized(target);
if self.is_pattern(target) {
return self.destructure(target, mode);
}
self.at(self.ast.expr_span(target).start);
match (mode, self.ast.expr(target)) {
(Mode::Assign, _) => {
self.store(target)?;
self.emit(Op::Pop);
}
(_, Some(Expr::Ident(name))) => {
let n = self.var_name(name);
if mode == Mode::Lexical {
self.emit(Op::InitVar(n));
} else {
self.emit(Op::SetVar(n));
self.emit(Op::Pop);
}
}
_ => return internal("a binding pattern's target is not a name"),
}
Ok(())
}
/// `value` → `value`, or the default value when the value is `undefined`.
fn default_value(&mut self, default: Option<ExprId>) -> CResult<()> {
let Some(default) = default else { return Ok(()) };
let skip = self.new_label();
self.emit(Op::Dup);
self.emit(Op::Undefined);
self.emit(Op::Binary(crate::ast::BinaryOp::StrictEq));
self.jump(Op::JumpIfFalse, skip);
self.emit(Op::Pop);
self.expr(default)?;
self.bind(skip);
Ok(())
}
/// `value` → nothing, for `[a, , b = 1, ...c]` (sections 12.15.5.5 and 13.3.3.6).
fn array_pattern(&mut self, elements: &[Option<ExprId>], mode: Mode) -> CResult<()> {
self.emit(Op::GetIterator);
let record = self.depth;
let start = self.pc();
for element in elements {
let Some(element) = *element else {
self.emit(Op::IterValue(0));
self.emit(Op::Pop);
continue;
};
if let Some(Expr::Spread(target)) = self.ast.expr(element) {
let under = self.target_refs(*target, mode)?;
self.emit(Op::IterRest(under));
self.write_target(*target, mode)?;
continue;
}
let (target, default) = self.split_default(element);
let under = self.target_refs(target, mode)?;
self.emit(Op::IterValue(under));
self.default_value(default)?;
self.write_target(target, mode)?;
}
let end = self.pc();
let close_throw = self.new_label();
let after = self.new_label();
self.emit(Op::IterClose);
self.jump(Op::Jump, after);
self.handlers.push((start, end, close_throw, record, self.env_depth));
self.bind(close_throw);
self.depth = record + 1;
self.emit(Op::IterCloseThrow);
self.bind(after);
self.depth = record.saturating_sub(1);
Ok(())
}
/// `value` → nothing, for `{a, b: c, [d]: e = 1}` (sections 12.15.5.4 and 13.3.3.5).
fn object_pattern(&mut self, properties: &[Property], mode: Mode) -> CResult<()> {
self.emit(Op::RequireObjectCoercible);
for p in properties {
let PropertyValue::Init(value) = p.value else { return internal("a getter or setter in a pattern") };
self.at(p.span.start);
match &p.key {
PropertyKey::Computed(e) => {
self.expr(*e)?;
self.emit(Op::ToKey);
}
key => {
let i = self.string(&key.to_utf16());
self.emit(Op::String(i));
}
}
let (target, default) = self.split_default(value);
let under = self.target_refs(target, mode)?;
self.emit(Op::PatternGet(under));
self.default_value(default)?;
self.write_target(target, mode)?;
self.emit(Op::Pop);
}
self.emit(Op::Pop);
Ok(())
}
/// `for (target of iterable) body` (sections 13.7.5.12 and 13.7.5.13): the iterable is read
/// where a `let` or `const` head's names are not yet initialized; each step's value goes to
/// the target, in a new environment for a `let` or `const` head; the iterator is closed when
/// the loop is left early, by `break`, `return`, a jump to an outer loop or an exception.
pub(super) fn for_of(&mut self, target: &ForInTarget, iterable: ExprId, body: StmtId, labels: Vec<String>) -> CResult<()> {
let scope = match target {
ForInTarget::Lexical(kind, binding) => {
let constant = *kind == LexKind::Const;
let lets = self.bound_keys(binding).into_iter().map(|k| (k, constant)).collect();
Some(self.push_scope(BlockScope { lets, funcs: Vec::new() }))
}
_ => None,
};
match scope {
Some(s) => {
self.emit(Op::PushBlock(s));
self.env_depth += 1;
self.expr(iterable)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
}
None => self.expr(iterable)?,
}
// The loop's completion value starts as `undefined` (ForIn/OfBodyEvaluation, step 2).
if self.kind != CodeKind::Function {
self.emit(Op::Undefined);
self.emit(Op::SetCompletion);
}
self.at(self.ast.expr_span(iterable).start);
self.emit(Op::GetIterator);
let record = self.depth;
let outer_env = self.env_depth;
let head = self.new_label();
let brk = self.new_label();
let done = self.new_label();
let close_throw = self.new_label();
let after = self.new_label();
self.contexts.push(Ctx::Iterator { depth: record, env_depth: outer_env });
self.bind(head);
self.jump(Op::IterStep, done);
let start = self.pc();
if let Some(s) = scope {
self.emit(Op::PushBlock(s));
self.env_depth += 1;
}
let r = self.for_of_target(target);
let r = r.and_then(|()| {
self.push_jump_ctx(labels, true, true, brk, Some(head));
if let Some(Ctx::Jump { env_depth, .. }) = self.contexts.last_mut() {
*env_depth = outer_env;
}
let r = self.stmt(body);
self.contexts.pop();
r
});
self.contexts.pop();
r?;
if scope.is_some() {
self.emit(Op::PopEnv);
self.env_depth -= 1;
}
let end = self.pc();
self.jump(Op::Jump, head);
self.handlers.push((start, end, close_throw, record, outer_env));
self.bind(close_throw);
self.depth = record + 1;
self.emit(Op::IterCloseThrow);
self.bind(brk);
self.depth = record;
self.emit(Op::IterClose);
self.jump(Op::Jump, after);
self.bind(done);
self.depth = record;
self.emit(Op::Pop);
self.bind(after);
Ok(())
}
/// `value` → nothing: a `for-of` loop's step value written to its target.
fn for_of_target(&mut self, target: &ForInTarget) -> CResult<()> {
match target {
ForInTarget::Var(d) => self.bind_to(&d.target, Mode::Var),
ForInTarget::Lexical(_, binding) => self.bind_to(binding, Mode::Lexical),
ForInTarget::Expr(e) if self.is_pattern(*e) => self.destructure(*e, Mode::Assign),
ForInTarget::Expr(e) => {
self.store_key_to(*e)?;
self.emit(Op::Pop);
Ok(())
}
}
}
/// The key of a destructured parameter's own binding, which no script can name.
pub(super) fn hidden_param(&self, i: usize) -> Key {
key_of(&format!("\u{0}p{}", len_u32(i)))
}
}
+297 -11
View File
@@ -93,7 +93,10 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
syntax("try {} catch (e) { let e; }");
syntax("const c;");
syntax("let let = 1;");
syntax("let [a] = [1];");
syntax("let [a];");
syntax("let [let] = [1];");
syntax("let [a, a] = [1, 2];");
syntax("try {} catch ([e]) { let e; }");
syntax("'use strict'; { function f() {} function f() {} }");
syntax("for (let x = 1 in {}) {}");
syntax("if (1) let x = 1;");
@@ -322,14 +325,16 @@ fn rest_parameters_collect_the_remaining_arguments() {
// ---- spread ----
#[test]
fn spread_expands_arrays_strings_and_array_like_objects() {
fn spread_expands_what_an_iterator_gives() {
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'");
// A negative, NaN or fractional length is read as ToLength reads it.
truth("[...{ length: -1, 0: 'x' }].length === 0 && [...{ length: NaN }].length === 0");
truth("var b = [...{ length: 1.9, 0: 'x', 1: 'y' }]; b.join() === 'x'");
truth("function f() { return arguments.length; } f(...{ length: -4294967295, 0: 1 }) === 0");
truth("function f() { return [...arguments]; } f(1, 2).join() === '1,2'");
// Any object with an @@iterator method spreads, in the order its iterator gives.
truth(
"var n = 0; var it = { [Symbol.iterator]: function () { return { next: function () { n++; return { value: n, done: n > 3 }; } }; } }; \
var b = [...it]; b.join() === '1,2,3' && n === 4",
);
truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; [...a].join() === '9'");
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");
@@ -348,6 +353,10 @@ fn spreading_other_values_is_a_type_error() {
throws("[...null];", "TypeError");
throws("[...undefined];", "TypeError");
throws("[...{}];", "TypeError");
// An object with a length is not iterable for that.
throws("[...{ length: 2, 0: 'x', 1: 'y' }];", "TypeError");
throws("[...{ [Symbol.iterator]: function () { return 1; } }];", "TypeError");
throws("[...{ [Symbol.iterator]: function () { return { next: function () { return 1; } }; } }];", "TypeError");
throws("Math.max(...true);", "TypeError");
throws("new Array(...{ a: 1 });", "TypeError");
}
@@ -355,13 +364,16 @@ fn spreading_other_values_is_a_type_error() {
#[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();
let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }";
let e = realm.run(&format!("[...{endless}]")).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let e = realm.run("var a = []; a.length = 4294967294; [0, ...a];").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");
throws("function f() {} var a = []; a.length = 100000; f(...a);", "RangeError");
}
#[test]
@@ -408,13 +420,285 @@ fn for_each_takes_let_and_const_with_e4x() {
assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
}
// ---- for-of and destructuring ----
/// An iterable whose iterator gives 1 to `n` and counts the calls to its `return` method in
/// `closed`.
const COUNTED: &str = "var closed = 0; function it(n) { var i = 0; return { [Symbol.iterator]: function () { return this; }, \
next: function () { i++; return { value: i, done: i > n }; }, return: function () { closed++; return {}; } }; } ";
fn counted(src: &str) {
truth(&format!("{COUNTED}{src}"));
}
#[test]
fn for_of_runs_the_body_for_each_value() {
truth("var s = ''; for (var x of ['a', 'b']) s += x; s === 'ab' && x === 'b'");
truth("var s = []; for (var c of 'a\\uD83D\\uDE00') s.push(c); s.length === 2 && s[1] === '\\uD83D\\uDE00'");
truth("var n = 0; for (var x of []) n++; n === 0");
truth("var o = {}; for (o.p of [1, 2]); o.p === 2");
truth("var r = []; for (var [a, b] of [[1, 2], [3, 4]]) r.push(a + b); r.join() === '3,7'");
truth("var a, b; for ([a, { b }] of [[1, { b: 2 }]]); a === 1 && b === 2");
truth("var r = []; outer: for (var i = 0; i < 2; i++) { for (var x of [1, 2]) { if (x === 2) continue outer; r.push(i); } } r.join() === '0,1'");
truth("var s = 0; for (var x of [1, 2, 3]) { if (x === 2) continue; s += x; } s === 4");
truth("eval('1; for (var x of []) {}') === undefined && eval('1; for (var x of [2]) { break; }') === undefined");
truth("eval('1; for (var x of [2, 3]) { x; }') === 3");
}
#[test]
fn for_of_let_and_const_get_a_binding_for_each_iteration() {
truth("var fs = []; for (let x of [1, 2]) fs.push(function () { return x; }); fs[0]() === 1 && fs[1]() === 2");
truth("var fs = []; for (const [k, v] of [[1, 2], [3, 4]]) fs.push(() => k + v); fs[0]() === 3 && fs[1]() === 7");
truth("for (let x of [1]) {} typeof x === 'undefined'");
throws("for (const x of [1]) x = 2;", "TypeError");
// The iterable is read where the head's names are not yet initialized.
throws("let x = [1]; for (let x of x) {}", "ReferenceError");
}
#[test]
fn for_of_closes_the_iterator_when_the_loop_is_left_early() {
counted("for (var x of it(5)) break; closed === 1 && x === 1");
counted("function f() { for (var x of it(5)) return x * 10; } f() === 10 && closed === 1");
counted("try { for (var x of it(5)) throw 1; } catch (e) {} closed === 1");
counted("outer: for (var i = 0; i < 2; i++) for (var x of it(5)) continue outer; closed === 2");
counted("for (var x of it(5)) for (var y of it(5)) break; closed === 5");
counted("try { for (var x of it(5)) { try { break; } finally { closed += 10; } } } finally {} closed === 11");
counted("var r; try { for (var [a = (function () { throw 7; })()] of [[]]); } catch (e) { r = e; } r === 7");
// An iterator that finishes, or whose own next method throws, is not closed.
counted("for (var x of it(2)); closed === 0");
counted("var t = it(5); t.next = function () { throw 3; }; try { for (var x of t); } catch (e) {} closed === 0");
// Nor is one whose result's `value` getter throws (sections 13.7.5.13 and 13.3.3.6).
let bad_value = "var t = it(5); t.next = function () { return { done: false, get value() { throw 4; } }; };";
counted(&format!("{bad_value} var r; try {{ for (var x of t); }} catch (e) {{ r = e; }} r === 4 && closed === 0"));
counted(&format!("{bad_value} var r; try {{ var [a] = t; }} catch (e) {{ r = e; }} r === 4 && closed === 0"));
}
#[test]
fn closing_an_iterator_reports_a_bad_return_unless_an_exception_is_on_its_way() {
let bad = "var bad = { [Symbol.iterator]: function () { return this; }, next: function () { return { value: 1, done: false }; }, \
return: function () { return 1; } }; ";
throws(&format!("{bad} for (var x of bad) break;"), "TypeError");
truth(&format!("{bad} var r; try {{ for (var x of bad) throw new RangeError('x'); }} catch (e) {{ r = e; }} r instanceof RangeError"));
let throwing = "var t = { [Symbol.iterator]: function () { return this; }, next: function () { return { value: 1, done: false }; }, \
return: function () { throw new SyntaxError('r'); } }; ";
throws(&format!("{throwing} for (var x of t) break;"), "SyntaxError");
truth(&format!("{throwing} var r; try {{ for (var x of t) throw 5; }} catch (e) {{ r = e; }} r === 5"));
}
#[test]
fn array_patterns_step_the_iterator_and_close_it() {
truth("var [a, , b = 3, ...c] = [1, 2, undefined, 4, 5]; a === 1 && b === 3 && c.join() === '4,5'");
truth("var [a, b] = 'xy'; a + b === 'xy'");
truth("var [a, b] = [1]; a === 1 && b === undefined");
truth("let [[a], [b]] = [[1], [2]]; a + b === 3");
truth("var [...[a, b]] = [1, 2]; a + b === 3");
counted("var [a] = it(5); closed === 1 && a === 1");
counted("var [a, ...r] = it(2); closed === 0 && r.join() === '2'");
counted("var [] = it(5); closed === 1");
counted("var [a, b] = it(1); closed === 0 && b === undefined");
counted("try { var [a = (function () { throw 1; })()] = it(0); } catch (e) {} closed === 0");
counted("try { var [a, b = (function () { throw 1; })()] = [1]; } catch (e) {} closed === 0");
counted("var o = { set p(v) { throw 2; } }; try { [o.p] = it(5); } catch (e) {} closed === 1");
throws("var [a] = {};", "TypeError");
throws("var [a] = 1;", "TypeError");
}
#[test]
fn object_patterns_read_properties_by_name() {
truth("let { x, y: z = 2, ['w' + 1]: w } = { x: 1, w1: 4 }; x === 1 && z === 2 && w === 4");
truth("const [{ a: [b] }] = [{ a: [7] }]; b === 7");
truth("var { length } = 'abc'; length === 3");
truth("var s = Symbol(); var { [s]: v } = { [s]: 9 }; v === 9");
truth("var { 0: a, 'b c': b } = { 0: 1, 'b c': 2 }; a + b === 3");
truth(
"var order = []; var o = { get a() { order.push('a'); return 1; }, get b() { order.push('b'); return 2; } }; \
var { b, a } = o; order.join() === 'b,a'",
);
}
#[test]
fn destructuring_assignment_writes_to_any_assignment_target() {
truth("var a = 1, b = 2; [a, b] = [b, a]; a === 2 && b === 1");
truth("var a; var v = [1, 2]; var r = ([a] = v); r === v && a === 1");
truth("var o = {}; [o.a, o['b']] = [1, 2]; ({ c: o.c } = { c: 3 }); o.a + o.b + o.c === 6");
truth("var a, b; ({ a, b = 5 } = { a: 1 }); a === 1 && b === 5");
truth("var x, y; [x = 1, [y] = [2]] = []; x === 1 && y === 2");
truth("var r = []; var a; [a = r.push('default')] = [undefined]; a === 1 && r.length === 1");
}
#[test]
fn destructured_parameters_and_catch_clauses() {
truth("function f([a, b], { c } = { c: 3 }) { return a + b + c; } f([1, 2]) === 6");
truth("(([a], { b }) => a + b)([1], { b: 2 }) === 3");
truth("function f(...[a, b]) { return a + b; } f(1, 2) === 3");
truth("function f(a, [b], c = 1) {} f.length === 2");
truth("function f({ a }, b) {} f.length === 2");
truth("function f([a], b = a) { return b; } f([4]) === 4");
truth("function f({ a }) { var a; return a; } f({ a: 6 }) === 6");
truth("var r; try { throw { m: 'x', d: [1] }; } catch ({ m, d: [n] }) { r = m + n; } r === 'x1'");
truth("var r; try { throw [1, 2]; } catch ([a, b]) { r = function () { return a + b; }; } r() === 3");
throws("function f({ a }) {} f();", "TypeError");
throws("try { throw null; } catch ({ a }) {}", "TypeError");
throws("function f([a], b = a) {} f([]); f(undefined);", "TypeError");
}
#[test]
fn defaults_run_only_for_undefined() {
truth(
"var n = 0; function d() { n++; return 5; } var [a = d()] = [null]; var { b = d() } = { b: 0 }; var [c = d()] = []; \
var { e = d() } = { e: undefined }; a === null && b === 0 && c === 5 && e === 5 && n === 2",
);
truth("var n = 0; function f([a = n++] = [], { b = n++ } = {}) { return a + b; } f([3], { b: 4 }) === 7 && n === 0");
}
#[test]
fn destructuring_undefined_or_null_is_a_type_error() {
throws("var { a } = null;", "TypeError");
throws("var {} = undefined;", "TypeError");
throws("var [a] = null;", "TypeError");
throws("({ a } = undefined);", "TypeError");
throws("for (var { a } of [null]);", "TypeError");
throws("let { a: { b } } = { a: null };", "TypeError");
truth("var { toFixed } = 1; typeof toFixed === 'function'");
}
#[test]
fn object_literals_take_shorthand_and_computed_names() {
truth("var a = 1; var o = { a, ['b' + 1]: 2 }; o.a === 1 && o.b1 === 2");
truth("var s = Symbol('k'); var o = { [s]: 3 }; o[s] === 3 && Object.keys(o).length === 0");
truth("var o = { get ['x' + 1]() { return 4; }, set ['x' + 1](v) { this.y = v; } }; o.x1 = 5; o.x1 === 4 && o.y === 5");
truth("var order = []; var o = { [(order.push(1), 'a')]: order.push(2) }; order.join() === '1,2' && o.a === 2");
}
#[test]
fn bad_patterns_are_syntax_errors() {
for src in [
"({ a = 1 });",
"var o = { a = 1 };",
"[...a, b] = [];",
"[...a,] = [];",
"var [...a, b] = [];",
"({ get a() { return 1; } } = {});",
"([a]) = [];",
"[(a = 1)] = [];",
"[a()] = [];",
"[a + 1] = [];",
"'use strict'; [eval] = [];",
"'use strict'; var { arguments } = {};",
"var [a];",
"const { a };",
"for (var x = 1 of []) ;",
"for (let x = 1 of []) ;",
"for (var [x] = 1 in {}) ;",
"for (x of [], []) ;",
"for (let.x of []) ;",
"for (async of []) ;",
"for (var x of []) let\n[a] = 0;",
"if (1) let [a] = [];",
"for (a() of []) ;",
"function f([a]) { 'use strict'; }",
"function f([a, a]) {}",
"function f(a, [a]) {}",
"([a, a]) => 1;",
"try {} catch ([e, e]) {}",
"try {} catch ([e]) { for (var e of []); }",
"({ a: 1 } = {});",
"[...[a] = []] = [];",
"var a; [a = { b = 1 }] = [];",
"var a; ({ a = { b = 1 } } = {});",
"var a; ({ [{ b = 1 }]: a } = {});",
"for ([a = { b = 1 }] of []) ;",
"(a = { b = 1 }) => 0;",
"([a = { b = 1 }]) => 0;",
] {
syntax(src);
}
// A shorthand property with an initializer is a target only in the pattern that holds it.
truth("var a, b; [{ b = 1 }] = [{}]; ({ a: { b = 2 } = {} } = {}); b === 2");
truth("var f = ({ a = 1 }, [{ b = 2 }] = [{}]) => a + b; f({}) === 3");
// `of` stays a name.
truth("var of = [1]; var n = 0; for (var x of of) n += x; n === 1");
}
#[test]
fn a_realm_without_the_later_built_ins_walks_arrays_arguments_and_strings() {
let mut realm = Realm::new();
realm.set_es2015(true);
let src = "var s = ''; for (var x of [1, 2]) s += x; for (var c of 'a\\uD83D\\uDE00') s += c.length; \
(function () { for (var a of arguments) s += a; })(3); var [p, ...q] = 'xyz'; \
s === '1212' + '3' && [...[4, 5]].length === 2 && p === 'x' && q.join('') === 'yz'";
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
let r = realm.run("for (var x of {}) {}");
assert!(matches!(&r, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("TypeError")), "{r:?}");
}
#[test]
fn for_of_and_patterns_stay_within_the_limits() {
let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }";
for src in [format!("for (var x of {endless});"), format!("var [...r] = {endless};")] {
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let e = realm.run(&src).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{src}: {e:?}");
}
// Spread and a rest element reserve each new element's whole size, its index name included,
// so the run ends at the heap limit without passing it, wherever the limit falls. A realm
// without `Symbol.iterator` walks the array by index and makes no result objects.
let walking = |limits: Limits| {
let mut realm = Realm::with_options(Options::default(), limits);
realm.set_es2015(true);
realm
};
let setup = "var a = []; for (var i = 0; i < 2000; i++) a.push(i); 0";
let mut measure = walking(Limits::default());
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
measure.interp().collect_garbage();
let base = measure.interp().heap.bytes + 100_000;
let mut wrong = Vec::new();
for src in ["var b = [...a]; 0", "var [...b] = a; 0"] {
for heap_bytes in (base..base + 128).step_by(2) {
let mut realm = walking(Limits { heap_bytes, ..Limits::default() });
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
let r = realm.run(src).map_err(|e| e.kind);
let bytes = realm.interp().heap.bytes;
if r != Err(RunErrorKind::Limit(LimitKind::Heap)) || bytes > heap_bytes {
wrong.push((src, heap_bytes, r, bytes));
}
}
}
assert!(wrong.is_empty(), "runs that ended past the heap limit: {wrong:?}");
// Patterns nested past the nesting limit are a SyntaxError.
for src in [format!("var {}a{} = 1;", "[".repeat(5000), "]".repeat(5000)), format!("({}a{} = 1);", "[".repeat(5000), "]".repeat(5000))] {
let e = es().run(&src).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]"] {
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]",
"for (var x of []) {}",
"var [a] = [1];",
"var { a } = {};",
"({ a } = {});",
"function f([a]) {}",
"try {} catch ({ a }) {}",
"var o = { ['a']: 1 };",
] {
let r = Realm::new().run(src);
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() };
let r = Realm::with_options(extendscript, Limits::default()).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)));
@@ -432,6 +716,8 @@ fn code_made_at_run_time_reads_the_realm_s_language() {
// ---- robustness ----
const FRAGMENTS: &[&str] = &[
" of ",
"...",
"let ",
"const ",
"var ",
+15 -2
View File
@@ -231,6 +231,9 @@ pub(crate) enum Class {
Symbol(crate::symbol::Sym),
/// An Array Iterator or a String Iterator and how far it has gone (sections 22.1.5 and 21.1.5).
Iterator(Box<crate::builtins::iterator::IterState>),
/// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the
/// operand stack only.
IterRecord(Box<crate::iteration::IterRecord>),
ForIn(Box<ForIn>),
/// The `Math` object (section 15.8).
Math,
@@ -316,7 +319,7 @@ impl Class {
Class::XmlFilter(_) => "Object",
Class::Math => "Math",
Class::Json => "JSON",
Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) => "Object",
Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
Class::Array { .. } => "Array",
Class::Function(_) => "Function",
Class::Error(_) => "Error",
@@ -641,6 +644,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
+ code.names.len()
+ code.functions.len()
+ code.params.len()
+ code.pattern_names.len()
+ code.vars.len()
+ 2 * code.fun_decls.len()
+ code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::<usize>()
@@ -660,7 +664,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
strings.add(pattern);
strings.add(flags);
}
let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
let keys = code.names.iter().chain(&code.params).chain(&code.pattern_names).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) {
strings.add_key(k);
}
@@ -713,6 +717,15 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
}
Class::Symbol(s) => strings.add_symbol(s),
Class::IterRecord(r) => {
mark_value(&r.iterator, work, strings);
mark_value(&r.next, work, strings);
match &r.walk {
Some(crate::iteration::Walk::Array(a, _)) => work.push(a.0),
Some(crate::iteration::Walk::String(s, _)) => strings.add(s),
None => {}
}
}
Class::Iterator(state) => match &**state {
crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)),
crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)),
+78 -86
View File
@@ -49,7 +49,7 @@ pub(crate) type JsResult<T> = Result<T, Abrupt>;
/// with a NUL, which no identifier holds.
const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73];
fn internal<T>(message: &str) -> JsResult<T> {
pub(crate) fn internal<T>(message: &str) -> JsResult<T> {
Err(Abrupt::Internal(message.into()))
}
@@ -1102,6 +1102,16 @@ impl Interp {
self.replace(1, Value::String(s))
}
Op::TemplateObject(i) => self.op_template_object(i),
Op::GetIterator => self.op_get_iterator(),
Op::IterStep(t) => self.op_iter_step(t),
Op::IterValue(n) => self.op_iter_value(n),
Op::IterRest(n) => self.op_iter_rest(n),
Op::IterClose => self.op_iter_close(),
Op::IterCloseThrow => self.op_iter_close_throw(),
Op::RequireObjectCoercible => self.op_require_object_coercible(),
Op::PatternGet(n) => self.op_pattern_get(n),
Op::InitIndex => self.op_init_index(),
Op::InitAccessorIndex(getter) => self.op_init_accessor_index(getter),
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
}
}
@@ -1152,6 +1162,26 @@ impl Interp {
Err(self.throw(ErrorType::Reference, &message))
}
/// Throws `v` again from a handler that is not a catch clause, with the stack cut back to
/// where the handler took it: the exception keeps the position and mark it was thrown with.
pub(crate) fn rethrow(&mut self, v: Value) -> Abrupt {
self.passing = v.clone();
self.throw_site = None;
self.thrown_mark = None;
if let Value::Object(o) = v
&& let Some(i) = self.finally_marks.iter().rposition(|&(id, _, _)| id == o)
{
self.thrown_mark = self.finally_marks.get(i).map(|&(_, mark, _)| mark);
self.finally_marks.truncate(i);
}
let slot = self.stack.len();
if let Some(i) = self.finally_sites.iter().rposition(|&(_, s)| s == slot) {
self.throw_site = self.finally_sites.get(i).map(|(site, _)| site.clone());
self.finally_sites.truncate(i);
}
Abrupt::Throw(v)
}
fn op_end_finally(&mut self, table: u32) -> JsResult<()> {
let Value::Number(kind) = self.pop()? else { return internal("finally kind is not a number") };
if kind == 0.0 {
@@ -1159,19 +1189,7 @@ impl Interp {
}
if kind == 1.0 {
let v = self.pop()?;
self.passing = v.clone();
if let Value::Object(o) = v
&& let Some(i) = self.finally_marks.iter().rposition(|&(id, _, _)| id == o)
{
self.thrown_mark = self.finally_marks.get(i).map(|&(_, mark, _)| mark);
self.finally_marks.truncate(i);
}
let slot = self.stack.len();
if let Some(i) = self.finally_sites.iter().rposition(|&(_, s)| s == slot) {
self.throw_site = self.finally_sites.get(i).map(|(site, _)| site.clone());
self.finally_sites.truncate(i);
}
return Err(Abrupt::Throw(v));
return Err(self.rethrow(v));
}
let k = (kind - 2.0) as usize;
let target = self.frame()?.code.finally_tables.get(table as usize).and_then(|t| t.get(k)).copied();
@@ -2078,6 +2096,47 @@ impl Interp {
self.define(o, name, Prop::Accessor { get, set, flags: ENUMERABLE | CONFIGURABLE })
}
/// `object key value` → `object`: a property with a computed name, the key already a name or
/// a Symbol.
fn op_init_index(&mut self) -> JsResult<()> {
let v = self.pop()?;
let k = self.pop()?;
let Value::Object(o) = self.peek(0)? else { return internal("object literal is not an object") };
let prop = Prop::Data { value: v, flags: OPEN };
match k {
Value::Symbol(s) => self.define_sym(o, s, prop),
Value::String(s) => self.define(o, s.flat(), prop),
_ => internal("computed property name is not a key"),
}
}
/// `object key function` → `object`: a getter (or a setter) with a computed name.
fn op_init_accessor_index(&mut self, getter: bool) -> JsResult<()> {
let Value::Object(f) = self.pop()? else { return internal("accessor is not a function") };
let k = self.pop()?;
let Value::Object(o) = self.peek(0)? else { return internal("object literal is not an object") };
let current = match &k {
Value::Symbol(s) => self.get_own_sym(o, s)?,
Value::String(s) => self.object(o)?.props.get(&s.flat()).cloned(),
_ => return internal("computed property name is not a key"),
};
let (mut get, mut set) = match current {
Some(Prop::Accessor { get, set, .. }) => (get, set),
_ => (None, None),
};
if getter {
get = Some(f);
} else {
set = Some(f);
}
let prop = Prop::Accessor { get, set, flags: ENUMERABLE | CONFIGURABLE };
match k {
Value::Symbol(s) => self.define_sym(o, s, prop),
Value::String(s) => self.define(o, s.flat(), prop),
_ => internal("computed property name is not a key"),
}
}
fn op_closure(&mut self, i: u32) -> JsResult<()> {
let frame = self.frame()?;
let (env, this) = (frame.env, frame.this.clone());
@@ -2304,77 +2363,6 @@ impl Interp {
// ---- 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<Value> = 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)?;
// ToLength (ECMA-262 2015 section 7.1.15): a negative or NaN length reads nothing.
let n = crate::string_builtins::to_integer(self.to_number(&len)?).max(0.0);
let current = match &self.object(a)?.class {
Class::Array { length, .. } => *length,
_ => return internal("spread into something that is not an array"),
};
let Some(n) = u32::MAX.checked_sub(current).filter(|room| n < f64::from(*room)).map(|_| n as u32) else {
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<u32> {
let Value::Object(a) = self.peek(0)? else { return internal("arguments are not an array") };
@@ -2737,7 +2725,7 @@ impl Interp {
if self.frames.len() >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
}
let params = code.params.iter().fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
let arguments =
if code.uses_arguments { OBJECT_BYTES.saturating_add(args.len().saturating_add(4).saturating_mul(binding_bytes(10))) } else { 0 };
let need = declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(params).saturating_add(arguments);
@@ -2803,6 +2791,10 @@ impl Interp {
b.lexical = code.param_init;
bindings.insert(rest.clone(), b);
}
for name in &code.pattern_names {
self.use_fuel()?;
bindings.insert(name.clone(), Binding::lexical(false));
}
let name_bytes = bindings.iter().map(|(k, _)| string_bytes(k.len())).sum::<usize>();
let env = self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) });
self.heap.bytes += name_bytes;
+1
View File
@@ -983,6 +983,7 @@ fn code(ops: Vec<Op>) -> Code {
arrow: false,
uses_this: false,
param_init: false,
pattern_names: Vec::new(),
}
}
+274
View File
@@ -0,0 +1,274 @@
//! The iterator protocol as `for-of`, array destructuring and spread use it (ECMA-262 11th
//! edition, <https://262.ecma-international.org/11.0/>): GetIterator (section 7.4.1),
//! IteratorStep (section 7.4.5) and IteratorClose (section 7.4.6), and the instructions that run
//! them.
//!
//! An Iterator Record lives on the operand stack as an object of its own class, which no script
//! can reach. Its `done` flag is set before each call that can throw, so a handler that closes
//! the iterator on an exception does not call `return` for an iterator that threw itself, has
//! finished, or is being closed already. Each step takes a unit of fuel.
//!
//! A realm made without [`crate::Options::es2015`] has no `Symbol.iterator`. When such a realm
//! later reads ECMAScript 2015 code ([`crate::Realm::set_es2015`]), arrays, `arguments` objects
//! and strings are walked as their iterators would walk them, and other values are not iterable.
use crate::heap::{Class, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes};
use crate::interp::{Abrupt, ErrorType, Interp, JsResult, internal};
use crate::value::{Str, Value, index_key, number_to_str};
/// An Iterator Record (section 7.4.1): the iterator, its `next` method, and whether it is done.
#[derive(Clone)]
pub(crate) struct IterRecord {
pub(crate) iterator: Value,
pub(crate) next: Value,
pub(crate) done: bool,
/// In a realm without the ECMAScript 2015 built-ins (one made without
/// [`crate::Options::es2015`] that later reads ECMAScript 2015 code), the walk over an array,
/// an `arguments` object or a string that stands in for their iterators.
pub(crate) walk: Option<Walk>,
}
/// A walk that steps as `%ArrayIteratorPrototype%.next` and `%StringIteratorPrototype%.next` do.
#[derive(Clone)]
pub(crate) enum Walk {
/// The object, read with its `length` at each step, and the next index.
Array(ObjId, f64),
/// The string, flat, and the next position in code units.
String(Str, usize),
}
impl Interp {
fn record(&mut self, rec: ObjId) -> JsResult<&mut IterRecord> {
match &mut self.object_mut(rec)?.class {
Class::IterRecord(r) => Ok(r),
_ => internal("not an iterator record"),
}
}
fn record_at(&self, n: usize) -> JsResult<ObjId> {
match self.peek(n)? {
Value::Object(o) => Ok(o),
_ => internal("iterator record is not an object"),
}
}
/// GetIterator (section 7.4.1): the record of the iterator `v`'s `@@iterator` method gives.
pub(crate) fn get_iterator(&mut self, v: &Value) -> JsResult<ObjId> {
let method = match self.well_known(|w| &w.iterator) {
Some(sym) if !v.is_nullish() => self.get_value_sym(v, &sym)?,
Some(_) => Value::Undefined,
None => return self.walk_record(v),
};
if !self.is_callable(&method) {
let what = match v {
Value::Undefined => "undefined",
Value::Null => "null",
_ => "the value",
};
return Err(self.type_error(&format!("{what} is not iterable")));
}
let iterator = self.call(&method, v, &[])?;
if !matches!(iterator, Value::Object(_)) {
return Err(self.type_error("the iterator is not an object"));
}
let next = self.rooted(std::slice::from_ref(&iterator), |i| i.get_value(&iterator, &key("next")))?;
let record = IterRecord { iterator, next, done: false, walk: None };
Ok(self.heap.alloc_object(Object::new(Class::IterRecord(Box::new(record)), None)))
}
/// The record of a [`Walk`] over an array, an `arguments` object or a string, for a realm
/// without `Symbol.iterator`; any other value is not iterable there.
fn walk_record(&mut self, v: &Value) -> JsResult<ObjId> {
let walk = match v {
Value::String(s) => Walk::String(Str::from_rc(s.flat()), 0),
Value::Object(o) if matches!(self.object(*o)?.class, Class::Array { .. } | Class::Arguments(_)) => Walk::Array(*o, 0.0),
_ => return Err(self.type_error("the value is not iterable")),
};
let record = IterRecord { iterator: Value::Undefined, next: Value::Undefined, done: false, walk: Some(walk) };
Ok(self.heap.alloc_object(Object::new(Class::IterRecord(Box::new(record)), None)))
}
/// One step of the [`Walk`] of `rec`, which is not done: the next value, or `None` at the end.
fn walk_step(&mut self, rec: ObjId, walk: Walk) -> JsResult<Option<Value>> {
self.use_fuel()?;
let (value, walk) = match walk {
Walk::Array(a, i) => {
let length = self.get_from(a, &key("length"), &Value::Object(a))?;
let n = self.to_number(&length)?;
if n.is_nan() || i >= n.trunc() {
return Ok(None);
}
let v = self.get_from(a, &number_to_str(i).flat(), &Value::Object(a))?;
(v, Walk::Array(a, i + 1.0))
}
Walk::String(s, pos) => {
let units = s.flat();
let Some(&first) = units.get(pos) else { return Ok(None) };
let pair = (0xD800..0xDC00).contains(&first) && units.get(pos + 1).is_some_and(|u| (0xDC00..0xE000).contains(u));
let width = if pair { 2 } else { 1 };
let piece = units.get(pos..pos + width).map(<[u16]>::to_vec).unwrap_or_default();
(Value::String(Str::from_units(piece)), Walk::String(s, pos + width))
}
};
let r = self.record(rec)?;
r.walk = Some(walk);
r.done = false;
Ok(Some(value))
}
/// IteratorStep and IteratorValue (sections 7.4.5 and 7.4.4): the next value, or `None` when
/// the iterator is done. The record stays done when the step throws.
pub(crate) fn iter_next(&mut self, rec: ObjId) -> JsResult<Option<Value>> {
let r = self.record(rec)?;
if r.done {
return Ok(None);
}
r.done = true;
if let Some(walk) = r.walk.clone() {
return self.walk_step(rec, walk);
}
let (iterator, next) = (r.iterator.clone(), r.next.clone());
self.use_fuel()?;
let result = self.call(&next, &iterator, &[])?;
if !matches!(result, Value::Object(_)) {
return Err(self.type_error("the iterator result is not an object"));
}
let value = self.rooted(std::slice::from_ref(&result), |i| {
if i.get_value(&result, &key("done"))?.truthy() {
return Ok(None);
}
i.get_value(&result, &key("value")).map(Some)
})?;
if value.is_some() {
self.record(rec)?.done = false;
}
Ok(value)
}
/// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return`
/// method, unless it is done, and checks that it gives an object.
fn iter_close(&mut self, rec: ObjId) -> JsResult<()> {
let r = self.record(rec)?;
if r.done {
return Ok(());
}
r.done = true;
if r.walk.is_some() {
return Ok(());
}
let iterator = r.iterator.clone();
self.rooted(std::slice::from_ref(&iterator), |i| {
let method = i.get_value(&iterator, &key("return"))?;
if method.is_nullish() {
return Ok(());
}
if !i.is_callable(&method) {
return Err(i.type_error("the iterator's return is not a function"));
}
match i.call(&method, &iterator, &[])? {
Value::Object(_) => Ok(()),
_ => Err(i.type_error("the iterator's return gave something that is not an object")),
}
})
}
/// `value` → `record`.
pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let rec = self.get_iterator(&v)?;
self.replace(1, Value::Object(rec))
}
/// `record` → `record value`, or jumps with `record` when the iterator is done.
pub(crate) fn op_iter_step(&mut self, target: u32) -> JsResult<()> {
let rec = self.record_at(0)?;
match self.iter_next(rec)? {
Some(v) => self.push(v),
None => self.jump_to(target),
}
}
/// `record x₁…xₙ` → `record x₁…xₙ value`: the next value, or `undefined` when the iterator
/// is done.
pub(crate) fn op_iter_value(&mut self, under: u32) -> JsResult<()> {
let rec = self.record_at(under as usize)?;
let v = self.iter_next(rec)?.unwrap_or(Value::Undefined);
self.push(v)
}
/// `record x₁…xₙ` → `record x₁…xₙ array`: an array of the values left.
pub(crate) fn op_iter_rest(&mut self, under: u32) -> JsResult<()> {
let rec = self.record_at(under as usize)?;
let proto = self.intrinsics.array_proto;
let a = self.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto)));
self.push(Value::Object(a))?;
self.append_values(rec, a)
}
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack.
fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
while let Some(v) = self.iter_next(rec)? {
let Class::Array { length, .. } = &self.object(a)?.class else { return internal("not an array") };
let i = *length;
if i == u32::MAX - 1 {
return Err(self.throw(ErrorType::Range, "array too long"));
}
let k = index_key(i);
self.rooted(std::slice::from_ref(&v), |interp| interp.reserve_heap(PROP_BYTES + string_bytes(k.len())))?;
let Class::Array { length, .. } = &mut self.object_mut(a)?.class else { return internal("not an array") };
*length = i + 1;
self.define(a, k, Prop::Data { value: v, flags: OPEN })?;
}
Ok(())
}
/// `array value` → `array`, with the values the value's iterator gives appended (spread,
/// ECMA-262 11th edition section 12.2.5.2).
pub(crate) 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 rec = self.get_iterator(&v)?;
self.replace(1, Value::Object(rec))?;
self.append_values(rec, a)?;
self.pop().map(drop)
}
/// `record` → nothing: closes the iterator unless it is done.
pub(crate) fn op_iter_close(&mut self) -> JsResult<()> {
let rec = self.record_at(0)?;
self.iter_close(rec)?;
self.pop().map(drop)
}
/// `record exception` → throws the exception, after closing the iterator unless it is done.
/// What closing it throws is dropped (section 7.4.6, step 6); running out of fuel, heap or
/// time is not.
pub(crate) fn op_iter_close_throw(&mut self) -> JsResult<()> {
let exception = self.pop()?;
let rec = self.record_at(0)?;
let closed = self.rooted(std::slice::from_ref(&exception), |i| i.iter_close(rec));
match closed {
Ok(()) | Err(Abrupt::Throw(_)) => Err(self.rethrow(exception)),
Err(other) => Err(other),
}
}
/// `value` → `value`: a `TypeError` when it is `undefined` or `null` (RequireObjectCoercible,
/// section 7.2.1), before an object pattern reads it.
pub(crate) fn op_require_object_coercible(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
if v.is_nullish() {
let what = if matches!(v, Value::Null) { "null" } else { "undefined" };
return Err(self.type_error(&format!("cannot destructure {what}")));
}
Ok(())
}
/// `object key x₁…xₙ` → `object key x₁…xₙ object[key]`.
pub(crate) fn op_pattern_get(&mut self, under: u32) -> JsResult<()> {
let k = self.peek(under as usize)?;
let object = self.peek(under as usize + 1)?;
let v = self.with_prop_key(&k, |i, pk| i.get_value_pk(&object, &pk))?;
self.push(v)
}
}
+15 -7
View File
@@ -53,9 +53,14 @@
//! 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.
//! `new` (sections 12.2.5 and 12.3.6.1), `for … of` loops (section 13.7.5), array and object
//! destructuring in declarations, assignments, parameters and `catch` clauses (sections 12.15.5
//! and 13.3.3), and shorthand and computed property names in object literals (section 12.2.6).
//! Spread, `for … of` and array patterns use the iterator protocol of the 11th edition
//! (<https://262.ecma-international.org/11.0/>, section 7.4), and a loop or pattern left early
//! closes its iterator. In a realm made without the option and later given it with
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays, `arguments` objects and strings by index and throw a `TypeError` for other values.
//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors.
//!
//! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4,
//! <https://262.ecma-international.org/11.0/>): `Symbol.for` and `Symbol.keyFor` over a registry
@@ -80,6 +85,7 @@ mod file_classes;
mod heap;
mod host;
mod interp;
mod iteration;
mod lexer;
mod number;
mod number_builtins;
@@ -97,8 +103,9 @@ mod xml_builtins;
mod xpath;
pub use ast::{
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,
AssignOp, Ast, BinaryOp, Binding, 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};
@@ -123,8 +130,9 @@ pub struct Options {
/// 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
/// template literals (tagged ones included), default and rest parameters, spread in array
/// literals, calls and `new`, `for … of`, array and object destructuring, and shorthand and
/// computed property names. 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.
/// On, a realm also has the later editions' built-ins this engine has: `Symbol` with
/// Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects. Off, a
+151 -69
View File
@@ -7,14 +7,15 @@
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
//! runs of them do not nest at all.
mod pattern;
mod xml;
use std::collections::{HashMap, HashSet};
use crate::LineTable;
use crate::ast::{
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LexKind, LogicalOp, Name, Program, Property,
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl,
AssignOp, Ast, BinaryOp, Binding, 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};
@@ -56,9 +57,9 @@ struct Scope {
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<Name>, Vec<Option<ExprId>>, Option<Name>);
/// The parameters of a function as they are read: names or patterns, each one's default value,
/// and a rest parameter.
type Params = (Vec<Binding>, Vec<Option<ExprId>>, Option<Binding>);
/// A binary operator, with the logical ones apart.
#[derive(Clone, Copy, Debug)]
@@ -101,6 +102,15 @@ pub(crate) struct Parser<'s> {
es2015: bool,
/// The scopes open around the current token, outermost first (only with `es2015`).
scopes: Vec<Scope>,
/// Where each shorthand property with an initializer (`{a = 1}`) not yet read as part of a
/// destructuring pattern starts; one left when its expression ends is a `SyntaxError`.
cover_inits: Vec<u32>,
/// The next assignment expression may leave such properties to a pattern around it: it is an
/// element of an array or object literal, an arrow function's parenthesized head or a
/// `for` loop's head.
cover_ok: bool,
/// The spread elements of array literals followed by a comma, which cannot end a pattern.
rest_commas: HashSet<u32>,
}
impl<'s> Parser<'s> {
@@ -125,6 +135,9 @@ impl<'s> Parser<'s> {
e4x: options.e4x,
es2015: options.es2015,
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
cover_inits: Vec::new(),
cover_ok: false,
rest_commas: HashSet::new(),
};
parser.tok = parser.next_significant()?;
Ok(parser)
@@ -375,25 +388,32 @@ impl<'s> Parser<'s> {
}
/// `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.
/// `no_in` leaves `in` to a `for (… in …)` around them, where a `const` or a pattern may go
/// without an initializer, as in `for (… of …)`.
fn parse_lexical_decls(&mut self, kind: LexKind, no_in: bool) -> Result<Vec<VarDecl>> {
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 target = self.parse_declaration_target()?;
for name in self.ast.bound_names(&target) {
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 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)));
let in_head = no_in && (self.at_keyword(Keyword::In) || self.at_of()) && decls.is_empty();
if init.is_none() && !in_head {
match &target {
Binding::Pattern(p) => {
return Err(self.error_at_offset(self.ast.expr_span(*p).start, "a destructuring declaration needs an initializer"));
}
Binding::Name(name) if kind == LexKind::Const => {
return Err(self.error_at_offset(name.span.start, format!("const '{}' needs an initializer", name.name)));
}
Binding::Name(_) => {}
}
}
decls.push(VarDecl { name, init });
decls.push(VarDecl { target, init });
if !self.eat(Punct::Comma)? {
return Ok(decls);
}
@@ -525,6 +545,11 @@ impl<'s> Parser<'s> {
Ok(self.ast.push_stmt(Stmt::Empty, start))
}
TokenKind::Keyword(k) => self.keyword_statement(*k, start),
// An expression statement cannot start with `let [` (ECMA-262 2015 section 13.5); in
// a statement list that starts a declaration, and elsewhere it is an error.
_ if self.es2015 && self.tok.ident() == Some("let") && !self.tok.escaped && self.peek().is_some_and(|t| t.is_punct(Punct::LBracket)) => {
Err(self.error_at_token(&self.tok, "a lexical declaration cannot stand here; put it in a block"))
}
_ => {
let expr = self.parse_expression(false)?;
self.semicolon()?;
@@ -571,10 +596,20 @@ impl<'s> Parser<'s> {
}
/// `{ … }`, 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<Vec<StmtId>> {
/// declaration in the block must not take. A pattern's names are not taken by a `var` in the
/// block either (ECMA-262 2015 section 13.15.1 and Annex B.3.5).
fn parse_block_with(&mut self, param: Option<&Binding>) -> Result<Vec<StmtId>> {
self.expect(Punct::LBrace)?;
self.push_scope(false, param.map(str::to_string));
match param {
Some(Binding::Name(name)) => self.push_scope(false, std::iter::once(name.name.clone())),
Some(Binding::Pattern(p)) => {
self.push_scope(false, std::iter::empty());
for name in self.ast.pattern_names(*p) {
self.declare_lexical(&name, false)?;
}
}
None => self.push_scope(false, std::iter::empty()),
}
let body = self.block_items();
self.pop_scope();
let body = body?;
@@ -597,10 +632,18 @@ impl<'s> Parser<'s> {
fn parse_var_decls(&mut self, no_in: bool) -> Result<Vec<VarDecl>> {
let mut decls = Vec::new();
loop {
let name = self.binding_identifier()?;
self.declare_var(&name)?;
let target = self.parse_declaration_target()?;
for name in self.ast.bound_names(&target) {
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 let (Binding::Pattern(p), None) = (&target, init) {
let in_head = no_in && (self.at_keyword(Keyword::In) || self.at_of()) && decls.is_empty();
if !in_head {
return Err(self.error_at_offset(self.ast.expr_span(*p).start, "a destructuring declaration needs an initializer"));
}
}
decls.push(VarDecl { target, init });
if !self.eat(Punct::Comma)? {
return Ok(decls);
}
@@ -689,22 +732,45 @@ impl<'s> Parser<'s> {
} else if self.at_keyword(Keyword::Var) {
self.bump()?;
let mut decls = self.parse_var_decls(true)?;
if decls.len() == 1 && self.at_of() {
let decl = decls.pop().ok_or_else(|| self.unexpected())?;
return self.parse_for_of_var(decl, start);
}
if decls.len() == 1 && self.at_keyword(Keyword::In) {
let decl = decls.pop().ok_or_else(|| self.unexpected())?;
// The variable of a for-in loop takes an initializer only outside strict mode
// code (ECMA-262 2017 Annex B.3.6).
if self.ctx.strict && decl.init.is_some() {
return Err(self.error_at_token(&self.tok, "a for-in variable cannot have an initializer in strict mode code"));
// code, and only when it is a name (ECMA-262 2017 Annex B.3.6).
if decl.init.is_some() && (self.ctx.strict || matches!(decl.target, Binding::Pattern(_))) {
return Err(self.error_at_token(&self.tok, "a for-in variable cannot have an initializer here"));
}
return self.parse_for_in(ForInTarget::Var(decl), start, false);
}
Some(ForInit::Var(decls))
} else {
let starts_with_let = self.tok.ident() == Some("let") && !self.tok.escaped;
let async_of =
self.tok.ident() == Some("async") && !self.tok.escaped && self.peek().is_some_and(|t| t.ident() == Some("of") && !t.escaped);
let mark = self.cover_inits.len();
self.cover_ok = self.es2015;
let expr = self.parse_expression(true)?;
if self.at_of() {
if starts_with_let {
return Err(self.error_at_offset(self.ast.expr_span(expr).start, "a for-of loop's left-hand side cannot start with 'let'"));
}
// `for (async of …` is left to async arrow functions (ECMA-262 2017 section 13.7).
if async_of {
return Err(self.error_at_offset(self.ast.expr_span(expr).start, "a for-of loop's left-hand side cannot be 'async'"));
}
self.loop_target(expr, "invalid left-hand side in for-of loop", true)?;
self.check_cover(mark)?;
return self.parse_for_of(ForInTarget::Expr(expr), start);
}
if self.at_keyword(Keyword::In) {
self.check_target(expr, "invalid left-hand side in for-in loop")?;
self.loop_target(expr, "invalid left-hand side in for-in loop", false)?;
self.check_cover(mark)?;
return self.parse_for_in(ForInTarget::Expr(expr), start, false);
}
self.check_cover(mark)?;
Some(ForInit::Expr(expr))
};
self.parse_for_rest(init, start)
@@ -724,12 +790,15 @@ impl<'s> Parser<'s> {
/// `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<StmtId> {
let mut decls = self.parse_lexical_decls(kind, true)?;
if decls.len() == 1 && self.at_keyword(Keyword::In) {
if decls.len() == 1 && (self.at_keyword(Keyword::In) || self.at_of()) {
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 Err(self.error_at_token(&self.tok, "a loop variable declared with let or const cannot have an initializer here"));
}
return self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, false);
if self.at_of() {
return self.parse_for_of(ForInTarget::Lexical(kind, decl.target), start);
}
return self.parse_for_in(ForInTarget::Lexical(kind, decl.target), start, false);
}
self.parse_for_rest(Some(ForInit::Lexical(kind, decls)), start)
}
@@ -773,9 +842,9 @@ impl<'s> Parser<'s> {
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"));
return Err(self.error_at_token(&self.tok, "a loop variable declared with let or const cannot have an initializer here"));
}
self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, true)
self.parse_for_in(ForInTarget::Lexical(kind, decl.target), start, true)
}
/// `break` or `continue`, with an optional label on the same line, which must name a label
@@ -900,12 +969,9 @@ 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()?;
let param = self.parse_declaration_target()?;
self.expect(Punct::RParen)?;
let body = self.parse_block_with(Some(&param.name))?;
let body = self.parse_block_with(Some(&param))?;
Some(CatchClause { param, body })
} else {
None
@@ -987,20 +1053,20 @@ impl<'s> Parser<'s> {
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result<crate::ast::FunctionId> {
self.expect(Punct::LParen)?;
let mut params: Vec<Name> = Vec::new();
let mut params: Vec<Binding> = Vec::new();
let mut defaults: Vec<Option<ExprId>> = Vec::new();
let mut rest = None;
if !self.at(Punct::RParen) {
loop {
if self.es2015 && self.at(Punct::Ellipsis) {
self.bump()?;
rest = Some(self.function_name_or_param()?.0);
rest = Some(self.parse_param_target()?);
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 param = self.parse_param_target()?;
let default = if self.es2015 && self.eat(Punct::Eq)? { Some(self.parse_assignment(false)?) } else { None };
params.push(param);
defaults.push(default);
@@ -1023,7 +1089,7 @@ impl<'s> Parser<'s> {
defaults.clear();
}
self.expect(Punct::LBrace)?;
let names: Vec<String> = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
let outer_strict = self.ctx.strict;
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
@@ -1046,7 +1112,7 @@ impl<'s> Parser<'s> {
}
self.expect(Punct::Arrow)?;
self.enter()?;
let names: Vec<String> = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
let outer_strict = self.ctx.strict;
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
@@ -1073,32 +1139,28 @@ impl<'s> Parser<'s> {
}
/// 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<Params> {
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)) };
/// 14.2.1): names or patterns, each with an optional `= default`, and a last `...name` or
/// `...[pattern]`.
fn arrow_params(&mut self, expr: ExprId) -> Result<Params> {
let invalid = |p: &Self, at: ExprId| p.error_at_offset(p.ast.expr_span(at).start, "invalid arrow function parameters");
let Some(Expr::Paren(inner)) = self.ast.expr(expr) else { return Err(invalid(self, 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))?);
match self.ast.expr(item).cloned() {
Some(Expr::Assign { op: None, target, value }) => {
params.push(self.arrow_param(target).ok_or_else(|| invalid(self, item))??);
defaults.push(Some(value));
}
Some(Expr::Spread(arg)) if i + 1 == count => rest = Some(self.arrow_param(arg).ok_or_else(|| invalid(self, item))??),
_ => {
params.push(self.arrow_param(item).ok_or_else(|| invalid(self, 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))
@@ -1121,11 +1183,12 @@ impl<'s> Parser<'s> {
/// 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 names: Vec<Name> = function.params.iter().chain(&function.rest).flat_map(|p| self.ast.bound_names(p)).collect();
let params = || names.iter();
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"));
return Err(self.error_at_offset(at, "\"use strict\" is not allowed in a function with default, rest or destructured parameters"));
}
if function.strict {
for n in function.name.iter().chain(params()) {
@@ -1171,10 +1234,16 @@ impl<'s> Parser<'s> {
}
fn parse_assignment(&mut self, no_in: bool) -> Result<ExprId> {
let cover_ok = std::mem::take(&mut self.cover_ok);
let mark = self.cover_inits.len();
self.enter()?;
let result = self.assignment(no_in);
self.leave();
result
let expr = result?;
if !cover_ok {
self.check_cover(mark)?;
}
Ok(expr)
}
/// `a = b += c`: the targets kept on a stack, so a long chain does not nest.
@@ -1193,7 +1262,11 @@ impl<'s> Parser<'s> {
}
return Ok(value);
};
self.check_target(expr, "invalid assignment target")?;
if op.is_none() && self.es2015 && matches!(self.ast.expr(expr), Some(Expr::Array(_) | Expr::Object(_))) {
self.check_assignment_pattern(expr)?;
} else {
self.check_target(expr, "invalid assignment target")?;
}
self.bump()?;
targets.push((expr, op));
}
@@ -1204,7 +1277,7 @@ impl<'s> Parser<'s> {
fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result<ExprId> {
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::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None),
Some(Expr::Paren(_)) => self.arrow_params(expr)?,
_ => return Err(self.unexpected()),
};
@@ -1465,15 +1538,16 @@ impl<'s> Parser<'s> {
let start = self.expect(Punct::LParen)?.span;
let mut items = Vec::new();
let mut head_only = self.at(Punct::RParen);
let mark = self.cover_inits.len();
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);
let arg = self.binding_target_expr()?;
items.push(self.ast.push_expr(Expr::Spread(arg), self.span_from(spread_start)));
head_only = true;
break;
}
self.cover_ok = true;
items.push(self.parse_assignment(false)?);
if !self.eat(Punct::Comma)? {
break;
@@ -1486,6 +1560,9 @@ impl<'s> Parser<'s> {
if head_only && !self.at(Punct::Arrow) {
return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok))));
}
if !self.at(Punct::Arrow) {
self.check_cover(mark)?;
}
let inner = match items.as_slice() {
[one] => *one,
_ => {
@@ -1540,9 +1617,14 @@ impl<'s> Parser<'s> {
elements.push(None);
continue;
}
elements.push(Some(self.parse_element()?));
self.cover_ok = self.es2015;
let element = self.parse_element()?;
elements.push(Some(element));
if !self.at(Punct::RBracket) {
self.expect(Punct::Comma)?;
if matches!(self.ast.expr(element), Some(Expr::Spread(_))) {
self.rest_commas.insert(element.0);
}
}
}
Ok(self.ast.push_expr(Expr::Array(elements), self.span_from(start)))
@@ -1554,7 +1636,7 @@ impl<'s> Parser<'s> {
let start = self.expect(Punct::LBrace)?.span;
let mut properties = Vec::new();
while !self.eat(Punct::RBrace)? {
let property = self.parse_property()?;
let property = if self.es2015 { self.parse_property_es2015()? } else { self.parse_property()? };
properties.push(property);
if !self.at(Punct::RBrace) {
self.expect(Punct::Comma)?;
+362
View File
@@ -0,0 +1,362 @@
//! `for (… of …)` and destructuring with [`crate::Options::es2015`] (ECMA-262 11th edition,
//! <https://262.ecma-international.org/11.0/>): binding patterns in declarations, parameters and
//! catch clauses (section 13.3.3), assignment patterns read from array and object literals
//! (section 12.15.5), and the shorthand, computed and `name = default` properties an object
//! literal takes while it may still turn out to be a pattern (section 12.2.6).
//!
//! A pattern is kept as the array or object expression it looks like (see [`Binding`]). A binding
//! pattern is read as one; an assignment pattern is read as a literal and checked when an `=` or a
//! loop head shows that it is a pattern.
use super::{Parser, Result, describe, property_key};
use crate::ast::{Binding, Expr, ExprId, ForInTarget, FunctionKind, Name, Property, PropertyKey, PropertyValue, Stmt, StmtId, VarDecl};
use crate::token::{Punct, Span, TokenKind};
impl Parser<'_> {
/// The current token is `of` written without escapes, in a loop head.
pub(super) fn at_of(&self) -> bool {
self.es2015 && self.tok.ident() == Some("of") && !self.tok.escaped
}
/// A shorthand property with an initializer (`{a = 1}`) read since `mark` that no pattern
/// took is a `SyntaxError`.
pub(super) fn check_cover(&self, mark: usize) -> Result<()> {
match self.cover_inits.get(mark) {
Some(&at) => Err(self.error_at_offset(at, "a shorthand property cannot have an initializer outside a destructuring pattern")),
None => Ok(()),
}
}
/// The name or pattern a `var`, `let`, `const` or catch clause declares.
pub(super) fn parse_declaration_target(&mut self) -> Result<Binding> {
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
return Ok(Binding::Pattern(self.parse_binding_pattern()?));
}
Ok(Binding::Name(self.binding_identifier()?))
}
/// A parameter's name or pattern; a name's strict-mode checks wait for the body.
pub(super) fn parse_param_target(&mut self) -> Result<Binding> {
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
return Ok(Binding::Pattern(self.parse_binding_pattern()?));
}
Ok(Binding::Name(self.function_name_or_param()?.0))
}
/// `[…]` or `{…}`: a binding pattern, each nested pattern counted as one more level of
/// nesting.
pub(super) fn parse_binding_pattern(&mut self) -> Result<ExprId> {
self.enter()?;
let result = if self.at(Punct::LBracket) { self.binding_array() } else { self.binding_object() };
self.leave();
result
}
/// `[a, , [b], c = 1, ...d]`: a comma with nothing before it skips a value, and a rest element
/// comes last, without a comma after it.
fn binding_array(&mut self) -> Result<ExprId> {
let start = self.expect(Punct::LBracket)?.span;
let mut elements = Vec::new();
loop {
if self.eat(Punct::RBracket)? {
break;
}
if self.eat(Punct::Comma)? {
elements.push(None);
continue;
}
if self.at(Punct::Ellipsis) {
let rest_start = self.bump()?.span;
let target = self.binding_target_expr()?;
elements.push(Some(self.ast.push_expr(Expr::Spread(target), self.span_from(rest_start))));
if !self.at(Punct::RBracket) {
return Err(self.error_at_token(&self.tok, "a rest element must be the last element of a pattern"));
}
continue;
}
elements.push(Some(self.binding_element()?));
if !self.at(Punct::RBracket) {
self.expect(Punct::Comma)?;
}
}
Ok(self.ast.push_expr(Expr::Array(elements), self.span_from(start)))
}
/// `{a, b = 1, c: d, "e": [f], [g]: h = 2}`.
fn binding_object(&mut self) -> Result<ExprId> {
let start = self.expect(Punct::LBrace)?.span;
let mut properties = Vec::new();
while !self.eat(Punct::RBrace)? {
let property_start = self.tok.span;
let shorthand = matches!(self.tok.kind, TokenKind::Ident(_)) && !self.peek().is_some_and(|t| t.is_punct(Punct::Colon));
let (key, value) = if shorthand {
let name = self.binding_identifier()?;
let target = self.ast.push_expr(Expr::Ident(name.name.clone()), name.span);
(PropertyKey::Ident(name.name), self.binding_default(target)?)
} else {
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
self.expect(Punct::Colon)?;
(key, self.binding_element()?)
};
properties.push(Property { key, value: PropertyValue::Init(value), span: self.span_from(property_start) });
if !self.at(Punct::RBrace) {
self.expect(Punct::Comma)?;
}
}
Ok(self.ast.push_expr(Expr::Object(properties), self.span_from(start)))
}
/// A name or a nested pattern, as a pattern's target.
pub(super) fn binding_target_expr(&mut self) -> Result<ExprId> {
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
return self.parse_binding_pattern();
}
let name = self.binding_identifier()?;
Ok(self.ast.push_expr(Expr::Ident(name.name), name.span))
}
/// A pattern's target with its optional default value.
fn binding_element(&mut self) -> Result<ExprId> {
let target = self.binding_target_expr()?;
self.binding_default(target)
}
/// `= value` after a target, kept as an assignment whose target is the target.
fn binding_default(&mut self, target: ExprId) -> Result<ExprId> {
if !self.eat(Punct::Eq)? {
return Ok(target);
}
let value = self.parse_assignment(false)?;
let span = self.ast.expr_span(target).to(self.ast.expr_span(value));
Ok(self.ast.push_expr(Expr::Assign { op: None, target, value }, span))
}
/// `[expression]` as a property name.
fn computed_key(&mut self) -> Result<PropertyKey> {
self.expect(Punct::LBracket)?;
let key = self.parse_assignment(false)?;
self.expect(Punct::RBracket)?;
Ok(PropertyKey::Computed(key))
}
/// A property of an object literal with [`crate::Options::es2015`]: what ECMAScript 5.1 reads,
/// a computed name (`[k]: v`, `get [k]() {}`), a shorthand name (`a`, the value of `a`), and a
/// shorthand name with an initializer (`a = 1`), which only a pattern may hold.
pub(super) fn parse_property_es2015(&mut self) -> Result<Property> {
let start = self.tok.span;
// `get` and `set` start an accessor only when written without escapes and followed by a
// property name.
let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) {
Some("get") => Some(FunctionKind::Getter),
Some("set") => Some(FunctionKind::Setter),
_ => None,
};
if let Some(kind) = accessor
&& self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket))
{
self.bump()?;
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
let function = self.parse_function_rest(kind, None, start)?;
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
return Ok(Property { key, value, span: self.span_from(start) });
}
if self.at(Punct::LBracket) {
let key = self.computed_key()?;
return self.cover_property_value(key, start);
}
if let TokenKind::Ident(name) = &self.tok.kind
&& self.peek().is_some_and(|t| t.is_punct(Punct::Comma) || t.is_punct(Punct::RBrace) || t.is_punct(Punct::Eq))
{
let name = name.clone();
self.check_identifier(&self.tok, &name)?;
let token = self.bump()?;
let target = self.ast.push_expr(Expr::Ident(name.clone()), token.span);
let value = if self.at(Punct::Eq) {
self.cover_inits.push(self.tok.span.start);
self.bump()?;
let init = self.parse_assignment(false)?;
let span = token.span.to(self.ast.expr_span(init));
self.ast.push_expr(Expr::Assign { op: None, target, value: init }, span)
} else {
target
};
return Ok(Property { key: PropertyKey::Ident(name), value: PropertyValue::Init(value), span: self.span_from(start) });
}
let (key, _) = self.parse_property_key()?;
self.cover_property_value(key, start)
}
/// `: value` after a property name; the value may still turn out to be a pattern.
fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result<Property> {
self.expect(Punct::Colon)?;
self.cover_ok = true;
let value = self.parse_assignment(false)?;
Ok(Property { key, value: PropertyValue::Init(value), span: self.span_from(start) })
}
/// An assignment's, `++`'s or `--`'s target without the call that ECMAScript 5.1 code may
/// assign to: an identifier (in strict code neither `eval` nor `arguments`), a property or an
/// E4X name standing alone.
fn check_simple_target(&self, expr: ExprId, message: &str) -> Result<()> {
let inner = self.ast.unparenthesized(expr);
match self.ast.expr(inner) {
Some(Expr::Ident(name)) => {
if self.ctx.strict && super::is_eval_or_arguments(name) {
return Err(self.error_at_offset(self.ast.expr_span(inner).start, format!("cannot assign to '{name}' in strict mode")));
}
Ok(())
}
Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_)) => Ok(()),
_ => Err(self.error_at_offset(self.ast.expr_span(expr).start, message)),
}
}
/// A `for-in` or `for-of` loop's target expression: an assignment pattern, or a target that
/// an assignment takes (without a call in a `for-of` loop).
pub(super) fn loop_target(&mut self, expr: ExprId, message: &str, of: bool) -> Result<()> {
if self.es2015 && matches!(self.ast.expr(expr), Some(Expr::Array(_) | Expr::Object(_))) {
return self.check_assignment_pattern(expr);
}
if of { self.check_simple_target(expr, message) } else { self.check_target(expr, message) }
}
/// The targets of the elements and property values of the pattern `id`, each with its default
/// value taken off. A rest element that is not last or has a comma after it, and a getter or
/// a setter, are errors.
fn pattern_targets(&self, id: ExprId) -> Result<Vec<ExprId>> {
let mut out = Vec::new();
match self.ast.expr(id) {
Some(Expr::Array(elements)) => {
let count = elements.len();
for (i, el) in elements.iter().enumerate() {
let Some(el) = *el else { continue };
if let Some(Expr::Spread(arg)) = self.ast.expr(el) {
if i + 1 != count || self.rest_commas.contains(&el.0) {
return Err(self.error_at_offset(self.ast.expr_span(el).start, "a rest element must be the last element of a pattern"));
}
out.push(*arg);
} else {
out.push(self.without_default(el));
}
}
}
Some(Expr::Object(properties)) => {
for p in properties {
match p.value {
PropertyValue::Init(v) => out.push(self.without_default(v)),
_ => return Err(self.error_at_offset(p.span.start, "a getter or setter cannot be a destructuring target")),
}
}
}
_ => return Err(self.error_at_offset(self.ast.expr_span(id).start, "invalid destructuring pattern")),
}
Ok(out)
}
/// An element's target: the target of `target = default`, or the element itself.
fn without_default(&self, el: ExprId) -> ExprId {
match self.ast.expr(el) {
Some(Expr::Assign { op: None, target, .. }) => *target,
_ => el,
}
}
fn is_pattern(&self, id: ExprId) -> bool {
matches!(self.ast.expr(id), Some(Expr::Array(_) | Expr::Object(_)))
}
/// Checks that the array or object literal `pattern` is an assignment pattern (ECMA-262 11th
/// edition, section 12.15.5.1): each target is a nested pattern or one that an assignment
/// takes, a parenthesized pattern is not a target, and the shorthand properties with an
/// initializer in it are no longer errors.
pub(super) fn check_assignment_pattern(&mut self, pattern: ExprId) -> Result<()> {
let mut work = vec![pattern];
while let Some(id) = work.pop() {
for target in self.pattern_targets(id)? {
if self.is_pattern(target) {
work.push(target);
} else {
self.check_simple_target(target, "invalid destructuring target")?;
}
}
self.take_covers(id);
}
Ok(())
}
/// Checks that the array or object literal `pattern`, read as an arrow function's parameter,
/// is a binding pattern: each target is a name written bare or a nested pattern.
fn check_binding_pattern(&mut self, pattern: ExprId) -> Result<()> {
let mut work = vec![pattern];
while let Some(id) = work.pop() {
for target in self.pattern_targets(id)? {
match self.ast.expr(target) {
Some(Expr::Ident(_)) => {}
Some(Expr::Array(_) | Expr::Object(_)) => work.push(target),
_ => return Err(self.error_at_offset(self.ast.expr_span(target).start, "invalid arrow function parameters")),
}
}
self.take_covers(id);
}
Ok(())
}
/// Forgets the shorthand properties with an initializer that the object pattern `id` holds
/// itself: each one's `=` lies between its target and its default value. One inside a default
/// value or a computed name stays an error.
fn take_covers(&mut self, id: ExprId) {
let Some(Expr::Object(properties)) = self.ast.expr(id) else { return };
let mut gaps = Vec::new();
for p in properties {
if let PropertyValue::Init(v) = p.value
&& let Some(Expr::Assign { op: None, target, value }) = self.ast.expr(v)
{
gaps.push((self.ast.expr_span(*target).end, self.ast.expr_span(*value).start));
}
}
self.cover_inits.retain(|&at| !gaps.iter().any(|&(from, to)| from <= at && at < to));
}
/// An arrow function's parameter from its parenthesized head: `None` when `item` is neither a
/// name nor a pattern.
pub(super) fn arrow_param(&mut self, item: ExprId) -> Option<Result<Binding>> {
match self.ast.expr(item) {
Some(Expr::Ident(name)) => Some(Ok(Binding::Name(Name { name: name.clone(), span: self.ast.expr_span(item) }))),
Some(Expr::Array(_) | Expr::Object(_)) => Some(self.check_binding_pattern(item).map(|()| Binding::Pattern(item))),
_ => None,
}
}
/// `for (var … of …)`, from `of`: the variable takes no initializer, and no catch clause
/// around the loop in the same function has a parameter of the same name (ECMA-262 2015
/// Annex B.3.5).
pub(super) fn parse_for_of_var(&mut self, decl: VarDecl, start: Span) -> Result<StmtId> {
if decl.init.is_some() {
return Err(self.error_at_token(&self.tok, "a for-of variable cannot have an initializer"));
}
for name in self.ast.bound_names(&decl.target) {
for scope in self.scopes.iter().rev() {
if !scope.function && scope.params.contains(&name.name) {
return Err(self.redeclared(&name));
}
if scope.function {
break;
}
}
}
self.parse_for_of(ForInTarget::Var(decl), start)
}
/// The rest of `for (target of iterable) body`, from `of`; the iterable is an assignment
/// expression.
pub(super) fn parse_for_of(&mut self, target: ForInTarget, start: Span) -> Result<StmtId> {
if !self.at_of() {
return Err(self.error_at_token(&self.tok, format!("expected 'of' but found {}", describe(&self.tok))));
}
self.bump()?;
let iterable = self.parse_assignment(false)?;
self.expect(Punct::RParen)?;
let body = self.parse_loop_body()?;
Ok(self.ast.push_stmt(Stmt::ForOf { target, iterable, body }, self.span_from(start)))
}
}
+14 -6
View File
@@ -1,10 +1,18 @@
use proptest::prelude::*;
use crate::{
BinaryOp, Expr, ExprId, ForInTarget, FunctionKind, Options, Program, PropertyValue, Stmt, StmtId, SyntaxError, TOO_DEEP, TokenKind, parse,
tokenize,
BinaryOp, Binding, Expr, ExprId, ForInTarget, FunctionKind, Options, Program, PropertyValue, Stmt, StmtId, SyntaxError, TOO_DEEP, TokenKind,
VarDecl, parse, tokenize,
};
/// The name a declaration binds; a pattern fails the test.
fn decl_name(d: &VarDecl) -> &str {
match &d.target {
Binding::Name(n) => &n.name,
Binding::Pattern(_) => panic!("a pattern where a name was expected"),
}
}
fn ok(src: &str) -> Program {
match parse(src, &Options::default()) {
Ok(p) => p,
@@ -364,7 +372,7 @@ fn string_literals_and_escapes() {
fn identifiers_with_unicode_and_escapes() {
let p = ok("var caf\\u00e9 = 1, \u{3b1}\u{3b2} = 2, $_x1 = 3, a\u{300} = 4;");
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!() };
let names: Vec<&str> = decls.iter().map(|d| d.name.name.as_str()).collect();
let names: Vec<&str> = decls.iter().map(decl_name).collect();
assert_eq!(names, ["caf\u{e9}", "\u{3b1}\u{3b2}", "$_x1", "a\u{300}"]);
let p = ok("\\u{61}b;");
assert!(matches!(expr(&p, first_expr(&p)), Expr::Ident(n) if n == "ab"));
@@ -409,7 +417,7 @@ fn identifiers_take_the_other_id_start_and_continue_characters() {
for src in [format!("var {ch} = 1;"), format!("var a{ch} = 1;"), format!("var \\u{c:04X}\\u{{{c:X}}} = 1;")] {
let p = ok(&src);
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") };
assert!(decls[0].name.name.contains(ch), "{src:?}");
assert!(decl_name(&decls[0]).contains(ch), "{src:?}");
}
}
// Other_ID_Continue: may follow the first character, but cannot start a name.
@@ -438,7 +446,7 @@ fn identifiers_take_the_characters_unicode_17_assigned() {
] {
let p = ok(src);
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") };
assert_eq!(decls[0].name.name, name, "{src:?}");
assert_eq!(decl_name(&decls[0]), name, "{src:?}");
}
assert!(err("var \u{1ACF} = 1;").message.contains("unexpected character"));
assert!(err("var \\u1ACF = 1;").message.contains("identifier escape"));
@@ -462,7 +470,7 @@ fn identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes() {
// A supplementary letter is one identifier character, at the start and after a number.
let p = ok("var \u{10000}\u{1D7CE} = 1;");
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!() };
assert_eq!(decls[0].name.name, "\u{10000}\u{1D7CE}");
assert_eq!(decl_name(&decls[0]), "\u{10000}\u{1D7CE}");
assert!(err("1\u{10000};").message.contains("immediately after numeric literal"));
}
+113
View File
@@ -44,6 +44,11 @@
//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and
//! that parse as ES5. Its failures go to `symbol-failures.txt`.
//!
//! The last test reads the tests of `for-of` and destructuring (the folders
//! [`FOR_OF_AND_PATTERN_FOLDERS`] names) with [`Options::es2015`]: tests of any edition whose
//! feature tags are all in [`FOR_OF_AND_PATTERN_FEATURES`]. Negative parse tests must give a
//! `SyntaxError`; the others run as the Symbol tests run. Its failures go to `for-of-failures.txt`.
//!
//! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses
//! an `includes:` name that leaves the `harness/` folder, and refuses a file over
//! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test.
@@ -915,6 +920,114 @@ fn run_symbol_built_ins(dir: &Path) {
assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display());
}
/// The folders of the tests of `for-of` and destructuring, which are read in a realm with
/// [`Options::es2015`].
const FOR_OF_AND_PATTERN_FOLDERS: &[&str] = &[
"language/statements/for-of",
"language/expressions/assignment/destructuring",
"language/expressions/assignment/dstr",
"language/statements/variable/dstr",
"language/statements/let/dstr",
"language/statements/const/dstr",
"language/statements/function/dstr",
"language/expressions/function/dstr",
"language/expressions/arrow-function/dstr",
"language/statements/try/dstr",
"language/statements/for/dstr",
"language/statements/for-in/dstr",
];
/// The feature tags of the tests under [`FOR_OF_AND_PATTERN_FOLDERS`] that are read; a test with
/// any other tag is skipped.
const FOR_OF_AND_PATTERN_FEATURES: &[&str] = &[
"let",
"const",
"arrow-function",
"template",
"default-parameters",
"rest-parameters",
"destructuring-binding",
"destructuring-assignment",
"computed-property-names",
"Symbol",
"Symbol.iterator",
];
#[test]
fn es2015_for_of_and_destructuring_run() {
let Some(dir) = suite_dir() else {
println!("test262 for-of and destructuring: SKIPPED (no suite; run cargo xtask test262)");
return;
};
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_for_of_and_patterns(&dir)).unwrap();
handle.join().unwrap();
}
/// Reads the tests under each folder [`FOR_OF_AND_PATTERN_FOLDERS`] names whose feature tags are
/// all in [`FOR_OF_AND_PATTERN_FEATURES`] with [`Options::es2015`]: a negative parse test must give
/// a `SyntaxError`, and the others run as [`run_tagged_tests`] runs them. Prints the counts of each
/// folder and writes the failures to `for-of-failures.txt` beside the suite.
fn run_for_of_and_patterns(dir: &Path) {
let options = Options { es2015: true, ..Options::default() };
let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]);
let mut all = RunCounts::default();
let mut report = String::new();
for folder in FOR_OF_AND_PATTERN_FOLDERS {
let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else {
println!("test262 {folder}: SKIPPED (not in this suite)");
continue;
};
let mut counts = run_parse_negatives(dir, &root, &options, FOR_OF_AND_PATTERN_FEATURES);
counts.add(run_tagged_tests(dir, &root, &missing, &options, FOR_OF_AND_PATTERN_FEATURES));
println!("test262 {folder} with Options::es2015: {}.", counts.summary());
report.push_str(&format!("# {folder}\n{}\n", counts.failures));
all.add(counts);
}
assert!(all.tests > 0, "no for-of or destructuring tests ran under {}", dir.display());
let path = dir.join("for-of-failures.txt");
if let Err(e) = std::fs::write(&path, &report) {
println!("could not write {}: {e}", path.display());
}
println!("test262 for-of and destructuring with Options::es2015: {}. Failures: {}", all.summary(), path.display());
assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display());
}
/// Parses the negative parse tests under `root` whose feature tags are all in `features`, in
/// each mode the test names, with `options`; each must give a `SyntaxError`.
fn run_parse_negatives(dir: &Path, root: &Path, options: &Options, features: &[&str]) -> RunCounts {
let mut counts = RunCounts::default();
for path in or_fail(test_files(root)) {
let source = or_fail(read_source(&path));
let meta = meta(&source);
if meta.flags.iter().any(|f| f == "module") || meta.negative_phase.as_deref() != Some("parse") {
continue;
}
if meta.features.iter().any(|f| !features.contains(&f.as_str())) {
counts.skipped += 1;
continue;
}
counts.tests += 1;
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
for &strict in modes(&meta) {
let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() };
match std::panic::catch_unwind(|| parse(&text, options).is_err()) {
Ok(true) => counts.passed += 1,
Ok(false) => {
counts.failed += 1;
let mode = if strict { "strict" } else { "sloppy" };
counts.failures.push_str(&format!("{rel} ({mode}): parsed; a SyntaxError was expected\n"));
}
Err(_) => {
counts.failed += 1;
counts.panicked += 1;
counts.failures.push_str(&format!("{rel}: PANIC\n"));
}
}
}
}
counts
}
/// Runs the script tests under `root` of any edition whose feature tags are all in `features`,
/// each in a new realm made with `options` after the harness, the way [`run_tests`] runs the
/// others. A test with another tag is counted as skipped.
+13 -6
View File
@@ -2620,9 +2620,14 @@ not UTF-8. The language is ES5.1, except that identifiers take the characters Un
`.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
parameters, spread in array literals, calls and `new`, `for`-`of` loops, array and object destructuring in `var`,
`let` and `const` declarations, assignments, parameters and `catch` clauses (with defaults, holes and rest elements),
and shorthand and computed property names in object literals (https://262.ecma-international.org/11.0/). Spread,
`for`-`of` and array patterns use the iterator protocol, and a loop or pattern left early calls the iterator's
`return` method. Destructuring `undefined` or `null` throws a `TypeError`. Object rest properties
(`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In an engine that `#targetengine` keeps and a `.jsx` script
started, which has no `Symbol`, spread, `for`-`of` and array patterns read arrays, `arguments` objects and strings
(by code point), by index, and throw a `TypeError` for any other value; that rule is VectorCraft's own. `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 `$`:
@@ -2652,9 +2657,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot
- `vc.args` gives a read-only copy of the `args` object each time it is read.
- `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature.
A script does not have `Symbol` or the iterators of arrays, strings and `arguments` objects: `typeof Symbol` is
`"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. The JavaScript engine's ECMAScript
2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes.
A `.jsx` script and a `source` string do not have `Symbol` or the iterators of arrays, strings and `arguments`
objects: `typeof Symbol` is `"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. A `.js`
script that starts a new engine has them, through the JavaScript engine's ECMAScript 2015 mode (`Options::es2015` in
`vectorcraft-js`), as `docs/target-app-parity.md` describes; an engine that `#targetengine` keeps has them only when a
`.js` script started it.
Before any of the script runs, its preprocessor lines are read. The help page
https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and
+3 -2
View File
@@ -1079,11 +1079,12 @@ 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, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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 uses the iterator protocol (see the `for`-`of` line below). 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. 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 565 of 589 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, ECMAScript 2015 rules that `vectorcraft-js` does not implement. 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`.
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs `.jsx` scripts in, has none of these names. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator that threw, or whose `next()` said it was done, is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: 609 of 617 runs pass (529 before, most of them negative parse tests); the 8 others expect a function given as a default to take the name of its binding, a `name` property `vectorcraft-js` does not set. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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 <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`.
- With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`.
- `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `<!DOCTYPE>` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`.