mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
JavaScript: generator functions, yield and yield* in ES2015 realms
A realm made with Options::es2015 reads function* declarations and expressions, *name() methods in object literals, yield and yield*, as ECMA-262 11th edition sections 14.4 and 25.4 define them. A suspended generator keeps its frame in its object; next, return and throw on %GeneratorPrototype% push it back on the interpreter's frame stack, so a resumption takes fuel and counts against the frame limit, and return runs the finally blocks around the yield. Resuming a running generator throws a TypeError. yield* passes next, throw and return on to its iterator and closes one without throw before throwing a TypeError. %GeneratorFunction% is reached through a generator function's constructor. Outside generators, sloppy code still reads yield as a name, and a realm without the option reads function* as a syntax error. An engine that #targetengine kept from a .jsx run has no generator built-ins, so a generator function called there throws a TypeError. cargo xtask test262 runs the generator folders: 509 of 549 runs pass (94 of 96 before). Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
f1f0911ddb
commit
30eb12aba3
20 files changed
+1312
-53
No files matched your search
@@ -331,6 +331,33 @@ fn a_js_script_reads_ecmascript_2015_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);
|
||||
}
|
||||
|
||||
/// A new empty folder for test `name`.
|
||||
fn fresh_folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
|
||||
|
||||
@@ -218,6 +218,12 @@ pub enum Expr {
|
||||
/// `...expression` in an array literal or an argument list, and as the last of an arrow
|
||||
/// function's parenthesized parameters while they are read.
|
||||
Spread(ExprId),
|
||||
/// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's
|
||||
/// body (ECMA-262 2015 section 14.4).
|
||||
Yield {
|
||||
arg: Option<ExprId>,
|
||||
delegate: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// A piece of a template literal's text between its substitutions.
|
||||
@@ -393,6 +399,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,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
//! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex
|
||||
//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with
|
||||
//! `Boolean.prototype`'s `toString` and `valueOf`. `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;
|
||||
@@ -148,6 +150,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)?;
|
||||
@@ -355,7 +358,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value {
|
||||
}
|
||||
|
||||
fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
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<Value> {
|
||||
@@ -476,7 +479,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<Value> {
|
||||
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<Value> {
|
||||
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());
|
||||
@@ -488,12 +497,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','));
|
||||
@@ -513,8 +522,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)),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! The generator built-ins (ECMA-262 11th edition, <https://262.ecma-international.org/11.0/>):
|
||||
//! `%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<Value> {
|
||||
super::create_dynamic_function(interp, args, true)
|
||||
}
|
||||
@@ -78,7 +78,7 @@ fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Va
|
||||
}
|
||||
|
||||
/// CreateIterResultObject (section 7.4.7): `{ value, done }`.
|
||||
fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult<Value> {
|
||||
pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult<Value> {
|
||||
interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES))?;
|
||||
let proto = interp.intrinsics.object_proto;
|
||||
let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)));
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -205,6 +205,29 @@ pub(crate) enum Op {
|
||||
ToStr,
|
||||
/// Pushes the template object of `templates[i]`, the same object for each evaluation.
|
||||
TemplateObject(u32),
|
||||
/// 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).
|
||||
GetIterator,
|
||||
/// `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`].
|
||||
@@ -299,6 +322,9 @@ pub(crate) struct Code {
|
||||
/// The function has default or rest parameters: its parameters start uninitialized, its
|
||||
/// code initializes them and then enters its body with [`Op::BodyEnv`].
|
||||
pub(crate) param_init: bool,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
@@ -381,6 +407,12 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
|
||||
Op::ArraySpread | Op::NewSpread => e(2, 1),
|
||||
Op::CallSpread(_) => e(3, 1),
|
||||
Op::ToStr => e(1, 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::GetIterator => 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)] },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -415,6 +447,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(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,8 @@ struct FnCompiler<'a> {
|
||||
block_funcs: HashSet<StmtId>,
|
||||
/// The function declarations in blocks whose names are also var-scoped (Annex B.3.3).
|
||||
annex: HashSet<StmtId>,
|
||||
/// The code is a generator function's.
|
||||
generator: bool,
|
||||
}
|
||||
|
||||
/// The `var` names and function declarations a body hoists.
|
||||
@@ -146,6 +148,7 @@ impl<'a> FnCompiler<'a> {
|
||||
top_funcs: HashSet::new(),
|
||||
block_funcs: HashSet::new(),
|
||||
annex: HashSet::new(),
|
||||
generator: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,12 +271,13 @@ impl<'a> FnCompiler<'a> {
|
||||
Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))),
|
||||
Stmt::Lexical(..) => {}
|
||||
Stmt::FunctionDecl(fid) => {
|
||||
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
|
||||
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 {
|
||||
@@ -1195,10 +1199,73 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::XmlScopeGet);
|
||||
}
|
||||
Expr::XmlDescendants { .. } | Expr::XmlFilter { .. } => self.chain(id)?,
|
||||
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::GetIterator);
|
||||
// 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<()> {
|
||||
@@ -1718,7 +1785,11 @@ impl<'a> FnCompiler<'a> {
|
||||
| Op::JumpIfFalseKeep(t)
|
||||
| Op::JumpIfTrueKeep(t)
|
||||
| Op::ForInNext(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"),
|
||||
}
|
||||
@@ -1762,6 +1833,7 @@ impl<'a> FnCompiler<'a> {
|
||||
arrow: meta.arrow,
|
||||
uses_this: self.uses_this,
|
||||
param_init: meta.param_init,
|
||||
generator: self.generator,
|
||||
};
|
||||
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
|
||||
Ok(Rc::new(code))
|
||||
@@ -1792,6 +1864,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
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()?;
|
||||
let params: Vec<Key> = f.params.iter().map(|p| key_of(&p.name)).collect();
|
||||
@@ -1828,6 +1901,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
//! Generator objects (ECMA-262 11th edition, <https://262.ecma-international.org/11.0/>,
|
||||
//! 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<Self> {
|
||||
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<Code>,
|
||||
pc: usize,
|
||||
pub(crate) env: EnvId,
|
||||
pub(crate) var_env: EnvId,
|
||||
env_depth: u32,
|
||||
pub(crate) this: Value,
|
||||
pub(crate) callee: Option<ObjId>,
|
||||
pub(crate) completion: Value,
|
||||
pub(crate) stack: Vec<Value>,
|
||||
/// [`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<ObjId>) {
|
||||
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<Option<Value>> {
|
||||
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<Option<Value>> {
|
||||
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<Option<Value>> {
|
||||
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)?;
|
||||
}
|
||||
let frame = self.frame()?;
|
||||
let held = (self.stack.len().saturating_sub(frame.base)).saturating_add(self.finally_sites.len()).saturating_add(self.finally_marks.len());
|
||||
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<Prepared> {
|
||||
// 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<Option<Value>> {
|
||||
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::GetIterator`](crate::bytecode::Op::GetIterator): `value` → `iterator next`.
|
||||
pub(crate) fn op_get_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(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! 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 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(); try { it.throw(1); } catch (e) {} !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");
|
||||
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 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}");
|
||||
}
|
||||
|
||||
#[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 body does no work.
|
||||
let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() });
|
||||
match realm.run("var it = (function* () {})(); it.next(); while (true) it.next();") {
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// 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)));
|
||||
}
|
||||
+23
-1
@@ -171,6 +171,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
|
||||
@@ -231,6 +233,8 @@ pub(crate) enum Class {
|
||||
Symbol(crate::symbol::Sym),
|
||||
/// An Array Iterator or a String Iterator and how far it has gone (sections 22.1.5 and 21.1.5).
|
||||
Iterator(Box<crate::builtins::iterator::IterState>),
|
||||
/// A generator object and its state (ECMA-262 11th edition, section 25.4).
|
||||
Generator(Box<crate::generator::GenState>),
|
||||
ForIn(Box<ForIn>),
|
||||
/// The `Math` object (section 15.8).
|
||||
Math,
|
||||
@@ -316,7 +320,7 @@ impl Class {
|
||||
Class::XmlFilter(_) => "Object",
|
||||
Class::Math => "Math",
|
||||
Class::Json => "JSON",
|
||||
Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) => "Object",
|
||||
Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) | Class::Generator(_) => "Object",
|
||||
Class::Array { .. } => "Array",
|
||||
Class::Function(_) => "Function",
|
||||
Class::Error(_) => "Error",
|
||||
@@ -717,6 +721,24 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, 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);
|
||||
|
||||
+67
-16
@@ -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
|
||||
@@ -49,7 +51,7 @@ pub(crate) type JsResult<T> = Result<T, Abrupt>;
|
||||
/// with a NUL, which no identifier holds.
|
||||
const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73];
|
||||
|
||||
fn internal<T>(message: &str) -> JsResult<T> {
|
||||
pub(crate) fn internal<T>(message: &str) -> JsResult<T> {
|
||||
Err(Abrupt::Internal(message.into()))
|
||||
}
|
||||
|
||||
@@ -173,22 +175,24 @@ pub(crate) struct Frame {
|
||||
pub(crate) code: Rc<Code>,
|
||||
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<ObjId>,
|
||||
pub(crate) env_depth: u32,
|
||||
pub(crate) this: Value,
|
||||
pub(crate) callee: Option<ObjId>,
|
||||
/// The object `new` made, returned unless the function returns an object.
|
||||
construct: Option<ObjId>,
|
||||
completion: Value,
|
||||
pub(crate) construct: Option<ObjId>,
|
||||
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<ObjId>,
|
||||
}
|
||||
|
||||
/// Where the exception being thrown was raised: the code and the instruction.
|
||||
type ThrowSite = (Rc<Code>, usize);
|
||||
pub(crate) type ThrowSite = (Rc<Code>, usize);
|
||||
|
||||
/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time.
|
||||
pub(crate) type CodeObserver = Rc<dyn Fn(&[u16])>;
|
||||
@@ -450,7 +454,7 @@ fn declaration_bytes(code: &Code) -> usize {
|
||||
}
|
||||
|
||||
/// A call to a function written in JavaScript, ready to enter.
|
||||
struct Entry {
|
||||
pub(crate) struct Entry {
|
||||
callee: ObjId,
|
||||
code: Rc<Code>,
|
||||
env: EnvId,
|
||||
@@ -459,9 +463,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<crate::generator::Resumed>),
|
||||
}
|
||||
|
||||
/// A variable found in the environment chain.
|
||||
@@ -762,7 +768,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));
|
||||
@@ -788,7 +794,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);
|
||||
@@ -872,6 +878,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),
|
||||
}
|
||||
}
|
||||
@@ -926,6 +934,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));
|
||||
@@ -942,6 +951,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;
|
||||
}
|
||||
@@ -949,8 +959,15 @@ impl Interp {
|
||||
}
|
||||
|
||||
fn return_value(&mut self, v: Value) -> JsResult<Option<Value>> {
|
||||
// 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 {
|
||||
@@ -1102,7 +1119,12 @@ impl Interp {
|
||||
self.replace(1, Value::String(s))
|
||||
}
|
||||
Op::TemplateObject(i) => self.op_template_object(i),
|
||||
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
|
||||
Op::Resume(t) => self.op_resume(t),
|
||||
Op::GetIterator => self.op_get_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"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2103,7 +2125,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;
|
||||
@@ -2114,6 +2137,17 @@ impl Interp {
|
||||
if arrow {
|
||||
return Ok(f);
|
||||
}
|
||||
// A generator function's `prototype` 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 Some((_, generator_proto)) = 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);
|
||||
}
|
||||
let p = self.new_object();
|
||||
self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?;
|
||||
self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?;
|
||||
@@ -2567,6 +2601,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;
|
||||
@@ -2689,6 +2728,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2709,6 +2752,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, env }) => {
|
||||
let Some(callee) = f.as_object() else { return internal("callee is not an object") };
|
||||
let proto = match self.get_from(callee, &key("prototype"), &f)? {
|
||||
@@ -2785,6 +2829,7 @@ impl Interp {
|
||||
construct,
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -3009,6 +3054,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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3207,6 +3257,7 @@ impl Interp {
|
||||
construct: None,
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -983,6 +983,7 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
arrow: false,
|
||||
uses_this: false,
|
||||
param_init: false,
|
||||
generator: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+14
-2
@@ -54,8 +54,17 @@
|
||||
//! functions (section 14.2), template literals and tagged templates (sections 12.2.9 and
|
||||
//! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and
|
||||
//! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays, strings (by code point) and objects
|
||||
//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, classes,
|
||||
//! generators and modules stay syntax errors.
|
||||
//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, 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,
|
||||
//! <https://262.ecma-international.org/11.0/>): `Symbol.for` and `Symbol.keyFor` over a registry
|
||||
@@ -80,6 +89,7 @@ mod compiler;
|
||||
mod date_builtins;
|
||||
mod error;
|
||||
mod file_classes;
|
||||
mod generator;
|
||||
mod heap;
|
||||
mod host;
|
||||
mod interp;
|
||||
@@ -241,6 +251,8 @@ mod es2015_tests;
|
||||
#[cfg(test)]
|
||||
mod extension_tests;
|
||||
#[cfg(test)]
|
||||
mod generator_tests;
|
||||
#[cfg(test)]
|
||||
mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
|
||||
+139
-17
@@ -36,6 +36,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
|
||||
@@ -101,6 +104,9 @@ pub(crate) struct Parser<'s> {
|
||||
es2015: bool,
|
||||
/// The scopes open around the current token, outermost first (only with `es2015`).
|
||||
scopes: Vec<Scope>,
|
||||
/// 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<u32>,
|
||||
}
|
||||
|
||||
impl<'s> Parser<'s> {
|
||||
@@ -125,6 +131,7 @@ impl<'s> Parser<'s> {
|
||||
e4x: options.e4x,
|
||||
es2015: options.es2015,
|
||||
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
yields: Vec::new(),
|
||||
};
|
||||
parser.tok = parser.next_significant()?;
|
||||
Ok(parser)
|
||||
@@ -266,9 +273,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<Name> {
|
||||
@@ -341,7 +357,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) {
|
||||
@@ -350,7 +366,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(()),
|
||||
}
|
||||
}
|
||||
@@ -507,6 +524,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),
|
||||
@@ -960,8 +980,9 @@ impl<'s> Parser<'s> {
|
||||
|
||||
fn parse_function_declaration(&mut self) -> Result<StmtId> {
|
||||
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)))
|
||||
}
|
||||
|
||||
@@ -977,15 +998,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<crate::ast::FunctionId> {
|
||||
/// 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<crate::ast::FunctionId> {
|
||||
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<crate::ast::FunctionId> {
|
||||
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result<crate::ast::FunctionId> {
|
||||
let params_start = self.tok.span.start;
|
||||
self.expect(Punct::LParen)?;
|
||||
let mut params: Vec<Name> = Vec::new();
|
||||
let mut defaults: Vec<Option<ExprId>> = Vec::new();
|
||||
@@ -1010,6 +1044,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"));
|
||||
@@ -1025,7 +1063,7 @@ impl<'s> Parser<'s> {
|
||||
self.expect(Punct::LBrace)?;
|
||||
let names: Vec<String> = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
|
||||
let outer_strict = self.ctx.strict;
|
||||
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
|
||||
let 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);
|
||||
@@ -1034,7 +1072,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))
|
||||
}
|
||||
@@ -1066,7 +1104,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)))
|
||||
@@ -1181,10 +1220,15 @@ impl<'s> Parser<'s> {
|
||||
fn assignment(&mut self, no_in: bool) -> Result<ExprId> {
|
||||
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() {
|
||||
@@ -1199,10 +1243,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<ExprId> {
|
||||
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<ExprId> {
|
||||
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![Name { name: name.clone(), span: start }], vec![None], None),
|
||||
Some(Expr::Paren(_)) => self.arrow_params(expr)?,
|
||||
@@ -1523,8 +1585,13 @@ impl<'s> Parser<'s> {
|
||||
|
||||
fn parse_function_expression(&mut self) -> Result<ExprId> {
|
||||
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)))
|
||||
}
|
||||
|
||||
@@ -1575,17 +1642,36 @@ 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) });
|
||||
}
|
||||
let key = PropertyKey::Ident(word.ident().unwrap_or_default().to_string());
|
||||
return self.property_value(key, start);
|
||||
}
|
||||
if self.es2015 && self.eat(Punct::Star)? {
|
||||
return self.generator_method(start);
|
||||
}
|
||||
let (key, _) = self.parse_property_key()?;
|
||||
self.property_value(key, start)
|
||||
}
|
||||
|
||||
/// `*name(…) {…}` after the `*`: a generator method (ECMA-262 2015 section 14.4), the value of
|
||||
/// the property `name`. Its parameter names are distinct (section 14.3.1), and it has no name
|
||||
/// binding of its own.
|
||||
fn generator_method(&mut self, start: Span) -> Result<Property> {
|
||||
let (key, _) = self.parse_property_key()?;
|
||||
let id = self.parse_function_rest(FunctionKind::Expression, None, start, true)?;
|
||||
if let Some(f) = self.ast.function(id) {
|
||||
let mut seen = HashSet::new();
|
||||
if let Some(p) = f.params.iter().chain(&f.rest).find(|p| !seen.insert(p.name.as_str())) {
|
||||
return Err(self.error_at_offset(p.span.start, format!("duplicate parameter name '{}'", p.name)));
|
||||
}
|
||||
}
|
||||
let value = self.ast.push_expr(Expr::Function(id), self.span_from(start));
|
||||
Ok(Property { key, value: PropertyValue::Init(value), span: self.span_from(start) })
|
||||
}
|
||||
|
||||
/// `: value` after a data property's name.
|
||||
fn property_value(&mut self, key: PropertyKey, start: Span) -> Result<Property> {
|
||||
self.expect(Punct::Colon)?;
|
||||
@@ -1614,6 +1700,42 @@ fn property_key(token: &Token) -> Option<PropertyKey> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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"
|
||||
}
|
||||
|
||||
@@ -296,6 +296,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();
|
||||
|
||||
+15
-1
@@ -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<ObjId> {
|
||||
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.
|
||||
|
||||
@@ -44,6 +44,10 @@
|
||||
//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and
|
||||
//! that parse as ES5. Its failures go to `symbol-failures.txt`.
|
||||
//!
|
||||
//! Another reads and runs the tests of generator functions, `yield` and the generator objects (the
|
||||
//! folders [`GENERATOR_FOLDERS`] names) in a realm with [`Options::es2015`], negative parse tests
|
||||
//! included. 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.
|
||||
@@ -910,6 +914,102 @@ fn run_symbol_built_ins(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();
|
||||
}
|
||||
|
||||
/// Runs the tests under each folder [`GENERATOR_FOLDERS`] names in a realm with
|
||||
/// [`Options::es2015`]: those whose feature tags are all `generators` or in [`ES2015_FEATURES`] or
|
||||
/// [`SYMBOL_FEATURES`]. A negative parse test must give a `SyntaxError`; the others run as
|
||||
/// [`run_tagged_tests`] runs them. 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 harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
|
||||
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
|
||||
let allowed = |f: &str| f == "generators" || ES2015_FEATURES.contains(&f) || SYMBOL_FEATURES.contains(&f);
|
||||
let mut all = RunCounts::default();
|
||||
let mut report = String::new();
|
||||
for folder in GENERATOR_FOLDERS {
|
||||
let root = or_fail(inside(dir, &format!("test/{folder}")));
|
||||
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
|
||||
let mut counts = RunCounts::default();
|
||||
for path in or_fail(test_files(&root)) {
|
||||
let source = or_fail(read_source(&path));
|
||||
let meta = meta(&source);
|
||||
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
|
||||
let expect_error = meta.negative_phase.as_deref() == Some("parse");
|
||||
let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
|
||||
if has("module")
|
||||
|| has("async")
|
||||
|| meta.negative_phase.as_deref() == Some("resolution")
|
||||
|| !meta.features.iter().all(|f| allowed(f))
|
||||
|| (!expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &options))
|
||||
{
|
||||
counts.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
counts.tests += 1;
|
||||
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
|
||||
for &strict in modes(&meta) {
|
||||
let mode = if strict { "strict" } else { "sloppy" };
|
||||
if expect_error {
|
||||
let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() };
|
||||
if parse(&text, &options).is_ok() {
|
||||
counts.failed += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): parsed; a SyntaxError was expected\n"));
|
||||
} else {
|
||||
counts.passed += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
|
||||
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
|
||||
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
|
||||
match std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), &options)) {
|
||||
Ok(Ok(())) => counts.passed += 1,
|
||||
Ok(Err(why)) => {
|
||||
counts.failed += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): {why}\n"));
|
||||
}
|
||||
Err(_) => {
|
||||
counts.failed += 1;
|
||||
counts.panicked += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
|
||||
/// Runs the script tests under `root` of any edition whose feature tags are all in `features`,
|
||||
/// each in a new realm made with `options` after the harness, the way [`run_tests`] runs the
|
||||
/// others. A test with another tag is counted as skipped.
|
||||
|
||||
+10
-2
@@ -2622,9 +2622,17 @@ not UTF-8. The language is ES5.1, except that identifiers take the characters Un
|
||||
declarations scoped to their block, arrow functions, template literals and tagged templates, default and rest
|
||||
parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects
|
||||
with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own
|
||||
until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and
|
||||
until iterators are added. 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. The script reaches the
|
||||
`.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. The script reaches the
|
||||
app through the global object `vc`, and writes to the Script Console and runs other files through `$`:
|
||||
|
||||
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
|
||||
|
||||
@@ -1079,11 +1079,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`.
|
||||
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
|
||||
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
|
||||
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. 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 without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, 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, `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 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: 509 of 549 runs of 296 tests pass (94 of 96 runs of 50 tests passed before), and the 40 others expect a configurable function `length`, a function `name` property and 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 <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`.
|
||||
- With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`.
|
||||
- `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `<!DOCTYPE>` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`.
|
||||
|
||||
Reference in new issue
Block a user