diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index c12653602f..9489921682 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -393,6 +393,33 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("generators"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let source = "function* ids(n) { for (let i = 0; i < n; i++) yield `id${i}`; }\n\ + function* all() { yield* ids(2); yield* [vc.document ? 'doc' : 'none']; return 'end'; }\n\ + const it = all(); let s;\nwhile (!(s = it.next()).done) vc.log(s.value);\nvc.log(s.value);\n"; + let r = s.execute("script.run", &path(&write("gen.js", source))).unwrap(); + assert_eq!(r["log"], json!(["id0", "id1", "doc", "end"]), "{r}"); + let e = s.execute("script.run", &path(&write("gen.jsx", "function* g() {}"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + // `yield` stays a name in a `.jsx` script. + let r = s.execute("script.run", &path(&write("name.jsx", "var yield = 4; vc.log(yield);"))).unwrap(); + assert_eq!(r["log"], json!([4]), "{r}"); + // An engine a `.jsx` run made has no generator built-ins for a later `.js` run. + s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); + let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); + assert!(e.contains("TypeError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn every_script_reads_e4x_and_has_the_xml_objects() { let dir = fresh_folder("e4x"); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index e255258f34..8efa1458eb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -244,6 +244,12 @@ pub enum Expr { OptionalChain(ExprId), /// The object or function before `?.` in an [`Expr::OptionalChain`]. Optional(ExprId), + /// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's + /// body (ECMA-262 2015 section 14.4). + Yield { + arg: Option, + delegate: bool, + }, } /// A piece of a template literal's text between its substitutions. @@ -440,6 +446,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// A generator function (`function*`, or `*name() {…}` in an object literal). + pub generator: bool, pub span: Span, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 86b31414b3..3baad7b7bd 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,8 +3,9 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and //! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and -//! the iterators of arrays, strings and `arguments` objects (in `iterator`). +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`), +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,6 +13,7 @@ mod array; pub(crate) mod extensions; +mod generator; mod global; pub(crate) mod iterator; mod json; @@ -261,6 +263,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.es2015 { symbol::install(interp, object)?; iterator::install(interp)?; + generator::install(interp, function)?; } if interp.options.e4x { crate::xml_builtins::install(interp)?; @@ -471,7 +474,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value { } fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Err(Abrupt::Internal("call or apply reached its native body".into())) + Err(Abrupt::Internal("a built-in the interpreter runs itself reached its native body".into())) } fn throw_type_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { @@ -610,7 +613,13 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + create_dynamic_function(interp, args, false) +} + +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with +/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { + let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -622,12 +631,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -647,8 +656,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe }; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { - Ok(Some(code)) => code, - Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), + Ok(Some(code)) if code.generator == generator => code, + Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)), Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; @@ -687,6 +696,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) }; let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); + // With ECMAScript 2015 the bound function inherits from the target's prototype, read before + // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function + // inherits from %GeneratorFunction.prototype%. + let target_proto = interp.heap.object(target).and_then(|o| o.proto); // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. @@ -700,7 +713,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; if interp.options.es2015 { - return bind_es2015(interp, target, bound_this, bound_args, length); + return bind_es2015(interp, target, target_proto, bound_this, bound_args, length); } interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; @@ -722,9 +735,10 @@ fn prop_bytes(names: &[&str]) -> usize { /// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section /// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the -/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps -/// the `caller` and `arguments` that throw, as without the option. -fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { +/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its +/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as +/// without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { Value::String(s) => s, _ => Str::from(""), @@ -740,9 +754,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args crate::string_builtins::charge_units(interp, name_len)?; let mut units: Vec = "bound ".encode_utf16().collect(); units.extend_from_slice(&target_units); - let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); - let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + let f = interp.heap.alloc_object(Object::new(class, proto)); interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs new file mode 100644 index 0000000000..c8e46e09d6 --- /dev/null +++ b/crates/js/src/builtins/generator.rs @@ -0,0 +1,51 @@ +//! The generator built-ins (ECMA-262 11th edition, ): +//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and +//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits +//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the +//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator +//! function's `constructor`. + +use super::{data, native, unreachable_native}; +use crate::generator::ResumeMode; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { + let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) }; + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto); + + let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] { + let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?; + data(interp, generator_proto, name, Value::Object(m), HIDDEN)?; + } + interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?; + + let function_proto = interp.intrinsics.function_proto; + // %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from + // Function.prototype (section 25.2.3). + let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?; + data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?; + interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?; + + let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(generator_function) { + o.proto = Some(function); + } + data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?; + data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?; + + objects.generator_proto = generator_proto; + objects.generator_function_proto = generator_function_proto; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). +fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + super::create_dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs index b40f979fc0..d7d5a8192a 100644 --- a/crates/js/src/builtins/iterator.rs +++ b/crates/js/src/builtins/iterator.rs @@ -84,7 +84,7 @@ fn iter_result_bytes() -> usize { } /// CreateIterResultObject (section 7.4.7): `{ value, done }`. -fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?; let proto = interp.intrinsics.object_proto; let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 06bd175fca..6667de7a8f 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -928,8 +928,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -938,7 +938,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { code, .. } => return Ok(!code.arrow && !code.method), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..109493a03d 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; - // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + // The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators + // and generators are installed. interp.symbols.objects = Some(Es2015Objects { symbol_proto: proto, array_iterator_proto: proto, string_iterator_proto: proto, array_values: has_instance, has_instance, + generator_proto: proto, + generator_function_proto: function_proto, }); Ok(()) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 2671959b17..5a44e6385a 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -246,6 +246,30 @@ pub(crate) enum Op { InitIndex, /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. InitAccessorIndex(bool), + /// Ends a generator function's call once its parameters are initialized: the frame becomes a + /// new generator object, which the call returns. The first `next` goes on after it. + GeneratorStart, + /// `value` → `received mode`: suspends the generator, giving its caller `{ value, done: false }` + /// (or, when true, the value itself, an iterator result from `yield*`'s delegate). It goes on + /// when the generator is resumed, with the value it was resumed with and how (0 `next`, 1 + /// `throw`, 2 `return`). + Yield(bool), + /// `received mode` → `received`: goes on for `next`, throws the value for `throw`, and jumps + /// with it for `return`. + Resume(u32), + /// `value` → `iterator next`: GetIterator (ECMA-262 11th edition, section 7.4.1) for `yield*`, + /// which calls the iterator's methods itself. + DelegateIterator, + /// `iterator next received mode` → `iterator next mode method iterator received`, ready for + /// `Call(1)`: the delegate's `next`, `throw` or `return`. With `return` and no `return` method + /// it jumps with `iterator next received`; with `throw` and no `throw` method it closes the + /// iterator and throws a `TypeError` (section 14.4.14). + DelegateCall(u32), + /// `mode result` → `result` when the iterator result is not done; when it is, jumps with + /// `mode value`. A result that is not an object is a `TypeError`. + DelegateResult(u32), + /// `mode value` → `value`; for `return`, jumps with it. + DelegateDone(u32), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -354,6 +378,9 @@ pub(crate) struct Code { /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: /// its functions have no `prototype` and cannot be constructed (section 14.3.8). pub(crate) method: bool, + /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), + /// and it is not a constructor. + pub(crate) generator: bool, } /// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. @@ -476,6 +503,12 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::IterClose => e(1, 0), Op::IterCloseThrow => end(2), Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), + Op::GeneratorStart => e(0, 0), + Op::Yield(_) => e(1, 2), + Op::Resume(t) | Op::DelegateDone(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 1)] }, + Op::DelegateIterator => e(1, 2), + Op::DelegateCall(t) => Effect { pops: 2, next: Some(4), jumps: vec![(t, 1)] }, + Op::DelegateResult(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 2)] }, }) } @@ -511,6 +544,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), + Op::GeneratorStart | Op::Yield(_) if !code.generator => Err("a generator instruction outside a generator function".into()), _ => Ok(()), } } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 26cd0a71cd..f4314f2e5e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -109,6 +109,8 @@ struct FnCompiler<'a> { /// The optional chains being compiled, innermost last: where a step that finds `undefined` /// or `null` jumps, and the stack depth the chain started at. optional: Vec<(Label, u32)>, + /// The code is a generator function's. + generator: bool, } /// The `var` names and function declarations a body hoists. @@ -157,6 +159,7 @@ impl<'a> FnCompiler<'a> { block_funcs: HashSet::new(), annex: HashSet::new(), optional: Vec::new(), + generator: false, } } @@ -281,12 +284,13 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations only a var binding too. + if !self.strict && !generator { annex.push((k, scope, id)); } } else { @@ -1351,10 +1355,73 @@ impl<'a> FnCompiler<'a> { self.at(self.ast.expr_span(id).end); self.nullish_check()?; } + Expr::Yield { arg, delegate: false } => { + match arg { + Some(e) => self.expr(*e)?, + None => self.emit(Op::Undefined), + } + self.at(self.ast.expr_span(id).start); + self.emit(Op::Yield(false)); + self.resume_after_yield()?; + } + Expr::Yield { arg: Some(e), delegate: true } => self.yield_delegate(id, *e)?, + Expr::Yield { arg: None, delegate: true } => return internal("yield* without an operand"), } Ok(()) } + /// After a `Yield` that left `received mode`: goes on with the received value for `next`, + /// throws it for `throw`, and for `return` returns it through the `finally` blocks around. + fn resume_after_yield(&mut self) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let ret = self.new_label(); + let after = self.new_label(); + self.jump(Op::Resume, ret); + self.jump(Op::Jump, after); + self.bind(ret); + self.emit_exit(Exit::Return)?; + self.bind(after); + Ok(()) + } + + /// `yield* operand` (ECMA-262 11th edition, section 14.4.14): each `next`, `throw` and `return` + /// the generator is resumed with goes to the operand's iterator, each result it gives that is + /// not done is yielded as it is, and a done one gives the expression its value, or for a + /// `return` returns that value. + fn yield_delegate(&mut self, id: ExprId, operand: ExprId) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let d = self.depth; + self.expr(operand)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::DelegateIterator); + // The first step calls `next` with one argument, `undefined`: the spec starts with + // `received` as NormalCompletion(undefined) and calls `next` with « received.[[Value]] ». + self.emit(Op::Undefined); + self.push_number(0.0); + let (step, ret, done, end) = (self.new_label(), self.new_label(), self.new_label(), self.new_label()); + self.bind(step); + self.jump(Op::DelegateCall, ret); + self.emit(Op::Call(1)); + self.jump(Op::DelegateResult, done); + self.emit(Op::Yield(true)); + self.jump(Op::Jump, step); + self.bind(done); + self.depth = d + 4; + self.jump(Op::DelegateDone, ret); + self.emit(Op::PopUnder(2)); + self.jump(Op::Jump, end); + self.bind(ret); + self.depth = d + 3; + self.emit_exit(Exit::Return)?; + self.bind(end); + self.depth = d + 1; + Ok(()) + } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression /// `id`, then the name, as an assignment, update or `delete` uses them. fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { @@ -2075,7 +2142,11 @@ impl<'a> FnCompiler<'a> { | Op::JumpIfNullish { target: t, .. } | Op::ForInNext(t) | Op::IterStep(t) - | Op::XmlFilterNext(t), + | Op::XmlFilterNext(t) + | Op::Resume(t) + | Op::DelegateCall(t) + | Op::DelegateResult(t) + | Op::DelegateDone(t), ) => *t = target, _ => return internal("patching an instruction that is not a jump"), } @@ -2123,6 +2194,7 @@ impl<'a> FnCompiler<'a> { es2015: self.es2015, own_name: meta.own_name, method: meta.method, + generator: self.generator, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -2156,6 +2228,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; + c.generator = f.generator; c.at(f.span.start); c.enter()?; // A destructured parameter has a binding of its own under a name no script can write, which @@ -2207,6 +2280,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, } c.emit(Op::BodyEnv); } + if f.generator { + // The call has bound the arguments and run the default values; the body waits for + // the first `next` (ECMA-262 2015 section 14.4.11). + c.at(f.span.start); + c.emit(Op::GeneratorStart); + } c.stmts(&f.body)?; c.at(f.span.end.saturating_sub(1)); c.emit(Op::Undefined); diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs new file mode 100644 index 0000000000..ccf3aee006 --- /dev/null +++ b/crates/js/src/generator.rs @@ -0,0 +1,414 @@ +//! Generator objects (ECMA-262 11th edition, , +//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`]. +//! +//! A call to a generator function runs its parameters' initialization and stops at +//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally` +//! blocks it is inside, moves into a new generator object, which the call returns. `next`, +//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same +//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit +//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A +//! suspended generator's frame is reachable only through its object, so the collector keeps it +//! while the object is reachable and frees it with the object. +//! +//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart + +use std::rc::Rc; + +use crate::LimitKind; +use crate::builtins::iterator::iter_result; +use crate::bytecode::Code; +use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; +use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::value::Value; + +/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). +/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResumeMode { + Next, + Throw, + Return, +} + +impl ResumeMode { + fn number(self) -> f64 { + match self { + ResumeMode::Next => 0.0, + ResumeMode::Throw => 1.0, + ResumeMode::Return => 2.0, + } + } + + fn of(v: &Value) -> JsResult { + match v { + Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next), + Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw), + Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return), + _ => internal("a resumption mode that is not one"), + } + } +} + +/// The estimated bytes of a suspended generator's frame besides its operands. +const GENERATOR_BYTES: usize = 128; + +/// The estimated bytes of each operand and `finally` entry a suspended frame holds. +const SLOT_BYTES: usize = 16; + +/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its +/// base and its `finally` entries, their stack slots counted from its base. +#[derive(Clone)] +pub(crate) struct SavedFrame { + pub(crate) code: Rc, + pc: usize, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, + env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, + pub(crate) completion: Value, + pub(crate) stack: Vec, + /// [`Interp::finally_sites`] entries. + pub(crate) sites: Vec<(ThrowSite, usize)>, + /// [`Interp::finally_marks`] entries. + pub(crate) marks: Vec<(ObjId, u32, usize)>, +} + +/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended. +#[derive(Clone)] +pub(crate) enum GenState { + SuspendedStart(SavedFrame), + SuspendedYield(SavedFrame), + Executing, + Completed, +} + +impl GenState { + /// The suspended frame, if the generator is suspended. + pub(crate) fn saved(&self) -> Option<&SavedFrame> { + match self { + GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s), + GenState::Executing | GenState::Completed => None, + } + } +} + +/// The bytes a suspended frame adds to its generator object, which a collection counts. +pub(crate) fn saved_bytes(s: &SavedFrame) -> usize { + GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len()))) +} + +/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was +/// resumed with and how, unless it had not started. +pub(crate) struct Resumed { + generator: ObjId, + saved: SavedFrame, + received: Option<(Value, ResumeMode)>, +} + +impl Interp { + fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> { + match self.heap.object_mut(g).map(|o| &mut o.class) { + Some(Class::Generator(s)) => Some(s), + _ => None, + } + } + + /// Marks the generator `g`, whose frame was popped without being saved, completed. + pub(crate) fn end_generator(&mut self, g: Option) { + if let Some(state) = g.and_then(|g| self.generator_state_mut(g)) + && let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed) + { + self.release_saved(&saved); + } + } + + /// Takes a saved frame that left its generator object off the heap's total. + fn release_saved(&mut self, saved: &SavedFrame) { + self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved)); + } + + /// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below. + fn deliver(&mut self, boundary: bool, v: Value) -> JsResult> { + if boundary { + return Ok(Some(v)); + } + self.push(v)?; + Ok(None) + } + + /// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`]. + fn save_frame(&mut self, frame: Frame) -> SavedFrame { + let base = frame.base; + let stack = self.stack.split_off(base.min(self.stack.len())); + let i = self.finally_sites.partition_point(|&(_, slot)| slot < base); + let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(id, mark, slot)| { + let below = slot < base; + if !below { + marks.push((id, mark, slot - base)); + } + below + }); + SavedFrame { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + stack, + sites, + marks, + } + } + + /// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor + /// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an + /// object, holding the frame, which the call returns. + pub(crate) fn op_generator_start(&mut self) -> JsResult> { + let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") }; + // A realm made without `Options::es2015` that reads the syntax later has no generator + // built-ins. + let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else { + return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them")); + }; + let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? { + Value::Object(p) => p, + _ => fallback, + }; + self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + let bytes = saved_bytes(&saved); + let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + self.deliver(boundary, Value::Object(g)) + } + + /// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame, + /// already past the instruction, goes into the generator object, and its caller gets the + /// iterator result. + pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult> { + let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") }; + if !raw { + let v = self.peek(0)?; + let result = iter_result(self, v, false)?; + self.replace(1, result)?; + } + // What `save_frame` keeps: the frame's operands without the result, popped below, and its + // own `finally` entries, not those of the frames under it. + let base = self.frame()?.base; + let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base)); + let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count(); + let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks); + let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); + self.reserve_heap(bytes)?; + let result = self.pop()?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + self.heap.bytes = self.heap.bytes.saturating_add(saved_bytes(&saved)); + let Some(state) = self.generator_state_mut(g) else { return internal("a generator's frame without its object") }; + *state = GenState::SuspendedYield(saved); + self.deliver(boundary, result) + } + + /// GeneratorResume and GeneratorResumeAbrupt (sections 25.4.3.3 and 25.4.3.4) for `next`, + /// `return` and `throw` called on `this` with `sent`: the result when the generator does not + /// run, or its frame to push. + pub(crate) fn prepare_resume(&mut self, this: Value, mode: ResumeMode, sent: Value) -> JsResult { + // Whether it has started, or `None` when it is running or completed. + let (g, started) = match this { + Value::Object(g) => match self.heap.object(g).map(|o| &o.class) { + Some(Class::Generator(s)) => match **s { + GenState::SuspendedStart(_) => (g, Some(false)), + GenState::SuspendedYield(_) => (g, Some(true)), + GenState::Executing => return Err(self.type_error("the generator is already running")), + GenState::Completed => (g, None), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }; + let Some(started) = started else { + return match mode { + ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)), + ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)), + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + }; + }; + if !started && mode != ResumeMode::Next { + self.end_generator(Some(g)); + return match mode { + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + _ => Ok(Prepared::Done(iter_result(self, sent, true)?)), + }; + } + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") }; + let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else { + return internal("a suspended generator without its frame"); + }; + self.release_saved(&saved); + let received = started.then_some((sent, mode)); + Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received }))) + } + + /// Pushes a resumed generator's frame, with the value it was resumed with and how on top of + /// its operands when it had yielded. + pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> { + let Resumed { generator, saved, received } = r; + if self.frames.len() >= self.limits.frames { + let bytes = saved_bytes(&saved); + if let Some(state) = self.generator_state_mut(generator) { + *state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) }; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let base = self.stack.len(); + self.drop_left_finally_sites(base); + let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved; + self.stack.extend(stack); + if let Some((value, mode)) = received { + self.stack.push(value); + self.stack.push(Value::Number(mode.number())); + } + self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base))); + self.frames.push(Frame { + code, + pc, + base, + env, + var_env, + env_depth, + this, + callee, + construct: None, + completion, + boundary, + generator: Some(generator), + }); + Ok(()) + } + + /// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`. + pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let received = self.peek(1)?; + self.pop()?; + self.pop()?; + match mode { + ResumeMode::Next => self.push(received), + ResumeMode::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(received)) + } + ResumeMode::Return => { + self.push(received)?; + self.jump_to(target) + } + } + } + + /// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or + /// `null`. + fn get_method(&mut self, v: &Value, name: &str) -> JsResult> { + let f = self.get_value(v, &key(name))?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error(&format!("the iterator's {name} is not a function"))); + } + Ok(Some(f)) + } + + /// [`Op::DelegateIterator`](crate::bytecode::Op::DelegateIterator): `value` → `iterator next`. + pub(crate) fn op_delegate_iterator(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let Some(sym) = self.well_known(|w| &w.iterator) else { return internal("no Symbol.iterator in this realm") }; + let method = self.get_value_sym(&v, &sym)?; + if !self.is_callable(&method) { + return Err(self.type_error("the value 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")); + } + self.replace(1, iterator.clone())?; + let next = self.get_value(&iterator, &key("next"))?; + self.push(next) + } + + /// [`Op::DelegateCall`](crate::bytecode::Op::DelegateCall): the method of `yield*`'s iterator + /// that the generator's resumption calls (section 14.4.14, step 7). + pub(crate) fn op_delegate_call(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let iterator = self.peek(3)?; + let method = match mode { + ResumeMode::Next => Some(self.peek(2)?), + ResumeMode::Throw => self.get_method(&iterator, "throw")?, + ResumeMode::Return => self.get_method(&iterator, "return")?, + }; + let received = self.peek(1)?; + match (method, mode) { + (Some(m), _) => { + self.replace(2, Value::Number(mode.number()))?; + self.push(m)?; + self.push(iterator)?; + self.push(received) + } + (None, ResumeMode::Return) => { + self.replace(2, received)?; + self.jump_to(target) + } + (None, _) => { + // The iterator has no `throw`: it is closed, and the protocol violation is a + // `TypeError` (step 7.b.iii). + if let Some(close) = self.get_method(&iterator, "return")? { + let result = self.call(&close, &iterator, &[])?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + } + Err(self.type_error("the iterator has no throw method")) + } + } + } + + /// [`Op::DelegateResult`](crate::bytecode::Op::DelegateResult): `mode result` → `result`, or + /// when it is done, a jump with `mode value`. + pub(crate) fn op_delegate_result(&mut self, target: u32) -> JsResult<()> { + let result = self.peek(0)?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + if self.get_value(&result, &key("done"))?.truthy() { + let value = self.get_value(&result, &key("value"))?; + self.replace(1, value)?; + return self.jump_to(target); + } + self.replace(2, result) + } + + /// [`Op::DelegateDone`](crate::bytecode::Op::DelegateDone): `mode value` → `value`, a jump for + /// `return`. + pub(crate) fn op_delegate_done(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(1)?)?; + let value = self.peek(0)?; + self.replace(2, value)?; + if mode == ResumeMode::Return { + return self.jump_to(target); + } + Ok(()) + } +} diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs new file mode 100644 index 0000000000..551fb4e5e6 --- /dev/null +++ b/crates/js/src/generator_tests.rs @@ -0,0 +1,382 @@ +//! Generator functions, `yield`, `yield*` and the generator objects, in a realm with +//! [`Options::es2015`]. + +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015(limits: Limits) -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, limits) +} + +fn run(src: &str) -> JsValue { + match es2015(Limits::default()).run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match es2015(Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +/// The script does not parse in a realm with `options`. +fn syntax_with(src: &str, options: Options) { + match Realm::with_options(options, Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Syntax, .. }) => {} + other => panic!("{src}: {other:?}"), + } +} + +fn syntax(src: &str) { + syntax_with(src, Options { es2015: true, ..Options::default() }); +} + +#[test] +fn promise_jobs_resume_generator_callbacks() { + let mut realm = es2015(Limits::default()); + realm + .run( + "var log = []; var it = (function* () { log.push('start'); var value = yield 7; \ + log.push('resume:' + value); return 9; })(); \ + Promise.resolve().then(it.next.bind(it)).then(function (result) { \ + log.push(result.value + ':' + result.done); return it.next(5); \ + }).then(function (result) { log.push(result.value + ':' + result.done); });", + ) + .unwrap(); + assert_eq!(realm.run("log.join(',')").unwrap(), JsValue::String("start,7:false,resume:5,9:true".into())); +} + +#[test] +fn promise_static_methods_reject_generator_constructors() { + truth( + "var g = function* () {}, count = 0; [g, g.bind(null)].forEach(function (C) { \ + try { Promise.resolve.call(C, 1); } catch (error) { if (error instanceof TypeError) count++; } \ + try { Promise.reject.call(C, 1).catch(function () {}); } \ + catch (error) { if (error instanceof TypeError) count++; } }); count === 4", + ); +} + +#[test] +fn a_generator_runs_its_body_one_yield_at_a_time() { + assert_eq!( + string( + "var log = []; function* g(a, b) { log.push('start'); var x = yield a; log.push(x); yield b + x; return 'end'; } \ + var it = g(1, 2); log.push('made'); var r = [it.next('ignored'), it.next(10), it.next(20), it.next()]; \ + log.join() + ' ' + r.map(function (o) { return o.value + ':' + o.done; }).join()" + ), + "made,start,10 1:false,12:false,end:true,undefined:true" + ); + // The parameters' default values run at the call, the body at the first `next`. + assert_eq!(string("var log = []; function* g(a = log.push('d')) { log.push('b'); } var it = g(); log.push('c'); it.next(); log.join()"), "d,c,b"); + truth("function* g() { yield this; } var o = { g: g }; o.g().next().value === o"); + truth("function* g() { return arguments.length; } g(1, 2, 3).next().value === 3"); + truth("var it = (function* () {})(); var r = it.next(); r.value === undefined && r.done === true"); + truth("function* g() { yield 1; } var a = g(), b = g(); a.next(); a.next().done && !b.next().done"); +} + +#[test] +fn yield_takes_an_operand_only_on_the_same_line() { + assert_eq!(string("function* g() { yield\n1; } var it = g(); String(it.next().value) + ',' + it.next().done"), "undefined,true"); + truth("function* g() { var x = yield; return x; } var it = g(); it.next(); it.next(7).value === 7"); + truth("function* g() { yield /a/g; } g().next().value instanceof RegExp"); + truth("function* g() { yield yield 1; } var it = g(); it.next().value === 1 && it.next(2).value === 2"); + truth("function* g() { var a = [yield 1, yield 2]; return a.join(); } var it = g(); it.next(); it.next('x'); it.next('y').value === 'x,y'"); +} + +#[test] +fn return_runs_the_finally_blocks_around_the_yield() { + truth( + "var log = []; function* g() { try { yield 1; yield 2; } finally { log.push('f'); } } \ + var it = g(); it.next(); var r = it.return(9); r.value === 9 && r.done === true && log.join() === 'f' && it.next().done", + ); + // A `finally` block that yields suspends the return, which ends at the next resumption. + assert_eq!( + string( + "function* g() { try { yield 1; } finally { yield 'cleanup'; } } var it = g(); it.next(); \ + var a = it.return(5), b = it.next(), c = it.next(); [a.value, a.done, b.value, b.done, c.done].join()" + ), + "cleanup,false,5,true,true" + ); + truth("function* g() { try { yield 1; } finally { return 'override'; } } var it = g(); it.next(); it.return(5).value === 'override'"); + // Before the body starts, and after it ends, `return` only completes the generator. + truth("var ran = false; function* g() { ran = true; } var it = g(); var r = it.return(3); r.value === 3 && r.done && !ran && it.next().done"); + truth("function* g() {} var it = g(); it.next(); var r = it.return(4); r.value === 4 && r.done"); +} + +#[test] +fn throw_goes_into_a_suspended_generator() { + truth("function* g() { try { yield 1; } catch (e) { yield 'caught ' + e; } } var it = g(); it.next(); it.throw('x').value === 'caught x'"); + truth( + "function* g() { yield 1; yield 2; } var it = g(); it.next(); var e; try { it.throw(new RangeError('r')); } catch (x) { e = x; } \ + e instanceof RangeError && it.next().done", + ); + // A generator that has not started is completed by `throw`, which its body never sees. + truth( + "var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done", + ); + throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); +} + +#[test] +fn resuming_a_running_generator_is_a_type_error() { + truth( + "var it; function* g() { try { it.next(); } catch (e) { yield e instanceof TypeError; } } it = g(); \ + it.next().value === true", + ); + truth("var it; function* g() { it.next(); } it = g(); var e; try { it.next(); } catch (x) { e = x; } e instanceof TypeError && it.next().done"); + throws("var g = function* () {}; g.prototype.next.call({});", "TypeError"); + throws("(function* () {}).prototype.next.call(1);", "TypeError"); +} + +#[test] +fn yield_star_delegates_next_throw_and_return() { + truth( + "function* g() { yield* [1, 2]; yield* 'ab'; } var r = []; var it = g(), s; while (!(s = it.next()).done) r.push(s.value); r.join() === '1,2,a,b'", + ); + truth( + "function* inner() { yield 1; return 'r'; } function* outer() { var v = yield* inner(); yield v; } var it = outer(); it.next().value === 1 && it.next().value === 'r'", + ); + // The values `next` sends go to the delegate. + truth( + "function* inner() { var x = yield 1; yield x * 2; } function* outer() { yield* inner(); } var it = outer(); it.next(); it.next(21).value === 42", + ); + truth( + "var log = []; function* inner() { try { yield 1; } finally { log.push('inner'); } } function* outer() { try { yield* inner(); } finally { log.push('outer'); } } \ + var it = outer(); it.next(); var r = it.return(7); r.value === 7 && r.done && log.join() === 'inner,outer'", + ); + truth( + "function* inner() { try { yield 1; } catch (e) { yield 'in ' + e; } } function* outer() { yield* inner(); } var it = outer(); it.next(); it.throw('t').value === 'in t'", + ); + // The delegate's own results are passed on as they are. + truth( + "var r = { done: false, value: 1, extra: 2 }; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return r; } }; }; function* g() { yield* o; } g().next() === r", + ); + // A delegate without `throw` is closed, and the generator gets a TypeError. + truth( + "var closed = false; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return { done: false }; }, return: function () { closed = true; return {}; } }; }; \ + function* g() { yield* o; } var it = g(); it.next(); var e; try { it.throw(1); } catch (x) { e = x; } e instanceof TypeError && closed", + ); + throws("function* g() { yield* 5; } g().next();", "TypeError"); + throws( + "var o = {}; o[Symbol.iterator] = function () { return { next: function () { return 1; } }; }; function* g() { yield* o; } g().next();", + "TypeError", + ); +} + +#[test] +fn generator_methods_and_the_generator_objects() { + truth("var o = { *g(a) { yield this === o && a; } }; o.g(5).next().value === 5"); + truth("var o = { *'s'() { yield 1; }, *2() { yield 2; } }; o.s().next().value + o[2]().next().value === 3"); + throws("function* g() {} new g();", "TypeError"); + throws("var o = { *m() {} }; new o.m();", "TypeError"); + // A generator method has a `prototype` that its generator objects inherit from, unlike other + // methods, and takes a computed name and the method's `name`. + truth("var o = { *m() {} }; var it = o.m(); Object.getPrototypeOf(it) === o.m.prototype && !o.m.prototype.hasOwnProperty('constructor')"); + truth("var k = 'c'; var o = { *[k + 'd']() { yield 4; } }; o.cd().next().value === 4 && o.cd.name === 'cd'"); + truth("function* g() {} var GP = Object.getPrototypeOf(g); GP === Object.getPrototypeOf(function* () {}) && GP !== Function.prototype"); + truth("function* g() {} Object.getPrototypeOf(g.prototype) === Object.getPrototypeOf(g).prototype && !g.prototype.hasOwnProperty('constructor')"); + truth("function* g() {} var it = g(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Generator]'"); + truth("function* g() {} Object.prototype.toString.call(g) === '[object GeneratorFunction]' && g instanceof Function && typeof g === 'function'"); + // %GeneratorFunction.prototype% is an ordinary object, not a function (section 25.2.3). + truth("var GP = Object.getPrototypeOf(function* () {}); typeof GP === 'object' && Object.getPrototypeOf(GP) === Function.prototype"); + throws("Object.getPrototypeOf(function* () {})();", "TypeError"); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; var f = GF('a', 'yield a; yield a * 2;'); var it = f(3); it.next().value + it.next().value === 9", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; Object.getPrototypeOf(GF) === Function && GF.prototype === Object.getPrototypeOf(function* () {})", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; typeof this.GeneratorFunction === 'undefined' && new GF('yield 1')().next().value === 1", + ); + truth("function* g() { yield 1 } String(g) === 'function* g() { yield 1 }'"); + // A generator function's own `prototype` is used when it is an object. + truth("function* g() {} var p = { mark: 1 }; g.prototype = p; Object.getPrototypeOf(g()) === p"); + truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); +} + +#[test] +fn a_bound_generator_function_inherits_from_the_targets_prototype() { + truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function"); + truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3"); + truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype"); +} + +#[test] +fn yield_is_an_identifier_outside_generators_in_sloppy_code() { + truth("var yield = 1; yield + 1 === 2"); + truth("function f(yield) { return yield; } f(3) === 3"); + truth("function* g() { function f() { var yield = 4; return yield; } yield f(); } g().next().value === 4"); + truth("function* g() { var o = { yield: 5 }; yield o.yield; } g().next().value === 5"); + truth("function* yield() { yield 6; } yield().next().value === 6"); + syntax("'use strict'; var yield = 1;"); +} + +#[test] +fn bad_generators_are_syntax_errors() { + for src in [ + "function* g() { var yield; }", + "function* g(yield) {}", + "function* g(a = yield) {}", + "function* g() { function* h(a = yield 1) {} }", + "var f = function* yield() {};", + "function* g() { (yield) => 1; }", + "function* g() { yield = 1; }", + "function* g() { yi\\u0065ld 1; }", + "function* g() { yield\n* 1; }", + "function* g() { yield: 1; }", + "if (true) function* g() {}", + "L: function* g() {}", + "{ function* g() {} function* g() {} }", + "function* g() { yield* ; }", + "var o = { *m(a, a) {} };", + "function* g() { (a = yield) => 1; }", + ] { + syntax(src); + } + // A `yield` in the body of a function in a generator's parameters belongs to that function. + truth("function* g(a = function* () { yield 1; }) { yield* a(); } g().next().value === 1"); + truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); +} + +#[test] +fn realms_without_es2015_have_no_generators() { + let es5 = Options::default(); + let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() }; + for options in [es5, extendscript] { + for src in ["function* g() {}", "var g = function* () {};", "var o = { *m() {} };"] { + syntax_with(src, options.clone()); + } + let mut realm = Realm::with_options(options, Limits::default()); + assert_eq!(realm.run("function f() { var yield = 2; return yield; } f()"), Ok(JsValue::Number(2.0))); + // Reading the syntax later does not add the built-ins, so a call is a TypeError. + realm.set_es2015(true); + match realm.run("function* g() { yield 1; } g();") { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"), + other => panic!("{other:?}"), + } + } +} + +#[test] +fn a_suspended_generator_keeps_its_frame_across_a_collection() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var local = { v: 'left' }; var r = [{ w: 'held' }, yield 1]; yield local.v + r[0].w + r[1]; } \ + var it = g(); it.next(); it.next('!').value"; + assert_eq!(realm.run(setup), Ok(JsValue::String("leftheld!".into()))); + // The operands on the stack at the `yield` (the array being built) survive a collection. + assert_eq!(realm.run("var it3 = g(); it3.next(); 'ok'"), Ok(JsValue::String("ok".into()))); + realm.collect_garbage(); + assert_eq!(realm.run("it3.next('#').value"), Ok(JsValue::String("leftheld#".into()))); +} + +#[test] +fn a_frame_taken_out_of_its_generator_leaves_the_heap_total() { + let mut realm = es2015(Limits::default()); + // At the `yield`, the 500 arguments before it are operands in the saved frame. + let args = vec!["0"; 500].join(", "); + let setup = format!("function f() {{}} function* g() {{ while (true) f({args}, yield 1); }} var it = g(); it.next(); 0"); + assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0))); + let mut gaps = Vec::new(); + for resumes in [10, 210] { + realm.collect_garbage(); + assert_eq!(realm.run(&format!("for (var i = 0; i < {resumes}; i++) it.next(); 0")), Ok(JsValue::Number(0.0))); + let counted = realm.interp().heap.bytes; + gaps.push(counted.saturating_sub(realm.collect_garbage())); + } + // 200 more resumptions leave far less than one saved frame's worth each. + assert!(gaps[1] < gaps[0] + 200 * 1024, "{gaps:?}"); +} + +#[test] +fn an_unreachable_suspended_generator_is_freed() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var big = []; for (var i = 0; i < 20000; i++) big.push({ i: i }); yield big.length; } var it = g(); it.next().value"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(20000.0))); + let held = realm.collect_garbage(); + assert_eq!(realm.run("it = null; 0"), Ok(JsValue::Number(0.0))); + let freed = realm.collect_garbage(); + assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); +} + +/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`. +fn smallest_heap_limit(setup: &str, script: &str) -> usize { + let fits = |limit: usize| { + let mut realm = es2015(Limits::default()); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + realm.run(script).is_ok() + }; + let (mut low, mut high) = (0, 64 << 20); + assert!(fits(high), "{script}"); + while high - low > 256 { + let mid = low + (high - low) / 2; + if fits(mid) { + high = mid; + } else { + low = mid; + } + } + high +} + +#[test] +fn a_yield_reserves_only_what_its_frame_keeps() { + // At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks + // that a throw entered. Their entries stay with those frames, so the yield needs no more room + // than the one in `before`, which comes before those frames are pushed. + let setup = "function* g() { yield 1; } var it = g(); 0"; + let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0"; + let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0"; + let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before)); + assert!(inside < before + 4096, "inside {inside}, before {before}"); +} + +#[test] +fn generators_stay_within_the_limits() { + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("function* g() { while (true) yield 1; } var it = g(); while (true) it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + // Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next` + // take at least 1,000 more than the same calls of a native method that takes none. + let mut realm = es2015(Limits::default()); + let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let mut used = Vec::new(); + for callee in ["control", "it"] { + assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0))); + used.push(Limits::default().fuel - realm.fuel_left()); + } + assert!(used[1] >= used[0] + 1000, "{used:?}"); + // A deep `yield*` chain stops at the frame limit, and the realm can run again. + let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); + match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Frames), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(20).next().value"), Ok(JsValue::Number(1.0))); + // A generator whose body was running when a limit ended the run cannot be resumed. + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("var it = (function* () { while (true) {} })(); it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("var r = it.next(); r.done && r.value === undefined"), Ok(JsValue::Bool(true))); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 57ec9d6680..1a58fa1d28 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -181,6 +181,8 @@ pub(crate) enum NativeKind { Apply, /// The global `eval`: a call to it by that name is a direct eval. Eval, + /// `%GeneratorPrototype%`'s `next`, `return` or `throw`. + Resume(crate::generator::ResumeMode), } /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section @@ -245,6 +247,8 @@ pub(crate) enum Class { /// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the /// operand stack only. IterRecord(Box), + /// A generator object and its state (ECMA-262 11th edition, section 25.4). + Generator(Box), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -339,7 +343,13 @@ impl Class { Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object", + Class::Ordinary + | Class::ForIn(_) + | Class::Host(_) + | Class::Symbol(_) + | Class::Iterator(_) + | Class::IterRecord(_) + | Class::Generator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -759,6 +769,24 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u 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)), }, + Class::Generator(state) => { + if let Some(saved) = state.saved() { + work.push(saved.env.0); + work.push(saved.var_env.0); + work.extend(saved.callee.iter().map(|o| o.0)); + work.extend(saved.marks.iter().map(|&(id, _, _)| id.0)); + mark_value(&saved.this, work, strings); + mark_value(&saved.completion, work, strings); + for v in &saved.stack { + mark_value(v, work, strings); + } + mark_code(&saved.code, strings); + for ((code, _), _) in &saved.sites { + mark_code(code, strings); + } + extra = crate::generator::saved_bytes(saved); + } + } Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 6a57041cfe..f8e80a6e87 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4,7 +4,9 @@ //! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call //! only where the language needs a function's result in the middle of an operation (a getter or //! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are -//! counted against [`crate::Limits::reentry`]. +//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own, +//! which `yield` moves into the generator object, operands included, and a call to its `next`, +//! `return` or `throw` pushes again ([`crate::generator`]). //! //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap @@ -198,22 +200,24 @@ pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. - base: usize, + pub(crate) base: usize, pub(crate) env: EnvId, pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. - env_depth: u32, - this: Value, - callee: Option, + pub(crate) env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, /// The object `new` made, returned unless the function returns an object. - construct: Option, - completion: Value, + pub(crate) construct: Option, + pub(crate) completion: Value, /// Returning from this frame returns from the Rust call that pushed it. - boundary: bool, + pub(crate) boundary: bool, + /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. + pub(crate) generator: Option, } /// Where the exception being thrown was raised: the code and the instruction. -type ThrowSite = (Rc, usize); +pub(crate) type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -530,7 +534,7 @@ fn arguments_bytes(args: usize) -> usize { } /// A call to a function written in JavaScript, ready to enter. -struct Entry { +pub(crate) struct Entry { callee: ObjId, code: Rc, env: EnvId, @@ -539,9 +543,11 @@ struct Entry { } /// What a call resolved to. -enum Prepared { +pub(crate) enum Prepared { Closure(Entry), Done(Value), + /// A generator's `next`, `return` or `throw` that goes on with its body. + Resume(Box), } /// A variable found in the environment chain. @@ -868,7 +874,7 @@ impl Interp { /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. - fn drop_left_finally_sites(&mut self, len: usize) { + pub(crate) fn drop_left_finally_sites(&mut self, len: usize) { while let Some(&(_, slot)) = self.finally_sites.last() { #[cfg(test)] SITE_CHECKS.with(|c| c.set(c.get() + 1)); @@ -896,7 +902,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.generator.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -995,6 +1001,8 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::GeneratorStart => self.op_generator_start(), + Op::Yield(raw) => self.op_yield(raw), _ => self.exec(op).map(|()| None), } } @@ -1049,6 +1057,7 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -1065,6 +1074,7 @@ impl Interp { fn abort_to_boundary(&mut self) { while let Some(frame) = self.frames.pop() { self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { break; } @@ -1072,8 +1082,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // A generator's body that returns ends it, and its caller gets `{ value, done: true }`, + // made while the frame is still there to fail in. + let v = match self.frames.last().and_then(|f| f.generator) { + Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); let v = match frame.construct { @@ -1254,7 +1271,12 @@ impl Interp { 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"), + Op::Resume(t) => self.op_resume(t), + Op::DelegateIterator => self.op_delegate_iterator(), + Op::DelegateCall(t) => self.op_delegate_call(t), + Op::DelegateResult(t) => self.op_delegate_result(t), + Op::DelegateDone(t) => self.op_delegate_done(t), + Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"), } } @@ -2407,7 +2429,8 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten(); + let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto); let length = code.length; let strict = code.strict; let arrow = code.arrow; @@ -2421,6 +2444,18 @@ impl Interp { if let Some(name) = own_name { self.define(f, key("name"), Prop::Data { value: Value::String(Str::from_rc(name)), flags: CONFIGURABLE })?; } + // A generator function's `prototype`, a generator method's included, inherits from + // %GeneratorPrototype% and has no `constructor` (ECMA-262 11th edition, section 14.4.13). + // A generator function has no own `caller` or `arguments`, strict or not + // (section 16.2). + if let (false, Some((_, generator_proto))) = (arrow, generator) { + let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto))); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } // An arrow function, a method and an accessor of ECMAScript 2015 code have no // `prototype` and cannot be constructed (sections 14.2.16 and 14.3.8). if arrow || method { @@ -2819,6 +2854,11 @@ impl Interp { let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?; return Ok(Prepared::Closure(Entry { callee, code, env, this, args })); } + Func::Native { kind: NativeKind::Resume(mode), .. } => { + self.use_fuel()?; + let sent = args.into_iter().next().unwrap_or(Value::Undefined); + return self.prepare_resume(this, mode, sent); + } Func::Native { kind: NativeKind::Call, .. } => { self.use_fuel()?; f = this; @@ -2944,6 +2984,10 @@ impl Interp { self.stack.truncate(start); self.enter_function(entry, None, false) } + Prepared::Resume(r) => { + self.stack.truncate(start); + self.enter_resumed(*r, false) + } } } @@ -2964,6 +3008,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")), Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; @@ -3066,6 +3111,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -3300,6 +3346,7 @@ impl Interp { match prepared? { Prepared::Done(v) => Ok(Some(v)), Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None), + Prepared::Resume(resumed) => self.enter_resumed(*resumed, true).map(|()| None), } } @@ -3311,6 +3358,11 @@ impl Interp { self.enter_function(entry, None, true)?; self.execute() } + Prepared::Resume(r) => { + self.stack.truncate(saved); + self.enter_resumed(*r, true)?; + self.execute() + } } } @@ -3560,6 +3612,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index a300d22451..97f33ea054 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -1015,6 +1015,7 @@ fn code(ops: Vec) -> Code { es2015: false, own_name: None, method: false, + generator: false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 17f2b1de0f..a93dcd5483 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -63,7 +63,16 @@ //! 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 and `arguments` objects //! by index and strings by code point, and throw a `TypeError` for other values. -//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors. +//! Object rest properties (`{ a, ...rest }`), classes and modules stay syntax errors. +//! +//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition, +//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in +//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the +//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from +//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's +//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame +//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a +//! generator while its body runs is a `TypeError`. //! //! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, //! ): `Symbol.for` and `Symbol.keyFor` over a registry @@ -96,6 +105,7 @@ mod compiler; mod date_builtins; mod error; mod file_classes; +mod generator; mod heap; mod host; mod host_classes; @@ -273,6 +283,8 @@ mod es2020_tests; #[cfg(test)] mod extension_tests; #[cfg(test)] +mod generator_tests; +#[cfg(test)] mod host_tests; #[cfg(test)] mod interp_tests; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 0e25c141fe..b0b6870b67 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -37,6 +37,9 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is a generator function's body or parameters: `yield` starts a yield expression + /// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4). + generator: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -115,6 +118,9 @@ pub(crate) struct Parser<'s> { /// section B.3.1). Each is also in `cover_inits`, so it is a `SyntaxError` unless the literal /// is read as a destructuring pattern. proto_twice: HashSet, + /// Where each yield expression read so far starts, in the order read, so the parameters of a + /// generator function and an arrow function's head can be checked for one. + yields: Vec, } impl<'s> Parser<'s> { @@ -143,6 +149,7 @@ impl<'s> Parser<'s> { cover_ok: false, rest_commas: HashSet::new(), proto_twice: HashSet::new(), + yields: Vec::new(), }; parser.tok = parser.next_significant()?; Ok(parser) @@ -284,9 +291,18 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if self.ctx.generator && name == "yield" { + return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function")); + } Ok(()) } + /// A yield expression starts at `offset` or later, before `end`. + fn yield_between(&self, offset: u32, end: u32) -> bool { + let i = self.yields.partition_point(|&y| y < offset); + self.yields.get(i).is_some_and(|&y| y < end) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -359,7 +375,7 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) }; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -368,7 +384,8 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + // Only plain function declarations may repeat in a block (Annex B.3.3.4). + Some(_) => self.declare_lexical(&name, !generator), None => Ok(()), } } @@ -532,6 +549,9 @@ impl<'s> Parser<'s> { }; return Err(self.error_at_token(&self.tok, message)); } + if self.es2015 && self.peek().is_some_and(|t| t.is_punct(Punct::Star)) { + return Err(self.error_at_token(&self.tok, "a generator declaration cannot stand here; put it in a block")); + } self.parse_function_declaration() } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), @@ -1039,8 +1059,9 @@ impl<'s> Parser<'s> { fn parse_function_declaration(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; + let generator = self.es2015 && self.eat(Punct::Star)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -1056,15 +1077,28 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + generator: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with the function's own `yield` rule, not the enclosing code's. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let yields = self.yields.len(); + let result = self.function_rest(kind, name, start, generator); + // The `yield` expressions of this function are not in the code around it. + self.yields.truncate(yields); + self.ctx.generator = outer_generator; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result { + let params_start = self.tok.span.start; self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1097,6 +1131,10 @@ impl<'s> Parser<'s> { } } let close = self.expect(Punct::RParen)?; + if generator && self.yield_between(params_start, close.span.start) { + let at = self.yields.get(self.yields.partition_point(|&y| y < params_start)).copied().unwrap_or(params_start); + return Err(self.error_at_offset(at, "a yield expression cannot stand in a generator function's parameters")); + } match kind { FunctionKind::Getter if !params.is_empty() || rest.is_some() => { return Err(self.error_at_token(&close, "a getter must not have parameters")); @@ -1112,7 +1150,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1121,7 +1159,7 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start) }; self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } @@ -1153,7 +1191,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, generator: false, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1271,10 +1310,15 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; - if self.es2015 && self.at(Punct::Arrow) { - expr = self.arrow_from(expr, no_in)?; - } + let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped { + self.parse_yield(no_in)? + } else { + let mut expr = self.parse_conditional(no_in)?; + if self.es2015 && self.at(Punct::Arrow) { + expr = self.arrow_from(expr, no_in)?; + } + expr + }; let Some(op) = assign_op(&self.tok) else { let mut value = expr; while let Some((target, op)) = targets.pop() { @@ -1293,10 +1337,28 @@ impl<'s> Parser<'s> { } } + /// A yield expression, from `yield` (ECMA-262 2015 section 14.4): its operand is left out when + /// a line break follows `yield` or the next token cannot start an expression, and `yield*` + /// must have one. + fn parse_yield(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + self.yields.push(start.start); + let delegate = !self.tok.newline_before && self.at(Punct::Star); + if delegate { + self.bump()?; + } + let arg = + if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None }; + Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start))) + } + /// The arrow function whose head is `expr`, read before the current `=>`: a name standing /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); + if self.yield_between(start.start, start.end) { + return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); + } let params = match self.ast.expr(expr) { Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), Some(Expr::Paren(_)) => self.arrow_params(expr)?, @@ -1706,8 +1768,13 @@ impl<'s> Parser<'s> { fn parse_function_expression(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let generator = self.es2015 && self.eat(Punct::Star)?; + // A generator expression's name is read with its own `yield` rule. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.generator = outer_generator; + let name = name?; + let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1790,7 +1857,7 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -1829,6 +1896,42 @@ fn property_key(token: &Token) -> Option { } } +/// The token can start an expression, so a `yield` before it on the same line takes an operand. +fn starts_expression(token: &Token, e4x: bool) -> bool { + match &token.kind { + TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true, + TokenKind::Keyword(k) => matches!( + k, + Keyword::This + | Keyword::Null + | Keyword::True + | Keyword::False + | Keyword::Function + | Keyword::New + | Keyword::Delete + | Keyword::Void + | Keyword::Typeof + ), + TokenKind::Punct(p) => { + matches!( + p, + Punct::LParen + | Punct::LBracket + | Punct::LBrace + | Punct::Plus + | Punct::Minus + | Punct::Bang + | Punct::Tilde + | Punct::PlusPlus + | Punct::MinusMinus + | Punct::Slash + | Punct::SlashEq + ) || (e4x && matches!(p, Punct::Lt | Punct::At)) + } + _ => false, + } +} + fn is_eval_or_arguments(name: &str) -> bool { name == "eval" || name == "arguments" } diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index 27d684ced2..a616adc805 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -146,6 +146,12 @@ impl Parser<'_> { /// initializer (`a = 1`), which only a pattern may hold. pub(super) fn parse_property_es2015(&mut self) -> Result { let start = self.tok.span; + // `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4). + if self.eat(Punct::Star)? { + let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; + let function = self.parse_function_rest(FunctionKind::Method, None, start, true)?; + return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); + } // `get` and `set` start an accessor only when written without escapes and followed by a // property name. let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) { @@ -158,7 +164,7 @@ impl Parser<'_> { { 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 function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -192,7 +198,7 @@ impl Parser<'_> { /// the value may still turn out to be a pattern. fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result { if self.at(Punct::LParen) { - let function = self.parse_function_rest(FunctionKind::Method, None, start)?; + let function = self.parse_function_rest(FunctionKind::Method, None, start, false)?; return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); } self.expect(Punct::Colon)?; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index a3a7c0cc1f..bd191b0463 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -353,6 +353,9 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.stack.clear(); + // A generator whose body was running when the run ended cannot go on. + let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect(); + running.into_iter().for_each(|g| interp.end_generator(Some(g))); interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7f19ba162e..4bb98b1e55 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects { pub(crate) array_values: ObjId, /// `Function.prototype[@@hasInstance]`. pub(crate) has_instance: ObjId, + /// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from. + pub(crate) generator_proto: ObjId, + /// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function. + pub(crate) generator_function_proto: ObjId, } /// The estimated bytes of a registry entry without its Symbol. @@ -208,7 +212,17 @@ impl Symbols { /// The objects the collector starts from. pub(crate) fn root_objects(&self) -> Vec { - self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + self.objects.map_or_else(Vec::new, |o| { + vec![ + o.symbol_proto, + o.array_iterator_proto, + o.string_iterator_proto, + o.array_values, + o.has_instance, + o.generator_proto, + o.generator_function_proto, + ] + }) } /// The bytes the registry's entries hold besides their Symbols, which a collection adds. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index bd8c406b79..8d012a81e1 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -51,11 +51,15 @@ //! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and //! that parse with that option. Its failures go to `symbol-failures.txt`. //! -//! The last test reads the tests of `for-of` and destructuring (the folders +//! Another 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 last test reads and runs the tests of generator functions, `yield` and the generator objects +//! (the folders [`GENERATOR_FOLDERS`] names) the same way, with the `generators` tag and the tags of +//! the two tests before it. Its failures go to `generators-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. @@ -1176,6 +1180,58 @@ fn run_for_of_and_patterns(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The folders of the tests of generator functions, `yield` and the generator objects, which run +/// in a realm with [`Options::es2015`]. +const GENERATOR_FOLDERS: &[&str] = &[ + "language/statements/generators", + "language/expressions/generators", + "language/expressions/yield", + "built-ins/GeneratorPrototype", + "built-ins/GeneratorFunction", +]; + +#[test] +fn es2015_generators_run() { + let Some(dir) = suite_dir() else { + println!("test262 generators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_generators(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Reads the tests under each folder [`GENERATOR_FOLDERS`] names whose feature tags are all +/// `generators` or in [`FOR_OF_AND_PATTERN_FEATURES`] or [`SYMBOL_FEATURES`] with +/// [`Options::es2015`], as [`run_for_of_and_patterns`] reads its tests. Prints the counts of each +/// folder and writes the failures to `generators-failures.txt` beside the suite. +fn run_generators(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let mut features: Vec<&str> = vec!["generators"]; + features.extend(FOR_OF_AND_PATTERN_FEATURES); + features.extend(SYMBOL_FEATURES); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in GENERATOR_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, &features); + counts.add(run_tagged_tests(dir, &root, &missing, &options, &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 generator tests ran under {}", dir.display()); + let path = dir.join("generators-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 generators 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 { diff --git a/docs/mcp.md b/docs/mcp.md index bba4d6e73d..855d1b8b90 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2721,9 +2721,17 @@ value, assignment target or property they are first given to, with `get ` or `se Symbol key's description in brackets; `bound ` before the target's name for `bind`; `anonymous` for `Function`; and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). A function's `length` can be redefined. The built-in functions get their names the first time a run reads -ECMAScript 2015, and keep them in later `.jsx` runs of an engine that `#targetengine` keeps. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and +ECMAScript 2015, and keep them in later `.jsx` runs of an engine that `#targetengine` keeps. A `.js` script also has +generator functions (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): +`function*` declarations and expressions, `*name() {…}` methods in object literals, `yield`, and `yield*`, which +passes `next`, `throw` and `return` on to the iterator it delegates to. Calling a generator function returns a +generator object whose `next`, `return` and `throw` run its body to the next `yield`; `return` runs the body's +`finally` blocks, and resuming a generator while its body runs throws a `TypeError`. Each resumption takes fuel and +counts against the call depth. A generator function called in an engine that `#targetengine` kept from a `.jsx` run +throws a `TypeError`, since that engine was made without the ECMAScript 2015 built-ins. `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. A `.js` file +`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there +`yield` is a name like any other. A `.js` file also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or `null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af90145d80..74a9bef455 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1125,7 +1125,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans. A comma may follow the last argument of a call or `new` expression and the last parameter of a function other than a setter, as ECMAScript 2017 allows (https://tc39.es/ecma262/2017/#sec-left-hand-side-expressions, https://tc39.es/ecma262/2017/#sec-function-definitions); `f(,)` and `f(1,,)` give a `SyntaxError`. 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 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: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. 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 and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.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), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), 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: 7,000 of 7,070 runs pass (the 35 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,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 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`. @@ -1134,6 +1134,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. 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`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. 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, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `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: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. 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 it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or 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: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,267 of 1,287 runs of 668 tests pass. Of the 20 others, 16 do not parse because the tests also use classes, and 4 expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - 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. `` 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`.