diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..eb8f43cc41 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -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); } diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..9dbf58f33e 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -80,15 +80,19 @@ pub enum PropertyKey { Ident(String), String(Vec), 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 { 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, } -/// 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, } @@ -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), @@ -384,11 +407,11 @@ pub struct Function { pub kind: FunctionKind, pub name: Option, /// The parameters before a rest parameter. - pub params: Vec, + pub params: Vec, /// Each parameter's default value, in the order of `params` (empty when none has one). pub defaults: Vec>, - /// The rest parameter (`...name`). - pub rest: Option, + /// The rest parameter (`...name` or `...[pattern]`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -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 { + 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 { + 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) { diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..a8d8471a4c 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -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, } impl Code { @@ -380,7 +404,13 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { 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), }) } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..3321475da6 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -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, is_loop: bool, plain_break: bool, brk: Label, cont: Option