From 8d12b37da2401a55037f8e37379be2a0c6daf91b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:09:15 -0800 Subject: [PATCH 1/7] JavaScript: Symbol and the iterators of arrays, strings and arguments in ES2015 realms With Options::es2015 set, a vectorcraft-js realm has Symbol (ECMA-262 11th edition, section 19.4): Symbol(description), which new refuses, 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 them in the order they were added, defineProperty, getOwnPropertyDescriptor, freeze, seal, in, delete and hasOwnProperty take them, and for-in, Object.keys, 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 throws a TypeError. Symbol.iterator, asyncIterator, hasInstance, toPrimitive and toStringTag are defined. Conversion to a primitive calls @@toPrimitive, instanceof calls @@hasInstance, and Object.prototype.toString writes a string @@toStringTag. Array.prototype.values (also @@iterator), keys and entries, String.prototype[@@iterator] (by code point) and every arguments object's @@iterator return iterators with next(). An Array Iterator's next keeps its object reachable while a length getter or valueOf runs script. Each iterator step takes fuel, and each Symbol and registry entry counts against the heap limit. An error about a Symbol-keyed property names the Symbol by at most 256 units of its description, built only when the error is thrown. String(symbol), symbol.toString() and the [object tag] of Object.prototype.toString charge their copies to the heap and fuel first. Realms without the option, including the one the app runs scripts in, are unchanged. for-of, spread and destructuring are not part of this change. cargo xtask test262 runs the suite's Symbol, ArrayIteratorPrototype, StringIteratorPrototype, getOwnPropertySymbols, Array.prototype values/keys/entries/Symbol.iterator and String.prototype[Symbol.iterator] tests in such a realm: 164 of 216 runs pass (6 before). The 52 others expect a configurable function length and a function name property. --- crates/js/src/builtins.rs | 28 +- crates/js/src/builtins/extensions.rs | 8 +- crates/js/src/builtins/iterator.rs | 224 +++++++++++ crates/js/src/builtins/json.rs | 6 +- crates/js/src/builtins/object.rs | 35 +- crates/js/src/builtins/symbol.rs | 161 ++++++++ crates/js/src/heap.rs | 47 ++- crates/js/src/host.rs | 1 + crates/js/src/interp.rs | 126 ++++-- crates/js/src/lib.rs | 20 +- crates/js/src/realm.rs | 4 +- crates/js/src/string_builtins.rs | 2 + crates/js/src/symbol.rs | 581 +++++++++++++++++++++++++++ crates/js/src/symbol_tests.rs | 230 +++++++++++ crates/js/src/value.rs | 29 +- crates/js/tests/test262.rs | 116 +++++- docs/mcp.md | 4 + docs/target-app-parity.md | 1 + 18 files changed, 1557 insertions(+), 66 deletions(-) create mode 100644 crates/js/src/builtins/iterator.rs create mode 100644 crates/js/src/builtins/symbol.rs create mode 100644 crates/js/src/symbol.rs create mode 100644 crates/js/src/symbol_tests.rs diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..b8c21bbc64 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,7 +3,8 @@ //! `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. +//! 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`). //! //! 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,9 +13,11 @@ mod array; pub(crate) mod extensions; mod global; +pub(crate) mod iterator; mod json; mod math; mod object; +mod symbol; use std::rc::Rc; @@ -142,6 +145,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { crate::number_builtins::install(interp)?; crate::regexp_builtins::install(interp)?; crate::date_builtins::install(interp)?; + if interp.options.es2015 { + symbol::install(interp, object)?; + iterator::install(interp)?; + } if interp.options.e4x { crate::xml_builtins::install(interp)?; } @@ -370,7 +377,9 @@ fn object_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResu interp.to_object(&v).map(Value::Object) } -/// `Object.prototype.toString` (section 15.2.4.2). +/// `Object.prototype.toString` (section 15.2.4.2). In a realm with [`crate::Options::es2015`], a +/// string `@@toStringTag` takes the place of the class name (ECMA-262 11th edition, section +/// 19.1.3.6). fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { // With `$.localize` on, a localization object gives its text for the current locale. if interp.localization.enabled() @@ -384,6 +393,13 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Value::Null => "Null", _ => { let o = interp.to_object(&this)?; + // The tag's getter can run script that collects, and the object of a primitive is + // reachable from nowhere else. + let tag = interp.rooted(&[Value::Object(o)], |i| i.string_tag_of(o))?; + if let Some(tag) = tag { + let roots = [Value::String(tag.clone())]; + return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]")); + } interp.heap.object(o).map_or("Object", |o| o.class.name()) } }; @@ -431,9 +447,9 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js } fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some())) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -450,9 +466,9 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> } fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()))) } // ---- Function ---- diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..b32fecdcb5 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -235,6 +235,7 @@ impl Source { } Value::String(s) => self.quoted(interp, &s.flat()), Value::Object(id) => self.object(interp, *id), + Value::Symbol(_) => Err(interp.type_error("toSource: a Symbol cannot be written as source")), } } @@ -280,13 +281,18 @@ impl Source { // only, so an array with other properties, an object with another prototype and a property // that is not enumerable are refused. let enumerable = o.props.iter().all(|(_, p)| p.enumerable()); + let has_symbols = o.syms.as_ref().is_some_and(|m| m.len() > 0); let shape = match &o.class { Class::Array { length, .. } - if o.proto == Some(array_proto) && enumerable && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => + if o.proto == Some(array_proto) + && enumerable + && !has_symbols + && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => { Some(Err(*length)) } Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)), + Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")), Class::Ordinary if o.proto == Some(object_proto) && enumerable => { Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::>())) } diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs new file mode 100644 index 0000000000..317b66ecc2 --- /dev/null +++ b/crates/js/src/builtins/iterator.rs @@ -0,0 +1,224 @@ +//! The iterators of arrays, strings and `arguments` objects (ECMA-262 11th edition, +//! ): `%IteratorPrototype%` (section 25.1.2), +//! `%ArrayIteratorPrototype%` with `Array.prototype.values`, `keys`, `entries` and `@@iterator` +//! (sections 22.1.3 and 22.1.5), `%StringIteratorPrototype%` with `String.prototype[@@iterator]` +//! (sections 21.1.3.29 and 21.1.5), which steps by code point, and the `@@iterator` of every +//! `arguments` object (section 9.4.4). Installed in a realm with [`crate::Options::es2015`] only. +//! +//! An iterator's `next` takes a unit of fuel for each step. An Array Iterator reads its object's +//! `length` at every step, so elements added while it runs are visited, and it lets go of the +//! object once it is done. + +use super::{create_at, data, native, new_array, new_string}; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key}; +use crate::interp::{Interp, JsResult}; +use crate::value::{Str, Value, number_to_str}; + +/// What an Array Iterator gives at each step (section 22.1.5.1). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ArrayKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. The object or string is `None` once the iterator is done. +#[derive(Clone)] +pub(crate) enum IterState { + /// [[IteratedObject]], [[ArrayIteratorNextIndex]] and [[ArrayIterationKind]]. + Array { target: Option, next: f64, kind: ArrayKind }, + /// [[IteratedString]], flat, and [[StringIteratorNextIndex]] in code units. + String { text: Option, pos: usize }, +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let Some(wk) = interp.symbols.well_known.as_ref() else { return Ok(()) }; + let (iterator, to_string_tag) = (wk.iterator.clone(), wk.to_string_tag.clone()); + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + super::symbol::sym_method(interp, iterator_proto, iterator.clone(), "[Symbol.iterator]", return_this, 0, HIDDEN)?; + + let array_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, array_iterator_proto, "next", array_iterator_next, 0)?; + interp.define_sym(array_iterator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Array Iterator"), flags: CONFIGURABLE })?; + + let string_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, string_iterator_proto, "next", string_iterator_next, 0)?; + interp.define_sym(string_iterator_proto, to_string_tag, Prop::Data { value: Value::str("String Iterator"), flags: CONFIGURABLE })?; + + let array_proto = interp.intrinsics.array_proto; + let values = native(interp, "values", array_values, 0, crate::heap::NativeKind::Plain, false)?; + data(interp, array_proto, "values", Value::Object(values), HIDDEN)?; + interp.define_sym(array_proto, iterator.clone(), Prop::Data { value: Value::Object(values), flags: HIDDEN })?; + super::method(interp, array_proto, "keys", array_keys, 0)?; + super::method(interp, array_proto, "entries", array_entries, 0)?; + + let string_proto = interp.intrinsics.string_proto; + super::symbol::sym_method(interp, string_proto, iterator, "[Symbol.iterator]", string_iterator, 0, HIDDEN)?; + + objects.array_iterator_proto = array_iterator_proto; + objects.string_iterator_proto = string_iterator_proto; + objects.array_values = values; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// Gives a new `arguments` object its `@@iterator`, `%ArrayProto_values%` (section 9.4.4.6, +/// step 20, and section 9.4.4.7, step 7), in a realm that has it. +pub(crate) fn define_arguments_iterator(interp: &mut Interp, a: ObjId) -> JsResult<()> { + let (Some(objects), Some(sym)) = (interp.symbols.objects, interp.well_known(|w| &w.iterator)) else { return Ok(()) }; + interp.define_sym(a, sym, Prop::Data { value: Value::Object(objects.array_values), flags: HIDDEN }) +} + +/// `%IteratorPrototype%[@@iterator]()` (section 25.1.2.1): the iterator itself. +fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(this) +} + +/// CreateIterResultObject (section 7.4.7): `{ value, done }`. +fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + 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))); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new iterator object with `state`, its target kept reachable while it is made. +fn new_iterator(interp: &mut Interp, proto: ObjId, state: IterState, root: Value) -> JsResult { + interp.rooted(&[root], |i| i.reserve_heap(OBJECT_BYTES))?; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Iterator(Box::new(state)), Some(proto))))) +} + +/// CreateArrayIterator (section 22.1.5.1) for `ToObject(this)`. +fn create_array_iterator(interp: &mut Interp, this: &Value, kind: ArrayKind) -> JsResult { + let o = interp.to_object(this)?; + let Some(proto) = interp.symbols.objects.map(|o| o.array_iterator_proto) else { return Ok(Value::Undefined) }; + new_iterator(interp, proto, IterState::Array { target: Some(o), next: 0.0, kind }, Value::Object(o)) +} + +/// `Array.prototype.values()` (section 22.1.3.32), which is also `Array.prototype[@@iterator]`. +fn array_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Values) +} + +/// `Array.prototype.keys()` (section 22.1.3.16). +fn array_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Keys) +} + +/// `Array.prototype.entries()` (section 22.1.3.4). +fn array_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Entries) +} + +/// `String.prototype[@@iterator]()` (section 21.1.3.29). +fn string_iterator(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + if this.is_nullish() { + return Err(interp.type_error("String.prototype[Symbol.iterator] was called on null or undefined")); + } + let s = interp.to_str(&this)?; + let flat = Str::from_rc(crate::string_builtins::flat_charged(interp, &s)?); + let Some(proto) = interp.symbols.objects.map(|o| o.string_iterator_proto) else { return Ok(Value::Undefined) }; + let root = Value::String(flat.clone()); + new_iterator(interp, proto, IterState::String { text: Some(flat), pos: 0 }, root) +} + +/// The state of the iterator `this`, or a `TypeError` naming `what` when `this` is not one. +fn state_of<'a>(interp: &'a mut Interp, this: &Value, string: bool, what: &str) -> JsResult<&'a mut IterState> { + let ok = match this { + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Iterator(s)) => matches!(**s, IterState::String { .. }) == string, + _ => false, + }, + _ => false, + }; + if !ok { + return Err(interp.type_error(&format!("{what}.next was called on a value that is not an {what}"))); + } + match this.as_object().and_then(|o| interp.heap.object_mut(o)).map(|x| &mut x.class) { + Some(Class::Iterator(s)) => Ok(s), + _ => Err(crate::interp::Abrupt::Internal("iterator state went missing".into())), + } +} + +/// ToLength (section 7.1.20). +fn to_length(interp: &mut Interp, v: &Value) -> JsResult { + let n = interp.to_number(v)?; + if n.is_nan() || n <= 0.0 { + return Ok(0.0); + } + Ok(n.trunc().min(9_007_199_254_740_991.0)) +} + +/// `%ArrayIteratorPrototype%.next()` (section 22.1.5.2.1). +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let IterState::Array { target, next, kind } = *state_of(interp, &this, false, "Array Iterator")? else { + return Err(crate::interp::Abrupt::Internal("not an Array Iterator".into())); + }; + interp.use_fuel()?; + let Some(a) = target else { return iter_result(interp, Value::Undefined, true) }; + // Reading `length` and the element can run script that collects, and that script can finish + // the iterator, which then no longer holds the object. + let roots = [this.clone(), Value::Object(a)]; + interp.rooted(&roots, |interp| array_step(interp, &this, a, next, kind)) +} + +/// One step of an Array Iterator over `a` at index `next`, with `this` and `a` kept reachable. +fn array_step(interp: &mut Interp, this: &Value, a: ObjId, next: f64, kind: ArrayKind) -> JsResult { + let len = interp.get_from(a, &key("length"), &Value::Object(a))?; + let len = to_length(interp, &len)?; + if next >= len { + if let IterState::Array { target, .. } = state_of(interp, this, false, "Array Iterator")? { + *target = None; + } + return iter_result(interp, Value::Undefined, true); + } + if let IterState::Array { next: n, .. } = state_of(interp, this, false, "Array Iterator")? { + *n = next + 1.0; + } + let index = Value::Number(next); + let value = match kind { + ArrayKind::Keys => index, + ArrayKind::Values | ArrayKind::Entries => { + let k = number_to_str(next).flat(); + let v = interp.get_from(a, &k, &Value::Object(a))?; + if kind == ArrayKind::Values { + v + } else { + let pair = interp.rooted(std::slice::from_ref(&v), |i| new_array(i, 0))?; + interp.rooted(&[Value::Object(pair), v.clone()], |i| { + create_at(i, pair, 0.0, index)?; + create_at(i, pair, 1.0, v.clone()) + })?; + Value::Object(pair) + } + } + }; + iter_result(interp, value, false) +} + +/// `%StringIteratorPrototype%.next()` (section 21.1.5.2.1): the next code point, a surrogate +/// pair kept together and a lone surrogate given alone. +fn string_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + interp.use_fuel()?; + let state = state_of(interp, &this, true, "String Iterator")?; + let IterState::String { text, pos } = state else { return Err(crate::interp::Abrupt::Internal("not a String Iterator".into())) }; + let Some(s) = text.as_ref() else { return iter_result(interp, Value::Undefined, true) }; + let units = s.flat(); + let Some(&first) = units.get(*pos) else { + *text = None; + return iter_result(interp, Value::Undefined, true); + }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(*pos + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let width = if pair { 2 } else { 1 }; + let piece = units.get(*pos..*pos + width).map(<[u16]>::to_vec).unwrap_or_default(); + *pos += width; + interp.rooted(std::slice::from_ref(&this), |interp| { + let v = new_string(interp, piece)?; + iter_result(interp, v, false) + }) +} diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 364ec99696..6f659922b2 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -556,7 +556,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K } } Ok(match v { - Value::Undefined => Item::Skip, + Value::Undefined | Value::Symbol(_) => Item::Skip, Value::Object(_) if interp.is_callable(&v) => Item::Skip, Value::Object(o) => Item::Container(o), other => Item::Primitive(other), @@ -579,7 +579,7 @@ fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult }; let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? }; - Ok(Some(if string { Value::String(interp.primitive_to_str(&p)) } else { Value::Number(interp.to_number(&p)?) })) + Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } /// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before @@ -637,7 +637,7 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul let units = flat_charged(i, s)?; write_quoted(i, out, &units) }), - Value::Undefined | Value::Object(_) => Ok(()), + Value::Undefined | Value::Object(_) | Value::Symbol(_) => Ok(()), } } diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..48fdbb6eda 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -7,6 +7,7 @@ use super::{ELEMENT_BYTES, arg, create_at, method, new_array}; use crate::heap::{CONFIGURABLE, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; +use crate::symbol::PropKey; use crate::value::{Str, Value}; pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> { @@ -119,6 +120,14 @@ fn names_array(interp: &mut Interp, names: Vec) -> JsResult { }) } +/// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section +/// 9.1.11). +fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult> { + let mut keys: Vec = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect(); + keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); + Ok(keys) +} + /// `Object.getPrototypeOf` (section 15.2.3.2). fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; @@ -129,8 +138,8 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let k = interp.to_key(&arg(args, 1))?; - match interp.get_own_property(o, &k)? { + let k = interp.to_prop_key(&arg(args, 1))?; + match interp.get_own_pk(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -166,10 +175,10 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; - interp.with_key(&arg(args, 1), |interp, k| { + interp.with_prop_key(&arg(args, 1), |interp, k| { let desc = to_desc(interp, &arg(args, 2))?; let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true)) + interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, true)) })?; Ok(Value::Object(o)) } @@ -189,12 +198,12 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - for k in interp.own_keys(p)? { + for k in own_prop_keys(interp, p)? { interp.use_fuel()?; - if !interp.get_own_property(p, &k)?.is_some_and(|prop| prop.enumerable()) { + if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) { continue; } - let v = interp.get_from(p, &k, &Value::Object(p))?; + let v = interp.get_value_pk(&Value::Object(p), &k)?; interp.temp_roots.push(v.clone()); let desc = to_desc(interp, &v)?; interp.temp_roots.extend(desc_values(&desc)); @@ -202,7 +211,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { } for (k, desc) in descs { interp.use_fuel()?; - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } Ok(()) })(); @@ -214,9 +223,9 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// then makes the object non-extensible (sections 15.2.3.8 and 15.2.3.9). fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; let mut desc = match &prop { Prop::Data { value, flags } => Desc::data(value.clone(), *flags), Prop::Accessor { get, set, flags } => Desc { @@ -231,7 +240,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { if freeze && desc.is_data() { desc.writable = Some(false); } - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } if let Some(obj) = interp.heap.object_mut(o) { obj.extensible = false; @@ -263,9 +272,9 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs new file mode 100644 index 0000000000..f0afe7b2f8 --- /dev/null +++ b/crates/js/src/builtins/symbol.rs @@ -0,0 +1,161 @@ +//! `Symbol` (ECMA-262 11th edition, section 19.4, ): +//! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of +//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10) and +//! `Function.prototype[@@hasInstance]` (section 19.2.3.6). Installed in a realm with +//! [`crate::Options::es2015`] only. + +use super::{arg, constructor, create_at, data, method, native, new_array}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; +use crate::interp::{Interp, JsResult}; +use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; +use crate::value::{Str, Value}; + +pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { + let well_known = WellKnown::new(); + let names = [ + ("iterator", well_known.iterator.clone()), + ("asyncIterator", well_known.async_iterator.clone()), + ("hasInstance", well_known.has_instance.clone()), + ("toPrimitive", well_known.to_primitive.clone()), + ("toStringTag", well_known.to_string_tag.clone()), + ]; + let (to_string_tag, to_primitive, has_instance) = + (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); + interp.symbols.well_known = Some(well_known); + + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let ctor = native(interp, "Symbol", symbol_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Symbol", ctor, proto)?; + method(interp, ctor, "for", symbol_for, 1)?; + method(interp, ctor, "keyFor", key_for, 1)?; + for (name, sym) in names { + data(interp, ctor, name, Value::Symbol(sym), 0)?; + } + method(interp, proto, "toString", to_string, 0)?; + method(interp, proto, "valueOf", value_of, 0)?; + let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?; + interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?; + interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?; + sym_method(interp, proto, to_primitive, "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + + 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. + interp.symbols.objects = Some(Es2015Objects { + symbol_proto: proto, + array_iterator_proto: proto, + string_iterator_proto: proto, + array_values: has_instance, + has_instance, + }); + Ok(()) +} + +/// Defines a built-in function as the property `sym` of `on`, with the attribute `flags`. +pub(super) fn sym_method(interp: &mut Interp, on: ObjId, sym: Sym, name: &'static str, f: NativeFn, length: u32, flags: u8) -> JsResult { + let m = native(interp, name, f, length, NativeKind::Plain, false)?; + interp.define_sym(on, sym, Prop::Data { value: Value::Object(m), flags })?; + Ok(m) +} + +/// A new Symbol, its bytes checked against the heap limit and charged to the heap. +fn new_symbol(interp: &mut Interp, description: Option, registered: bool, extra: usize) -> JsResult { + let bytes = SYMBOL_BYTES.saturating_add(extra); + let roots: Vec = description.iter().cloned().map(Value::String).collect(); + interp.rooted(&roots, |i| i.reserve_heap(bytes))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Sym::new(description, registered)) +} + +/// `Symbol([description])` (section 19.4.1.1). `new Symbol()` throws a `TypeError`. +fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + if construct { + return Err(interp.type_error("the value is not a constructor")); + } + let description = match arg(args, 0) { + Value::Undefined => None, + d => Some(interp.to_str(&d)?), + }; + new_symbol(interp, description, false, 0).map(Value::Symbol) +} + +/// `Symbol.for(key)` (section 19.4.2.2): the registry's Symbol for the key, made the first time. +fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let key = interp.to_str(&arg(args, 0))?; + let units = crate::string_builtins::flat_charged(interp, &key)?; + if let Some(v) = interp.symbols.registry.get(&*units) { + return Ok(v.clone()); + } + let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len())); + let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?; + interp.symbols.registry.insert(units, Value::Symbol(sym.clone())); + Ok(Value::Symbol(sym)) +} + +/// `Symbol.keyFor(sym)` (section 19.4.2.6). +fn key_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let Value::Symbol(sym) = arg(args, 0) else { return Err(interp.type_error("Symbol.keyFor was given a value that is not a Symbol")) }; + Ok(match sym.description() { + Some(d) if sym.registered() => Value::String(d.clone()), + _ => Value::Undefined, + }) +} + +/// thisSymbolValue (section 19.4.3): a Symbol, or the Symbol of a Symbol object. +fn this_symbol(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let sym = match this { + Value::Symbol(s) => Some(s.clone()), + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Symbol(s)) => Some(s.clone()), + _ => None, + }, + _ => None, + }; + sym.ok_or_else(|| interp.type_error(&format!("Symbol.prototype.{name} was called on a value that is not a Symbol"))) +} + +/// `Symbol.prototype.toString` (section 19.4.3.3): `Symbol(description)`. +fn to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "toString")?; + interp.descriptive_string(&sym) +} + +/// `Symbol.prototype.valueOf` (section 19.4.3.4). +fn value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "valueOf").map(Value::Symbol) +} + +/// The getter of `Symbol.prototype.description` (section 19.4.3.2). +fn description(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "description")?; + Ok(sym.description().map_or(Value::Undefined, |d| Value::String(d.clone()))) +} + +/// `Symbol.prototype[@@toPrimitive](hint)` (section 19.4.3.5). +fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol) +} + +/// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the +/// order they were added. +fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = interp.to_object(&arg(args, 0))?; + interp.rooted(&[Value::Object(o)], |interp| { + let syms = interp.own_symbols(o)?; + let a = new_array(interp, 0)?; + interp.rooted(&[Value::Object(a)], |interp| { + for (i, s) in syms.into_iter().enumerate() { + interp.use_fuel()?; + create_at(interp, a, i as f64, Value::Symbol(s))?; + } + Ok(Value::Object(a)) + }) + }) +} + +/// `Function.prototype[@@hasInstance](v)` (section 19.2.3.6): OrdinaryHasInstance. +fn function_has_instance(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + interp.ordinary_has_instance(&arg(args, 0), &this).map(Value::Bool) +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..2ee57c5fc3 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -227,6 +227,10 @@ pub(crate) enum Class { RegExp(Rc), /// A `Date` object and its time value. Date(f64), + /// A Symbol object made by ToObject, with its Symbol (ECMA-262 11th edition, section 19.4). + 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), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -312,7 +316,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -331,11 +335,13 @@ pub(crate) struct Object { pub(crate) proto: Option, pub(crate) extensible: bool, pub(crate) props: PropMap, + /// The properties whose keys are Symbols, once the object has one. + pub(crate) syms: Option>, } impl Object { pub(crate) fn new(class: Class, proto: Option) -> Self { - Self { class, proto, extensible: true, props: PropMap::default() } + Self { class, proto, extensible: true, props: PropMap::default(), syms: None } } } @@ -395,6 +401,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96; pub(crate) const XML_REF_BYTES: usize = 8; /// The estimated bytes of a namespace an XML node holds. pub(crate) const XML_NS_BYTES: usize = 48; +/// The estimated bytes of a Symbol without its description. +pub(crate) const SYMBOL_BYTES: usize = 48; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -557,16 +565,34 @@ impl StringSizes { self.bytes += string_bytes(k.len()); } } + + /// Adds a Symbol and its description, once however many values and keys share it. + fn add_symbol(&mut self, s: &crate::symbol::Sym) { + if self.seen.insert(s.addr()) { + self.bytes += SYMBOL_BYTES; + if let Some(d) = s.description() { + self.add(d); + } + } + } } fn mark_value(v: &Value, work: &mut Vec, strings: &mut StringSizes) { match v { Value::Object(o) => work.push(o.0), Value::String(s) => strings.add(s), + Value::Symbol(s) => strings.add_symbol(s), _ => {} } } +fn mark_prop(prop: &Prop, work: &mut Vec, strings: &mut StringSizes) { + match prop { + Prop::Data { value, .. } => mark_value(value, work, strings), + Prop::Accessor { get, set, .. } => work.extend(get.iter().chain(set.iter()).map(|f| f.0)), + } +} + /// The estimated bytes of `code` with the functions nested in it and its source text, for /// charging code made at run time to the heap before anything refers to it. pub(crate) fn code_bytes(code: &Code) -> usize { @@ -626,10 +652,12 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } for (k, prop) in o.props.iter() { strings.add_key(k); - match prop { - Prop::Data { value, .. } => mark_value(value, work, strings), - Prop::Accessor { get, set, .. } => work.extend(get.iter().chain(set.iter()).map(|f| f.0)), - } + mark_prop(prop, work, strings); + } + let syms = o.syms.as_ref().map_or(0, |m| m.len()); + for (k, prop) in o.syms.iter().flat_map(|m| m.iter()) { + strings.add_symbol(k); + mark_prop(prop, work, strings); } let mut extra = 0; match &o.class { @@ -656,6 +684,11 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.object.iter().map(|o| o.0)); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); } + Class::Symbol(s) => strings.add_symbol(s), + Class::Iterator(state) => match &**state { + crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), + crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), + }, Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); @@ -682,7 +715,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } _ => {} } - OBJECT_BYTES + PROP_BYTES * o.props.len() + extra + OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra } fn add_name(name: &XmlName, strings: &mut StringSizes) { diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..967d5e3656 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -243,6 +243,7 @@ impl Interp { Ok(Data::String(s.to_rust_string())) } Value::Object(id) => self.read_object(*id, r), + Value::Symbol(_) => Err(self.data_error(r, ErrorType::Type, "is a Symbol, not plain data")), } } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..13ac5cd834 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -28,6 +28,7 @@ use crate::heap::{ Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; use crate::string_builtins::flat_charged; +use crate::symbol::PropKey; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; use crate::{LimitKind, Limits, Options}; @@ -310,6 +311,9 @@ pub(crate) struct Interp { pub(crate) error_mark: Option, /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. pub(crate) strict_writes: bool, + /// The well-known Symbols, `Symbol.for`'s registry and the objects that go with them, in a + /// realm with [`crate::Options::es2015`]. + pub(crate) symbols: crate::symbol::Symbols, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -540,6 +544,7 @@ impl Interp { finally_sites: Vec::new(), error_mark: None, strict_writes: false, + symbols: crate::symbol::Symbols::default(), }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -774,12 +779,15 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.values.extend(self.symbols.root_values()); + roots.objects.extend(self.symbols.root_objects()); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); - self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()); + self.heap.bytes = + self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()).saturating_add(self.symbols.registry_bytes()); } /// Runs frames until the boundary frame on top returns, and returns its value. @@ -943,13 +951,13 @@ impl Interp { self.frame()?.code.names.get(i as usize).cloned().ok_or_else(|| Abrupt::Internal("name out of range".into())) } - fn strict(&self) -> bool { + pub(crate) fn strict(&self) -> bool { self.frames.last().is_some_and(|f| f.code.strict) } /// Does a property write the running code makes throw when it cannot be made? It does in /// strict mode code and in code from a source with [`crate::bytecode::Source::strict_writes`]. - fn strict_writes(&self) -> bool { + pub(crate) fn strict_writes(&self) -> bool { self.frames.last().is_some_and(|f| f.code.strict || f.code.source.strict_writes) } @@ -1416,12 +1424,13 @@ impl Interp { } /// The prototype a primitive's properties are looked up on. - fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult { + pub(crate) fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult { match v { Value::Object(o) => Ok(*o), Value::String(_) => Ok(self.intrinsics.string_proto), Value::Number(_) => Ok(self.intrinsics.number_proto), Value::Bool(_) => Ok(self.intrinsics.boolean_proto), + Value::Symbol(_) => Ok(self.symbols.objects.map_or(self.intrinsics.object_proto, |o| o.symbol_proto)), Value::Undefined | Value::Null => { let key = String::from_utf16_lossy(k); let base = if matches!(v, Value::Null) { "null" } else { "undefined" }; @@ -1520,7 +1529,7 @@ impl Interp { } } - fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { + pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { if throw { let key = String::from_utf16_lossy(k); return Err(self.type_error(&format!("cannot define property '{key}': {why}"))); @@ -1674,7 +1683,7 @@ impl Interp { r } - fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { + pub(crate) fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { if throw { let key = String::from_utf16_lossy(k); return Err(self.type_error(&format!("cannot assign to property '{key}': {why}"))); @@ -1780,7 +1789,7 @@ impl Interp { } /// PutValue on a property reference (section 8.7.2), whose base may be a primitive. - fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> { + pub(crate) fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> { if self.options.e4x && self.is_xml(base) { return self.xml_put(base, &Value::String(Str::from_rc(k)), &v); } @@ -1837,6 +1846,8 @@ impl Interp { let key = match k { Some(Value::String(s)) if s.len() > NAMED_KEY_UNITS => None, Some(Value::Object(_)) | None => None, + Some(Value::Symbol(s)) if s.description().is_some_and(|d| d.len() > NAMED_KEY_UNITS) => None, + Some(Value::Symbol(s)) => Some(self.sym_name(s)?), Some(k) => Some(self.to_str(k)?.to_rust_string()), }; let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; @@ -1860,8 +1871,11 @@ impl Interp { return Ok(()); } self.check_coercible(&base, Some(&k), true)?; - let name = self.to_key(&k)?; - self.replace(1, Value::String(Str::from_rc(name))) + let key = match self.to_prop_key(&k)? { + PropKey::Str(name) => Value::String(Str::from_rc(name)), + PropKey::Sym(s) => Value::Symbol(s), + }; + self.replace(1, key) } fn op_get_index(&mut self, with_this: bool) -> JsResult<()> { @@ -1878,7 +1892,7 @@ impl Interp { return self.replace(2, v); } self.check_coercible(&base, Some(&k), false)?; - let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?; + let v = self.with_prop_key(&k, |i, key| i.get_value_pk(&base, &key))?; self.replace(2, v)?; if with_this { self.push(base) } else { Ok(()) } } @@ -1891,8 +1905,8 @@ impl Interp { self.xml_put(&base, &k, &v)?; return self.replace(3, v); } - let name = self.to_key(&k)?; - self.put_value(&base, name, v.clone())?; + let key = self.to_prop_key(&k)?; + self.put_value_pk(&base, key, v.clone())?; self.replace(3, v) } @@ -1917,25 +1931,25 @@ impl Interp { return self.replace(2, Value::Bool(r)); } self.check_coercible(&base, Some(&k), false)?; - let name = self.to_key(&k)?; + let key = self.to_prop_key(&k)?; let o = self.to_object(&base)?; let strict = self.strict(); - let r = self.delete(o, &name, strict)?; + let r = self.delete_pk(o, &key, strict)?; self.replace(2, Value::Bool(r)) } - fn inc_property(&mut self, base: &Value, name: Key, prefix: bool, dec: bool) -> JsResult { - let v = self.get_value(base, &name)?; + fn inc_property(&mut self, base: &Value, key: PropKey, prefix: bool, dec: bool) -> JsResult { + let v = self.get_value_pk(base, &key)?; let old = self.to_number(&v)?; let new = if dec { old - 1.0 } else { old + 1.0 }; - self.put_value(base, name, Value::Number(new))?; + self.put_value_pk(base, key, Value::Number(new))?; Ok(Value::Number(if prefix { new } else { old })) } fn op_inc_member(&mut self, n: u32, prefix: bool, dec: bool) -> JsResult<()> { let name = self.name(n)?; let base = self.peek(0)?; - let r = self.inc_property(&base, name, prefix, dec)?; + let r = self.inc_property(&base, PropKey::Str(name), prefix, dec)?; self.replace(1, r) } @@ -1950,7 +1964,7 @@ impl Interp { return self.replace(2, Value::Number(if prefix { new } else { old })); } self.check_coercible(&base, Some(&k), false)?; - let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?; + let r = self.with_prop_key(&k, |i, key| i.inc_property(&base, key, prefix, dec))?; self.replace(2, r) } @@ -2481,6 +2495,7 @@ impl Interp { } else { self.define(a, key("callee"), Prop::Data { value: Value::Object(callee), flags: HIDDEN })?; } + crate::builtins::iterator::define_arguments_iterator(self, a)?; Ok(a) } @@ -2745,16 +2760,22 @@ impl Interp { Value::Bool(_) => "boolean", Value::Number(_) => "number", Value::String(_) => "string", + Value::Symbol(_) => "symbol", Value::Object(_) if self.options.e4x && self.is_xml(v) => "xml", Value::Object(_) if self.is_callable(v) => "function", Value::Object(_) => "object", } } - /// ToPrimitive (section 9.1) through [[DefaultValue]] (section 8.12.8). + /// ToPrimitive (section 9.1) through [[DefaultValue]] (section 8.12.8). In a realm with + /// [`crate::Options::es2015`], an object's `@@toPrimitive` method is called first when it + /// has one (ECMA-262 11th edition, section 7.1.1). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_primitive(&mut self, v: &Value, hint: Hint) -> JsResult { let Value::Object(o) = v else { return Ok(v.clone()) }; + if let Some(r) = self.exotic_to_primitive(*o, v, hint)? { + return Ok(r); + } // Without a hint, a Date object converts as with the String hint. let date = hint == Hint::Default && matches!(self.heap.object(*o).map(|ob| &ob.class), Some(Class::Date(_))); let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] }; @@ -2778,6 +2799,7 @@ impl Interp { Value::Bool(b) => f64::from(u8::from(*b)), Value::Number(n) => *n, Value::String(s) => string_to_number(&flat_charged(self, s)?), + Value::Symbol(_) => return Err(self.type_error("cannot convert a Symbol value to a number")), Value::Object(_) => { let p = self.to_primitive(v, Hint::Number)?; return self.to_number(&p); @@ -2785,7 +2807,9 @@ impl Interp { }) } - /// ToString applied to a primitive. + /// ToString applied to a primitive, with a Symbol written as `Symbol(description)` for + /// messages, its description cut as [`crate::symbol::Sym::message_name`] cuts it; + /// [`Self::to_str`] refuses a Symbol. pub(crate) fn primitive_to_str(&mut self, v: &Value) -> Str { match v { Value::Undefined => Str::from("undefined"), @@ -2798,12 +2822,22 @@ impl Interp { } Value::String(s) => s.clone(), Value::Object(_) => Str::from("[object]"), + Value::Symbol(s) => { + let (units, _) = s.message_name(); + self.heap.bytes += string_bytes(units.len()); + Str::from_units(units) + } } } + /// ToString (section 9.8); a Symbol throws a `TypeError` (ECMA-262 11th edition, section + /// 7.1.17). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_str(&mut self, v: &Value) -> JsResult { let p = self.to_primitive(v, Hint::String)?; + if matches!(p, Value::Symbol(_)) { + return Err(self.type_error("cannot convert a Symbol value to a string")); + } Ok(self.primitive_to_str(&p)) } @@ -2854,6 +2888,7 @@ impl Interp { Value::Bool(b) => (Class::Boolean(*b), self.intrinsics.boolean_proto), Value::Number(n) => (Class::Number(*n), self.intrinsics.number_proto), Value::String(s) => (Class::String(s.clone()), self.intrinsics.string_proto), + Value::Symbol(s) => (Class::Symbol(s.clone()), self.primitive_proto(v, &[])?), }; Ok(self.heap.alloc_object(Object::new(class, Some(proto)))) } @@ -2932,8 +2967,8 @@ impl Interp { return self.xml_has(b, a).map(Value::Bool); } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; - let k = self.to_key(a)?; - self.has_property(*o, &k).map(Value::Bool) + let k = self.to_prop_key(a)?; + self.has_pk(*o, &k).map(Value::Bool) } } } @@ -2949,8 +2984,10 @@ impl Interp { let pa = self.to_primitive(a, Hint::Default)?; let pb = self.to_primitive(b, Hint::Default)?; if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) { - let sa = self.primitive_to_str(&pa); - let sb = self.primitive_to_str(&pb); + // Both are primitives, so this converts them without running script code; a Symbol + // throws. + let sa = self.to_str(&pa)?; + let sb = self.to_str(&pb)?; return self.concat(&sa, &sb).map(Value::String); } Ok(Value::Number(self.to_number(&pa)? + self.to_number(&pb)?)) @@ -2995,29 +3032,45 @@ impl Interp { (Value::Number(_), Value::Number(_)) | (Value::String(_), Value::String(_)) | (Value::Bool(_), Value::Bool(_)) + | (Value::Symbol(_), Value::Symbol(_)) | (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)), (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => { return Ok(*n == string_to_number(&flat_charged(self, s)?)); } (Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))), (_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))), - (Value::Number(_) | Value::String(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?, - (Value::Object(_), Value::Number(_) | Value::String(_)) => x = self.to_primitive(&x, Hint::Default)?, + (Value::Number(_) | Value::String(_) | Value::Symbol(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?, + (Value::Object(_), Value::Number(_) | Value::String(_) | Value::Symbol(_)) => x = self.to_primitive(&x, Hint::Default)?, _ => return Ok(false), } } } - /// `instanceof` (sections 11.8.6 and 15.3.5.3). + /// `instanceof` (sections 11.8.6 and 15.3.5.3). In a realm with [`crate::Options::es2015`], + /// the right side's `@@hasInstance` method answers when it has one (ECMA-262 11th edition, + /// section 12.10.4). fn instance_of(&mut self, v: &Value, f: &Value) -> JsResult { + if let Some(r) = self.has_instance_hook(v, f)? { + return Ok(r); + } if !self.is_callable(f) { return Err(self.type_error("the right side of 'instanceof' is not a function")); } - let Some(mut fid) = f.as_object() else { return Ok(false) }; - // A bound function answers for its target (section 15.3.4.5.3). + self.ordinary_has_instance(v, f) + } + + /// OrdinaryHasInstance (ECMA-262 11th edition, section 7.3.21): `false` when `f` is not a + /// function. + pub(crate) fn ordinary_has_instance(&mut self, v: &Value, f: &Value) -> JsResult { + let Some(mut fid) = f.as_object().filter(|_| self.is_callable(f)) else { return Ok(false) }; + // A bound function answers for its target (section 15.3.4.5.3), or the target's own + // `@@hasInstance` method does. while let Some(Func::Bound { target, .. }) = self.func_of(&Value::Object(fid)) { self.use_fuel()?; fid = target; + if let Some(r) = self.bound_target_hook(v, fid)? { + return Ok(r); + } } let f = &Value::Object(fid); let Value::Object(mut o) = v.clone() else { return Ok(false) }; @@ -3048,6 +3101,7 @@ impl Interp { Value::Number(n) => crate::JsValue::Number(*n), Value::String(s) => crate::JsValue::String(s.to_rust_string()), Value::Object(o) => crate::JsValue::Object(self.heap.object(*o).map_or("Object", |o| o.class.name()).to_string()), + Value::Symbol(s) => crate::JsValue::Symbol(s.description().map(Str::to_rust_string)), } } @@ -3068,6 +3122,13 @@ impl Interp { Value::str(&s) } crate::JsValue::Object(_) => Value::Object(self.new_object()), + crate::JsValue::Symbol(description) => { + let units: Option> = description.map(|d| d.encode_utf16().collect()); + let bytes = crate::heap::SYMBOL_BYTES + units.as_ref().map_or(0, |u| string_bytes(u.len())); + self.reserve_heap(bytes)?; + self.heap.bytes += bytes; + Value::Symbol(crate::symbol::Sym::new(units.map(Str::from_units), false)) + } }) } @@ -3127,7 +3188,7 @@ impl Desc { } /// The attribute flags the descriptor gives, each absent one taken from `default`. - fn flags_or(&self, default: u8) -> u8 { + pub(crate) fn flags_or(&self, default: u8) -> u8 { let pick = |field: Option, bit: u8| match field { Some(true) => bit, Some(false) => 0, @@ -3147,7 +3208,7 @@ pub(crate) fn same_value(a: &Value, b: &Value) -> bool { /// Steps 5 to 12 of [[DefineOwnProperty]] (section 8.12.9) for an existing property: the /// property after `desc` is applied, or `None` when the change is not allowed. -fn merge_desc(current: &Prop, desc: &Desc) -> Option { +pub(crate) fn merge_desc(current: &Prop, desc: &Desc) -> Option { let flags = current.flags(); let configurable = flags & CONFIGURABLE != 0; if !configurable { @@ -3203,6 +3264,7 @@ pub(crate) fn strict_eq(a: &Value, b: &Value) -> bool { (Value::String(x), Value::String(y)) => x == y, (Value::Bool(x), Value::Bool(y)) => x == y, (Value::Object(x), Value::Object(y)) => x == y, + (Value::Symbol(x), Value::Symbol(y)) => x == y, _ => false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..c5e45af08f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -46,6 +46,17 @@ //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and //! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each //! node. +//! +//! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, +//! ): `Symbol.for` and `Symbol.keyFor` over a registry +//! that lasts as long as the realm, the well-known Symbols `iterator`, `asyncIterator`, +//! `hasInstance`, `toPrimitive` and `toStringTag` with the hooks ToPrimitive, `instanceof` and +//! `Object.prototype.toString` read, Symbol-keyed properties with `Object.getOwnPropertySymbols`, +//! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and +//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. A +//! Symbol converted to a string or a number without `String(symbol)` or `toString` throws a +//! `TypeError`. Every iterator step takes fuel, and every Symbol and registry entry counts against +//! the heap limit. #![forbid(unsafe_code)] pub mod ast; @@ -68,6 +79,7 @@ mod regexp; mod regexp_builtins; mod regexp_vm; mod string_builtins; +mod symbol; mod token; mod value; mod xml; @@ -100,11 +112,15 @@ pub struct Options { pub max_source_units: usize, /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, + /// Give a realm the later editions' built-ins this engine has: `Symbol` with Symbol-keyed + /// properties and the iterators of arrays, strings and `arguments` objects. Off, a realm has + /// the ES5.1 built-ins only, as the app's scripts expect. + pub es2015: bool, } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } } } @@ -209,6 +225,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod symbol_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ee2cd364f8..08d9913948 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -109,7 +109,8 @@ impl Interrupt { } } -/// A value passed between a script and the host. An object is given by its class name. +/// A value passed between a script and the host. An object is given by its class name, and a +/// Symbol by its description; a Symbol the host passes in is a new Symbol each time. #[derive(Clone, Debug, PartialEq)] pub enum JsValue { Undefined, @@ -118,6 +119,7 @@ pub enum JsValue { Number(f64), String(String), Object(String), + Symbol(Option), } #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/js/src/string_builtins.rs b/crates/js/src/string_builtins.rs index eed08f96bd..c2787b5a56 100644 --- a/crates/js/src/string_builtins.rs +++ b/crates/js/src/string_builtins.rs @@ -209,6 +209,8 @@ pub(crate) fn find(interp: &mut Interp, hay: &[u16], needle: &[u16], from: usize /// `String(value)` and `new String(value)` (sections 15.5.1 and 15.5.2). fn string_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { let s = match args.first() { + // `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1). + Some(Value::Symbol(sym)) if !construct => return interp.descriptive_string(sym), Some(v) => interp.to_str(v)?, None => Str::from(""), }; diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs new file mode 100644 index 0000000000..2c25ebd099 --- /dev/null +++ b/crates/js/src/symbol.rs @@ -0,0 +1,581 @@ +//! Symbols (ECMA-262 11th edition, section 6.1.5, ) and +//! the properties they name. +//! +//! A Symbol is a value with its own identity and an optional description; two Symbols are equal +//! only when they are the same Symbol. An object keeps its Symbol-keyed properties apart from its +//! string-keyed ones, in the order they were added, so `for-in`, `Object.keys`, +//! `Object.getOwnPropertyNames` and `JSON` see only names, and `Object.getOwnPropertySymbols` sees +//! only Symbols. `Symbol.for`'s registry belongs to the realm and lives as long as it does; each +//! entry counts against the heap limit. A realm without [`crate::Options::es2015`] makes no Symbol, +//! so its scripts run as before. + +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::rc::Rc; + +use crate::heap::{ObjId, PROP_BYTES, Prop, WRITABLE}; +use crate::interp::{Desc, Hint, Interp, JsResult, merge_desc}; +use crate::value::{Str, Value}; + +/// A Symbol value. Clones share the Symbol; equality and hashing compare identity. +#[derive(Clone)] +pub(crate) struct Sym(Rc); + +struct SymData { + description: Option, + /// `Symbol.for` made it, and the registry holds it under its description. + registered: bool, +} + +impl Sym { + pub(crate) fn new(description: Option, registered: bool) -> Self { + Sym(Rc::new(SymData { description, registered })) + } + + pub(crate) fn description(&self) -> Option<&Str> { + self.0.description.as_ref() + } + + pub(crate) fn registered(&self) -> bool { + self.0.registered + } + + /// An address that identifies the Symbol, for counting it once. + pub(crate) fn addr(&self) -> usize { + Rc::as_ptr(&self.0) as *const () as usize + } + + /// `Symbol(description)` for a message, with at most [`NAMED_UNITS`] units of the description + /// followed by `...` when it has more, and the work reading them took: the rope nodes visited + /// plus the units read. The description is not flattened or copied whole. + pub(crate) fn message_name(&self) -> (Vec, u64) { + let mut units: Vec = "Symbol(".encode_utf16().collect(); + let mut work = 0; + if let Some(d) = self.description() { + let (part, visited) = d.prefix(NAMED_UNITS, NAMED_NODES); + work = visited.saturating_add(part.len() as u64); + let cut = part.len() < d.len(); + units.extend_from_slice(&part); + if cut { + units.extend("...".encode_utf16()); + } + } + units.push(u16::from(b')')); + (units, work) + } +} + +/// The most units of a Symbol's description a message names. +const NAMED_UNITS: usize = 256; + +/// The most rope nodes read for the units a message names. +const NAMED_NODES: u64 = 4 * NAMED_UNITS as u64; + +impl PartialEq for Sym { + fn eq(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } +} + +impl Eq for Sym {} + +impl Hash for Sym { + fn hash(&self, state: &mut H) { + self.addr().hash(state); + } +} + +impl std::fmt::Debug for Sym { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", String::from_utf16_lossy(&self.message_name().0)) + } +} + +/// An object's Symbol-keyed properties in the order they were added. A removed entry leaves a +/// gap until half the entries are gaps, so removing keeps the order without moving the rest. +#[derive(Clone, Default)] +pub(crate) struct SymProps { + entries: Vec>, + index: HashMap, +} + +impl SymProps { + pub(crate) fn get(&self, k: &Sym) -> Option<&Prop> { + let i = *self.index.get(k)?; + self.entries.get(i)?.as_ref().map(|(_, p)| p) + } + + pub(crate) fn get_mut(&mut self, k: &Sym) -> Option<&mut Prop> { + let i = *self.index.get(k)?; + self.entries.get_mut(i)?.as_mut().map(|(_, p)| p) + } + + /// Sets the property under `k`, keeping its place when it is there already. Returns whether + /// the key is new. + pub(crate) fn insert(&mut self, k: Sym, prop: Prop) -> bool { + if let Some(slot) = self.get_mut(&k) { + *slot = prop; + return false; + } + self.index.insert(k.clone(), self.entries.len()); + self.entries.push(Some((k, prop))); + true + } + + pub(crate) fn remove(&mut self, k: &Sym) -> Option { + let i = self.index.remove(k)?; + let (_, prop) = self.entries.get_mut(i)?.take()?; + if self.entries.len() > 16 && self.index.len() * 2 < self.entries.len() { + self.entries.retain(Option::is_some); + self.index = self.entries.iter().enumerate().filter_map(|(i, e)| e.as_ref().map(|(k, _)| (k.clone(), i))).collect(); + } + Some(prop) + } + + pub(crate) fn len(&self) -> usize { + self.index.len() + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.entries.iter().filter_map(|e| e.as_ref().map(|(k, p)| (k, p))) + } +} + +/// A property key (section 6.1.7): a name or a Symbol. +pub(crate) enum PropKey { + Str(crate::heap::Key), + Sym(Sym), +} + +/// The well-known Symbols a realm has (section 6.1.5.1): `Symbol.iterator` and the others the +/// language reads, with `Symbol.asyncIterator`, which nothing reads yet. +pub(crate) struct WellKnown { + pub(crate) iterator: Sym, + pub(crate) async_iterator: Sym, + pub(crate) has_instance: Sym, + pub(crate) to_primitive: Sym, + pub(crate) to_string_tag: Sym, + /// The five as values, for the collector. + values: Vec, +} + +impl WellKnown { + pub(crate) fn new() -> Self { + let make = |name: &str| Sym::new(Some(Str::from(name)), false); + let (iterator, async_iterator, has_instance, to_primitive, to_string_tag) = ( + make("Symbol.iterator"), + make("Symbol.asyncIterator"), + make("Symbol.hasInstance"), + make("Symbol.toPrimitive"), + make("Symbol.toStringTag"), + ); + let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect(); + WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values } + } +} + +/// The objects of a realm with [`crate::Options::es2015`] that the interpreter itself uses. +#[derive(Clone, Copy)] +pub(crate) struct Es2015Objects { + pub(crate) symbol_proto: ObjId, + pub(crate) array_iterator_proto: ObjId, + pub(crate) string_iterator_proto: ObjId, + /// `%ArrayProto_values%`, the `@@iterator` of every `arguments` object. + pub(crate) array_values: ObjId, + /// `Function.prototype[@@hasInstance]`. + pub(crate) has_instance: ObjId, +} + +/// The estimated bytes of a registry entry without its Symbol. +pub(crate) const REGISTRY_ENTRY_BYTES: usize = 48; + +/// A realm's Symbols: the well-known ones, `Symbol.for`'s registry and the built-in objects that +/// go with them. All are `None` or empty in a realm without [`crate::Options::es2015`]. +#[derive(Default)] +pub(crate) struct Symbols { + pub(crate) well_known: Option, + /// Each key `Symbol.for` was given, with its Symbol as a value. + pub(crate) registry: HashMap, Value>, + pub(crate) objects: Option, +} + +impl Symbols { + /// The values the collector starts from. + pub(crate) fn root_values(&self) -> impl Iterator { + self.well_known.iter().flat_map(|w| w.values.iter()).chain(self.registry.values()) + } + + /// The objects the collector starts from. + pub(crate) fn root_objects(&self) -> Vec { + self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + } + + /// The bytes the registry's entries hold besides their Symbols, which a collection adds. + pub(crate) fn registry_bytes(&self) -> usize { + self.registry.len().saturating_mul(REGISTRY_ENTRY_BYTES) + } +} + +impl Interp { + /// ToPropertyKey (section 7.1.14): a Symbol, or an object whose primitive value is one, stays a + /// Symbol; any other value becomes a name. + #[allow(clippy::wrong_self_convention)] + pub(crate) fn to_prop_key(&mut self, v: &Value) -> JsResult { + match v { + Value::Symbol(s) => Ok(PropKey::Sym(s.clone())), + Value::Object(_) => match self.to_primitive(v, Hint::String)? { + Value::Symbol(s) => Ok(PropKey::Sym(s)), + p => self.to_key(&p).map(PropKey::Str), + }, + _ => self.to_key(v).map(PropKey::Str), + } + } + + /// Runs `f` with the key [`Self::to_prop_key`] makes from `v`, kept reachable while `f` runs + /// when it was converted from another value. + pub(crate) fn with_prop_key(&mut self, v: &Value, f: impl FnOnce(&mut Self, PropKey) -> JsResult) -> JsResult { + match v { + Value::Symbol(s) => f(self, PropKey::Sym(s.clone())), + Value::Object(_) => { + let p = self.to_primitive(v, Hint::String)?; + if let Value::Symbol(s) = p { + return f(self, PropKey::Sym(s)); + } + self.rooted(std::slice::from_ref(&p), |i| i.with_key(&p, |i, k| f(i, PropKey::Str(k)))) + } + _ => self.with_key(v, |i, k| f(i, PropKey::Str(k))), + } + } + + /// [`Sym::message_name`] as code units, its reading charged as fuel. + pub(crate) fn sym_name_units(&mut self, k: &Sym) -> JsResult> { + let (units, work) = k.message_name(); + crate::regexp_vm::use_fuel_n(self, work.max(1))?; + Ok(units) + } + + /// [`Sym::message_name`] as text, its reading charged as fuel. + pub(crate) fn sym_name(&mut self, k: &Sym) -> JsResult { + self.sym_name_units(k).map(|u| String::from_utf16_lossy(&u)) + } + + /// `prefix`, the units of `body` and `suffix` as a new string. Flattening `body` and building + /// the string are charged as fuel and checked against the heap limit first. + pub(crate) fn wrap_str(&mut self, prefix: &str, body: Option<&Str>, suffix: &str) -> JsResult { + let body = match body { + Some(b) => crate::string_builtins::flat_charged(self, b)?, + None => Rc::from([]), + }; + let (prefix, suffix): (Vec, Vec) = (prefix.encode_utf16().collect(), suffix.encode_utf16().collect()); + let len = prefix.len().saturating_add(body.len()).saturating_add(suffix.len()); + crate::string_builtins::reserve_units(self, len)?; + let mut units = Vec::with_capacity(len); + units.extend_from_slice(&prefix); + units.extend_from_slice(&body); + units.extend_from_slice(&suffix); + Ok(Value::String(Str::from_units(units))) + } + + /// SymbolDescriptiveString (section 19.4.3.3.1): `Symbol(description)` as a new string. + pub(crate) fn descriptive_string(&mut self, k: &Sym) -> JsResult { + let roots = [Value::Symbol(k.clone())]; + self.rooted(&roots, |i| i.wrap_str("Symbol(", k.description(), ")")) + } + + /// A `TypeError` for a property `k` that cannot be defined, when `throw`; otherwise `false`. + fn reject_sym_bool(&mut self, throw: bool, k: &Sym, why: &str) -> JsResult { + if !throw { + return Ok(false); + } + let name = self.sym_name_units(k)?; + self.reject_bool(true, &name, why) + } + + /// A `TypeError` for a property `k` that cannot be set, when `throw`. + fn reject_sym(&mut self, throw: bool, k: &Sym, why: &str) -> JsResult<()> { + if !throw { + return Ok(()); + } + let name = self.sym_name_units(k)?; + self.reject(true, &name, why) + } + + pub(crate) fn get_own_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) + } + + /// The property `k` found on the object or its prototype chain. + pub(crate) fn find_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + let mut cur = Some(id); + let mut steps = 0usize; + while let Some(o) = cur { + if let Some(p) = self.get_own_sym(o, k)? { + return Ok(Some(p)); + } + cur = self.object(o)?.proto; + steps += 1; + if steps > 1_000_000 { + return Err(crate::interp::Abrupt::Internal("prototype chain too long".into())); + } + } + Ok(None) + } + + /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. + pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult { + match self.find_sym(start, k)? { + None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + } + } + + /// `base[k]` for any value. + pub(crate) fn get_value_sym(&mut self, base: &Value, k: &Sym) -> JsResult { + if base.is_nullish() { + let (key, base) = (self.sym_name(k)?, if matches!(base, Value::Null) { "null" } else { "undefined" }); + return Err(self.type_error(&format!("cannot read property '{key}' of {base}"))); + } + let start = self.primitive_proto(base, &[])?; + self.get_sym_from(start, k, base) + } + + /// Adds or replaces an own property directly, keeping the heap estimate. + pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> { + let o = self.object_mut(id)?; + if o.syms.get_or_insert_with(Box::default).insert(k, prop) { + self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES); + } + Ok(()) + } + + /// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key. + pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult { + let Some(current) = self.get_own_sym(id, &k)? else { + if !self.object(id)?.extensible { + return self.reject_sym_bool(throw, &k, "the object is not extensible"); + } + let mut roots = vec![Value::Object(id), Value::Symbol(k.clone())]; + roots.extend(desc.value.iter().cloned()); + roots.extend(desc.get.flatten().into_iter().chain(desc.set.flatten()).map(Value::Object)); + self.rooted(&roots, |i| i.reserve_heap(PROP_BYTES))?; + let flags = desc.flags_or(0); + let prop = if desc.is_accessor() { + Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: flags & !WRITABLE } + } else { + Prop::Data { value: desc.value.clone().unwrap_or(Value::Undefined), flags } + }; + self.define_sym(id, k, prop)?; + return Ok(true); + }; + let Some(merged) = merge_desc(¤t, desc) else { return self.reject_sym_bool(throw, &k, "the property cannot be redefined") }; + self.define_sym(id, k, merged)?; + Ok(true) + } + + /// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key. + pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> { + match self.get_own_sym(id, &k)? { + Some(Prop::Data { flags, .. }) => { + if flags & WRITABLE == 0 { + return self.reject_sym(throw, &k, "it is read-only"); + } + if let Some(Some(Prop::Data { value, .. })) = self.object_mut(id)?.syms.as_mut().map(|m| m.get_mut(&k)) { + *value = v; + } + return Ok(()); + } + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), + None => {} + } + let proto = self.object(id)?.proto; + match proto.map(|p| self.find_sym(p, &k)).transpose()?.flatten() { + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"), + _ => {} + } + if !self.object(id)?.extensible { + return self.reject_sym(throw, &k, "the object is not extensible"); + } + let roots = [Value::Object(id), Value::Symbol(k.clone()), v.clone()]; + self.rooted(&roots, |i| i.reserve_heap(PROP_BYTES))?; + self.define_sym(id, k, Prop::Data { value: v, flags: crate::heap::OPEN }) + } + + /// PutValue (section 6.2.4.9) on a Symbol-keyed reference, whose base may be a primitive. + pub(crate) fn put_value_sym(&mut self, base: &Value, k: Sym, v: Value) -> JsResult<()> { + match base { + Value::Object(o) => { + let throw = self.strict_writes(); + self.put_sym(*o, k, v, throw) + } + Value::Undefined | Value::Null => { + let (key, base) = (self.sym_name(&k)?, if matches!(base, Value::Null) { "null" } else { "undefined" }); + Err(self.type_error(&format!("cannot set property '{key}' of {base}"))) + } + _ => { + let proto = self.primitive_proto(base, &[])?; + if let Some(Prop::Accessor { set: Some(s), .. }) = self.find_sym(proto, &k)? { + return self.call(&Value::Object(s), base, &[v]).map(drop); + } + let strict = self.strict(); + self.reject_sym(strict, &k, "the value is a primitive") + } + } + } + + /// [[Delete]] (section 9.1.10) for a Symbol key. + pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult { + match self.get_own_sym(id, k)? { + None => Ok(true), + Some(p) if p.configurable() => { + if let Some(m) = self.object_mut(id)?.syms.as_mut() { + m.remove(k); + } + Ok(true) + } + Some(_) if throw => { + let key = self.sym_name(k)?; + Err(self.type_error(&format!("cannot delete property '{key}'"))) + } + Some(_) => Ok(false), + } + } + + /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and + /// the heap for the list is checked first. + pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { + let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); + self.reserve_heap(count.saturating_mul(16))?; + for _ in 0..count { + self.use_fuel()?; + } + Ok(self.object(id)?.syms.iter().flat_map(|m| m.iter()).map(|(k, _)| k.clone()).collect()) + } + + // ---- either kind of key ---- + + pub(crate) fn get_own_pk(&self, id: ObjId, k: &PropKey) -> JsResult> { + match k { + PropKey::Str(name) => self.get_own_property(id, name), + PropKey::Sym(s) => self.get_own_sym(id, s), + } + } + + pub(crate) fn has_pk(&self, id: ObjId, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.has_property(id, name), + PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()), + } + } + + pub(crate) fn define_own_pk(&mut self, id: ObjId, k: PropKey, desc: &Desc, throw: bool) -> JsResult { + match k { + PropKey::Str(name) => self.define_own_property(id, name, desc, throw), + PropKey::Sym(s) => self.define_own_sym(id, s, desc, throw), + } + } + + pub(crate) fn get_value_pk(&mut self, base: &Value, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.get_value(base, name), + PropKey::Sym(s) => self.get_value_sym(base, s), + } + } + + pub(crate) fn put_value_pk(&mut self, base: &Value, k: PropKey, v: Value) -> JsResult<()> { + match k { + PropKey::Str(name) => self.put_value(base, name, v), + PropKey::Sym(s) => self.put_value_sym(base, s, v), + } + } + + pub(crate) fn delete_pk(&mut self, id: ObjId, k: &PropKey, throw: bool) -> JsResult { + match k { + PropKey::Str(name) => self.delete(id, name, throw), + PropKey::Sym(s) => self.delete_sym(id, s, throw), + } + } + + // ---- the hooks the well-known Symbols name ---- + + /// The well-known Symbol `pick` chooses, in a realm that has them. + pub(crate) fn well_known(&self, pick: fn(&WellKnown) -> &Sym) -> Option { + self.symbols.well_known.as_ref().map(|w| pick(w).clone()) + } + + /// Steps 2 and 3 of ToPrimitive (section 7.1.1): the result of the object's + /// `@@toPrimitive` method called with the hint, or `None` when it has none. + pub(crate) fn exotic_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.to_primitive) else { return Ok(None) }; + let f = self.get_sym_from(o, &sym, v)?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error("the value is not a function")); + } + let hint = match hint { + Hint::Default => "default", + Hint::Number => "number", + Hint::String => "string", + }; + let r = self.call(&f, v, &[Value::str(hint)])?; + if matches!(r, Value::Object(_)) { + return Err(self.type_error("cannot convert the object to a primitive value")); + } + Ok(Some(r)) + } + + /// Steps 2 to 4 of InstanceofOperator (section 12.10.4): the answer of `f`'s + /// `@@hasInstance` method, or `None` when `f` is not an object or has none. + pub(crate) fn has_instance_hook(&mut self, v: &Value, f: &Value) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.has_instance) else { return Ok(None) }; + let Value::Object(fid) = f else { return Ok(None) }; + let handler = self.get_sym_from(*fid, &sym, f)?; + if handler.is_nullish() { + return Ok(None); + } + if !self.is_callable(&handler) { + return Err(self.type_error("the value is not a function")); + } + Ok(Some(self.call(&handler, f, std::slice::from_ref(v))?.truthy())) + } + + /// For the target of a bound function in OrdinaryHasInstance (section 7.3.21, step 2): the + /// answer of its own `@@hasInstance` method when that is not `Function.prototype`'s, whose + /// answer is the one the caller goes on to give. + pub(crate) fn bound_target_hook(&mut self, v: &Value, target: ObjId) -> JsResult> { + let default = self.symbols.objects.map(|o| o.has_instance); + match self.has_instance_handler(target)? { + Some(h) if Some(h) != default => { + let f = Value::Object(target); + Ok(Some(self.call(&Value::Object(h), &f, std::slice::from_ref(v))?.truthy())) + } + _ => Ok(None), + } + } + + /// `target[@@hasInstance]` when it is callable, `None` when it is absent; anything else + /// throws a `TypeError`. + fn has_instance_handler(&mut self, target: ObjId) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.has_instance) else { return Ok(None) }; + let handler = self.get_sym_from(target, &sym, &Value::Object(target))?; + match handler { + Value::Undefined | Value::Null => Ok(None), + Value::Object(h) if self.is_callable(&handler) => Ok(Some(h)), + _ => Err(self.type_error("the value is not a function")), + } + } + + /// The `@@toStringTag` of `o` when it is a string (section 19.1.3.6, steps 15 and 16). + pub(crate) fn string_tag_of(&mut self, o: ObjId) -> JsResult> { + let Some(sym) = self.well_known(|w| &w.to_string_tag) else { return Ok(None) }; + match self.get_sym_from(o, &sym, &Value::Object(o))? { + Value::String(s) => Ok(Some(s)), + _ => Ok(None), + } + } +} diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs new file mode 100644 index 0000000000..d877e04106 --- /dev/null +++ b/crates/js/src/symbol_tests.rs @@ -0,0 +1,230 @@ +//! `Symbol`, Symbol-keyed properties and the iterators of arrays, strings and `arguments` +//! 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:?}"), + } +} + +#[test] +fn symbols_are_unique_values_with_a_description() { + truth("typeof Symbol() === 'symbol' && typeof Symbol('a') === 'symbol'"); + truth("Symbol('a') !== Symbol('a') && Symbol('a') != Symbol('a')"); + truth("var s = Symbol('a'); s === s && s == Object(s) && Object(s) == s"); + truth("Symbol('a').description === 'a' && Symbol().description === undefined && Symbol('').description === ''"); + assert_eq!(string("String(Symbol('a b'))"), "Symbol(a b)"); + assert_eq!(string("Symbol().toString()"), "Symbol()"); + truth("var s = Symbol(); Object(s).valueOf() === s && typeof Object(s) === 'object'"); + truth("Object.prototype.toString.call(Symbol()) === '[object Symbol]'"); + truth("!!Symbol() && Symbol.length === 0 && Symbol.prototype.constructor === Symbol"); + throws("new Symbol()", "TypeError"); + throws("Symbol.prototype.toString.call({})", "TypeError"); +} + +#[test] +fn symbol_for_and_key_for_use_the_registry() { + truth("Symbol.for('k') === Symbol.for('k') && Symbol.for('k') !== Symbol('k')"); + truth("Symbol.keyFor(Symbol.for('k')) === 'k' && Symbol.keyFor(Symbol('k')) === undefined"); + truth("Symbol.keyFor(Symbol.iterator) === undefined && Symbol.for('x').description === 'x'"); + throws("Symbol.keyFor('k')", "TypeError"); + throws("Symbol.for(Symbol())", "TypeError"); +} + +#[test] +fn implicit_conversion_of_a_symbol_throws_a_type_error() { + throws("Symbol() + ''", "TypeError"); + throws("'' + Symbol('a')", "TypeError"); + throws("+Symbol()", "TypeError"); + throws("Symbol() * 2", "TypeError"); + throws("Symbol() < 1", "TypeError"); + throws("[Symbol()].join()", "TypeError"); + throws("'abc'.indexOf(Symbol())", "TypeError"); + throws("Symbol(Symbol())", "TypeError"); + throws("new String(Symbol())", "TypeError"); + truth("String(Symbol('x')) === 'Symbol(x)' && Symbol('x').toString() === 'Symbol(x)'"); +} + +#[test] +fn symbol_keys_are_hidden_from_for_in_keys_and_json() { + let setup = "var s = Symbol('s'); var o = {a: 1}; o[s] = 2; "; + truth(&format!("{setup} var n = []; for (var k in o) n.push(k); n.join() === 'a'")); + truth(&format!("{setup} Object.keys(o).join() === 'a' && Object.getOwnPropertyNames(o).join() === 'a'")); + truth(&format!("{setup} JSON.stringify(o) === '{{\"a\":1}}'")); + truth("JSON.stringify({a: Symbol()}) === '{}' && JSON.stringify([Symbol()]) === '[null]' && JSON.stringify(Symbol()) === undefined"); + truth(&format!("{setup} var l = Object.getOwnPropertySymbols(o); l.length === 1 && l[0] === s && o[s] === 2")); + truth(&format!("{setup} s in o && o.hasOwnProperty(s) && o.propertyIsEnumerable(s) && delete o[s] && !(s in o)")); + truth(&format!("{setup} o[Object(s)] === 2 && o[s.toString()] === undefined")); + throws("var w = new String('x'); w.toString = function () { return Symbol(); }; JSON.stringify(w)", "TypeError"); + truth("var o = Object(Symbol()); delete Symbol.prototype[Symbol.toStringTag]; Object.prototype.toString.call(o) === '[object Object]'"); +} + +#[test] +fn define_property_freeze_and_descriptors_take_symbol_keys() { + truth( + "var s = Symbol(); var o = {}; Object.defineProperty(o, s, {value: 1}); \ + var d = Object.getOwnPropertyDescriptor(o, s); d.value === 1 && !d.writable && !d.enumerable && !d.configurable", + ); + truth("var s = Symbol(); var o = {}; o[s] = 1; Object.freeze(o); o[s] = 2; o[s] === 1 && Object.isFrozen(o)"); + truth("var s = Symbol(); var o = {}; o[s] = 1; Object.preventExtensions(o); Object.isSealed(o) === false"); + truth("var s = Symbol(); var p = {}; p[s] = {value: 3, enumerable: true}; var o = Object.create(null, p); o[s] === 3"); + throws("'use strict'; var s = Symbol(); var o = Object.freeze((function () { var x = {}; x[s] = 1; return x; })()); o[s] = 2;", "TypeError"); + truth("var s = Symbol(); var o = {}; o[s] = 1; o[s]++; o[s] === 2"); +} + +#[test] +fn well_known_symbols_hook_the_operations_that_read_them() { + truth("var o = {}; o[Symbol.toStringTag] = 'Thing'; Object.prototype.toString.call(o) === '[object Thing]'"); + truth("var o = {}; o[Symbol.toPrimitive] = function (h) { return h === 'number' ? 7 : 'str'; }; +o === 7 && String(o) === 'str'"); + throws("var o = {}; o[Symbol.toPrimitive] = function () { return {}; }; +o", "TypeError"); + throws("var o = {}; o[Symbol.toPrimitive] = 1; +o", "TypeError"); + truth("var C = {}; C[Symbol.hasInstance] = function (v) { return v === 1; }; (1 instanceof C) && !(2 instanceof C)"); + truth("function F() {} var B = F.bind(); new F() instanceof B && typeof Function.prototype[Symbol.hasInstance] === 'function'"); + truth("Function.prototype[Symbol.hasInstance].call(Array, []) === true && Function.prototype[Symbol.hasInstance].call({}, []) === false"); + truth( + "Symbol.iterator.toString() === 'Symbol(Symbol.iterator)' && typeof Symbol.asyncIterator === 'symbol' \ + && typeof Symbol.hasInstance === 'symbol' && typeof Symbol.toPrimitive === 'symbol' && typeof Symbol.toStringTag === 'symbol'", + ); +} + +#[test] +fn an_array_iterator_driven_by_hand_steps_through_values_keys_and_entries() { + truth( + "var it = [10, 20][Symbol.iterator](); var a = it.next(), b = it.next(), c = it.next(), d = it.next(); \ + a.value === 10 && !a.done && b.value === 20 && !b.done && c.value === undefined && c.done && d.done", + ); + truth("var it = ['a', 'b'].keys(); it.next().value === 0 && it.next().value === 1 && it.next().done"); + truth("var e = ['x'].entries().next().value; e.length === 2 && e[0] === 0 && e[1] === 'x'"); + truth("Array.prototype[Symbol.iterator] === Array.prototype.values"); + truth("var a = [1]; var it = a.values(); it.next(); a.push(2); it.next().value === 2"); + truth("var it = [].values(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Array Iterator]'"); + truth("var it = Array.prototype.values.call({length: 1, 0: 'q'}); it.next().value === 'q'"); + throws("[].values().next.call({})", "TypeError"); + throws("[].values().next.call(''[Symbol.iterator]())", "TypeError"); +} + +#[test] +fn a_string_iterator_steps_by_code_point() { + truth( + "var it = 'a\\uD83D\\uDE00b'[Symbol.iterator](); var x = it.next().value, y = it.next().value, z = it.next().value; \ + x === 'a' && y === '\\uD83D\\uDE00' && y.length === 2 && z === 'b' && it.next().done", + ); + truth("var it = '\\uDE00\\uD83D'[Symbol.iterator](); it.next().value === '\\uDE00' && it.next().value === '\\uD83D' && it.next().done"); + truth("Object.prototype.toString.call(''[Symbol.iterator]()) === '[object String Iterator]'"); + throws("String.prototype[Symbol.iterator].call(null)", "TypeError"); +} + +#[test] +fn arguments_objects_have_the_array_values_iterator() { + truth("(function () { return arguments[Symbol.iterator] === Array.prototype.values; })()"); + truth("(function () { 'use strict'; var it = arguments[Symbol.iterator](); return it.next().value === 5 && it.next().done; })(5)"); + truth("(function () { return !arguments.propertyIsEnumerable(Symbol.iterator); })()"); +} + +#[test] +fn realms_without_es2015_have_no_symbol() { + for options in [Options::default(), Options { e4x: true, preprocessor_lines: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + let src = "typeof Symbol === 'undefined' && Array.prototype.values === undefined && Object.getOwnPropertySymbols === undefined"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); + let src = "Object.getOwnPropertyNames((function () { return arguments; })()).join()"; + assert_eq!(realm.run(src), Ok(JsValue::String("length,callee".into()))); + } +} + +#[test] +fn symbols_and_the_registry_count_against_the_heap_limit() { + let limits = || Limits { heap_bytes: 1 << 20, fuel: 50_000_000, ..Limits::default() }; + let mut realm = es2015(limits()); + match realm.run("for (var i = 0; ; i++) Symbol.for('key' + i);") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{other:?}"), + } + let mut realm = es2015(limits()); + match realm.run("var keep = []; for (var i = 0; ; i++) keep.push(Symbol('d' + i));") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{other:?}"), + } + // Symbols nothing holds are collected, so making them one after another does not fill the + // heap, and keys survive a collection. + let mut realm = es2015(limits()); + let src = "var s = Symbol('k'); var o = {}; o[s] = 'v'; for (var i = 0; i < 40000; i++) Symbol('x' + i); o[s] === 'v'"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); +} + +#[test] +fn an_error_names_a_long_symbol_by_the_start_of_its_description() { + // `d` is a rope of 4,194,304 units whose halves share one node, so it takes little heap until + // something copies it whole. Each error names the Symbol by the first 256 units only. + let setup = "var d = 'x'; for (var i = 0; i < 22; i++) d = d + d; var s = Symbol(d); \ + var shut = Object.preventExtensions({}); var fixed = Object.defineProperty({}, s, { value: 1 }); "; + let named = format!("Symbol({}...)", "x".repeat(256)); + for (attempt, message) in [ + ("shut[s] = 1", format!("cannot assign to property '{named}': the object is not extensible")), + ("Object.defineProperty(shut, s, { value: 1 })", format!("cannot define property '{named}': the object is not extensible")), + ("Object.defineProperty(fixed, s, { value: 2 })", format!("cannot define property '{named}': the property cannot be redefined")), + ("fixed[s] = 2", format!("cannot assign to property '{named}': it is read-only")), + ("delete fixed[s]", format!("cannot delete property '{named}'")), + ("null[s]", "cannot read a property of null".to_string()), + ] { + let src = format!( + "{setup} (function () {{ 'use strict'; try {{ {attempt}; return 'none'; }} catch (e) {{ return (e instanceof TypeError) + ' ' + e.message; }} }})()" + ); + let mut realm = es2015(Limits { heap_bytes: 64 << 20, fuel: 1_000_000, ..Limits::default() }); + assert_eq!(realm.run(&src), Ok(JsValue::String(format!("true {message}"))), "{attempt}"); + } + // A write that does not throw leaves the Symbol's description as it is. + let src = format!("{setup} shut[s] = 1; fixed[s] = 2; shut[s] === undefined && fixed[s] === 1"); + assert_eq!(es2015(Limits { heap_bytes: 64 << 20, fuel: 1_000_000, ..Limits::default() }).run(&src), Ok(JsValue::Bool(true))); +} + +#[test] +fn an_array_iterator_keeps_its_object_while_reading_its_length_runs_script() { + // The `length` getter finishes the iterator by stepping it again, which lets go of `obj`, and + // the length's `valueOf` drops the last reference to `obj`, fills the heap until it collects + // and then reuses every free slot. The step still reads the element of `obj`. + let src = "var obj = { 0: 'x', 1: 'y' }, it = Array.prototype.values.call(obj), calls = 0, junk, fresh = []; \ + Object.defineProperty(obj, 'length', { get: function () { \ + calls++; if (calls > 1) return 0; it.next(); \ + return { valueOf: function () { obj = null; \ + for (var i = 0; i < 60000; i++) junk = { a: i }; \ + for (var j = 0; j < 70000; j++) fresh.push({ 0: 'wrong' }); return 2; } }; } }); 0; \ + var r = it.next(); r.value + ' ' + r.done + ' ' + it.next().done"; + assert_eq!(string(src), "x false true"); +} + +#[test] +fn iterator_steps_take_fuel() { + let mut realm = es2015(Limits { fuel: 5_000, ..Limits::default() }); + let src = "var a = []; a.length = 1e9; var it = a.values(); while (!it.next().done) {}"; + match realm.run(src) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } +} diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index a0fbcd4a53..66005773e2 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -19,6 +19,9 @@ pub(crate) enum Value { Number(f64), String(Str), Object(ObjId), + /// A Symbol (ECMA-262 11th edition, section 6.1.5), which only a realm with + /// [`crate::Options::es2015`] makes. + Symbol(crate::symbol::Sym), } impl Value { @@ -44,7 +47,7 @@ impl Value { Value::Bool(b) => *b, Value::Number(n) => !(n.is_nan() || *n == 0.0), Value::String(s) => s.len() > 0, - Value::Object(_) => true, + Value::Object(_) | Value::Symbol(_) => true, } } } @@ -191,6 +194,30 @@ impl Str { } } + /// At most `max` code units from the start, read along the rope without flattening it, + /// visiting at most `max_nodes` nodes, with the number of nodes visited. When the nodes run + /// out first, the units read so far are returned. + pub(crate) fn prefix(&self, max: usize, max_nodes: u64) -> (Vec, u64) { + let mut units = Vec::new(); + let mut stack = vec![self.clone()]; + let mut visited = 0u64; + while let Some(node) = stack.pop() { + if units.len() >= max || visited >= max_nodes { + break; + } + visited += 1; + match &*node.0.borrow() { + Node::Flat(f) => units.extend_from_slice(f.get(..f.len().min(max - units.len())).unwrap_or_default()), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + (units, visited) + } + pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 23337128bb..aeee6ca692 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -35,6 +35,11 @@ //! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without //! `test/annexB/` skips them; a folder there with no test to parse or run fails them. //! +//! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of +//! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with +//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and +//! that parse as ES5. Its failures go to `symbol-failures.txt`. +//! //! The 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. @@ -444,7 +449,12 @@ fn runs_strings_as_code(tokens: &[Token]) -> bool { /// Runs one test in a new realm; `Err` describes a failure. fn run_one(script: &str, negative_type: Option<&str>) -> Result<(), String> { - let mut realm = Realm::with_options(Options::default(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + run_one_with(&Options::default(), script, negative_type) +} + +/// Runs one test in a new realm made with `options`; `Err` describes a failure. +fn run_one_with(options: &Options, script: &str, negative_type: Option<&str>) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); match (realm.run(script), negative_type) { (Ok(_), None) => Ok(()), (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), @@ -696,6 +706,110 @@ fn run_annex_b(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); } +/// The folders of the tests of `Symbol`, Symbol-keyed properties and the iterators of arrays and +/// strings, which run in a realm with [`Options::es2015`]. +const SYMBOL_BUILT_INS: &[&str] = &[ + "built-ins/Symbol", + "built-ins/ArrayIteratorPrototype", + "built-ins/StringIteratorPrototype", + "built-ins/Object/getOwnPropertySymbols", + "built-ins/Array/prototype/values", + "built-ins/Array/prototype/keys", + "built-ins/Array/prototype/entries", + "built-ins/Array/prototype/Symbol.iterator", + "built-ins/String/prototype/Symbol.iterator", +]; + +/// The feature tags of the tests under [`SYMBOL_BUILT_INS`] that run; a test with any other tag is +/// skipped. +const SYMBOL_FEATURES: &[&str] = &[ + "Symbol", + "Symbol.iterator", + "Symbol.toStringTag", + "Symbol.hasInstance", + "Symbol.toPrimitive", + "Symbol.asyncIterator", + "Symbol.prototype.description", +]; + +#[test] +fn es2015_symbol_and_iterators_run() { + let Some(dir) = suite_dir() else { + println!("test262 Symbol and iterators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_symbol_built_ins(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under each folder [`SYMBOL_BUILT_INS`] names in a realm with +/// [`Options::es2015`], prints the counts of each and writes the failures to +/// `symbol-failures.txt` beside the suite. +fn run_symbol_built_ins(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in SYMBOL_BUILT_INS { + let root = or_fail(inside(dir, &format!("test/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let counts = run_tagged_tests(dir, &root, &missing, &options, SYMBOL_FEATURES); + println!("test262 {folder} with Options::es2015: {}.", counts.summary()); + report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + all.add(counts); + } + assert!(all.tests > 0, "no Symbol or iterator tests ran under {}", dir.display()); + let path = dir.join("symbol-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 Symbol and iterators 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. +fn run_tagged_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, options: &Options, features: &[&str]) -> RunCounts { + 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 mut counts = RunCounts::default(); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.flags.iter().any(|f| f == "module") || matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) { + continue; + } + let tagged_elsewhere = meta.features.iter().any(|f| !features.contains(&f.as_str())); + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if tagged_elsewhere || meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { + 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" }; + let body = if meta.flags.iter().any(|f| f == "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_with(options, &script, negative_type.as_deref())) { + 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")); + } + } + } + } + counts +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..9f6b452ea2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2644,6 +2644,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +A script does not have `Symbol` or the iterators of arrays, strings and `arguments` objects: `typeof Symbol` is +`"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. The JavaScript engine's ECMAScript +2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes. + Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..3264973bf5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,6 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From c021b269e7fd3ffff564c8b9b2a7414a63afc6af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:24:03 -0800 Subject: [PATCH 2/7] JavaScript: tighten Symbol conversions, lookups and host crossings in ES2015 realms - A string in `0b` or `0o` form converts to a number in a realm with `Options::es2015`, so an array iterator over an object whose length is "0b10" visits two elements. Realms without the option still read such strings as NaN. - `JSON.stringify` calls a String or Number object's `@@toPrimitive` method before using its stored value, for the value itself, a replacer list entry and the `space` argument. - A host function that returns a Symbol in a realm without the option throws a `TypeError`. A Symbol's description is charged to the heap before it is built. - A text function takes a Symbol as `String(symbol)` gives it, and a data function refuses an object or array with an enumerable Symbol-keyed property; checking the keys takes fuel. - A Symbol-keyed lookup takes a unit of fuel for each prototype it passes, and removing most of an object's Symbol keys releases their storage. --- crates/js/src/builtins/json.rs | 8 ++++- crates/js/src/chars.rs | 2 +- crates/js/src/host.rs | 17 ++++++++- crates/js/src/host_tests.rs | 39 +++++++++++++++++++++ crates/js/src/interp.rs | 32 +++++++++++------ crates/js/src/lib.rs | 10 +++--- crates/js/src/realm.rs | 3 +- crates/js/src/symbol.rs | 32 +++++++++++++++-- crates/js/src/symbol_tests.rs | 64 ++++++++++++++++++++++++++++++++++ crates/js/src/value.rs | 37 ++++++++++++++++---- docs/target-app-parity.md | 2 +- 11 files changed, 217 insertions(+), 29 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 6f659922b2..6fc8544e9d 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -570,6 +570,8 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K /// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that /// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and /// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found. +/// An `@@toPrimitive` method on the object, in a realm with [`crate::Options::es2015`], is called +/// before either (ECMA-262 11th edition, section 7.1.1). fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult> { let Value::Object(o) = v else { return Ok(None) }; let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) { @@ -578,7 +580,11 @@ fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult _ => return Ok(None), }; let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; - let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? }; + let p = match interp.exotic_to_primitive(*o, v, hint)? { + Some(p) => p, + None if reaches_prototype(interp, *o, proto, name)? => primitive, + None => interp.ordinary_to_primitive(*o, v, hint)?, + }; Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index 61b9a7f318..60df43513c 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option { } } -/// The value of the digit values `digits` in `radix` (8 or 16), rounded once to the nearest number +/// The value of the digit values `digits` in `radix` (2, 8 or 16), rounded once to the nearest number /// with ties to even (sections 7.8.3 and 9.3.1), or `None` when there are no digits. Digits are /// kept exactly in a `u128` while they fit; past that, each later digit counts only for its /// position and for whether any of the dropped bits is set. diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 967d5e3656..a57abaea06 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -269,6 +269,14 @@ impl Interp { return Err(self.data_error(r, ErrorType::Type, &what)); } }; + // Each Symbol key the scan may visit takes a unit of fuel first. + let syms = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); + if syms > 0 { + crate::regexp_vm::use_fuel_n(self, syms as u64)?; + } + if self.object(id)?.syms.as_ref().is_some_and(|m| m.iter().any(|(_, p)| p.enumerable())) { + return Err(self.data_error(r, ErrorType::Type, "has a Symbol-keyed property, not plain data")); + } r.ancestors.push(id); let out = match shape { Shape::Array(length) => self.read_array(id, length, r), @@ -529,7 +537,14 @@ impl Interp { /// `v` as the string `String(v)` gives, within the limits of a crossing. fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult { - let s = self.to_str(v)?; + let s = match v { + // `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1). + Value::Symbol(k) => match self.descriptive_string(k)? { + Value::String(s) => s, + _ => return Err(Abrupt::Internal("a Symbol's descriptive string is not a string".into())), + }, + _ => self.to_str(v)?, + }; self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?; Ok(Data::String(s.to_rust_string())) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..9fb7acc503 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -325,6 +325,45 @@ fn a_text_function_takes_each_argument_as_string_gives_it() { assert!(e.message.contains("no text"), "{}", e.message); } +#[test] +fn a_symbol_crosses_as_the_text_string_gives_it_and_never_as_data() { + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() }); + let seen = with_take(&mut r); + let texts: Rc>> = Rc::default(); + let log = texts.clone(); + let f: HostFunction = Rc::new(move |args| { + log.borrow_mut().extend(args); + Ok(Data::Undefined) + }); + r.define_host_object("text", vec![("of".into(), HostItem::TextFunction(f))]).unwrap(); + r.run("text.of(Symbol('tag'), Symbol())").unwrap(); + assert_eq!(texts.borrow().as_slice(), [Data::String("Symbol(tag)".into()), Data::String("Symbol()".into())]); + // An enumerable Symbol-keyed property is refused; one that is not enumerable is left out. + let probe = "var e = 'none'; var v = {a: 1}; v[Symbol('k')] = 2; try { host.take(v); } catch (x) { e = x.name + '|' + x.message; } e"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("TypeError|") && out.contains("has a Symbol-keyed property"), "{out}"); + let probe = "var e = 'none'; var v = [1]; v[Symbol('k')] = 2; try { host.take({list: v}); } catch (x) { e = x.name + '|' + x.message; } e"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("TypeError|") && out.contains(".list has a Symbol-keyed property"), "{out}"); + assert!(seen.borrow().is_empty(), "the function ran"); + r.run("var v = {a: 1}; Object.defineProperty(v, Symbol('k'), {value: 2}); host.take(v);").unwrap(); + assert_eq!(seen.borrow().as_slice(), [Data::Object(vec![("a".into(), Data::Number(1.0))])]); +} + +#[test] +fn checking_the_symbol_keys_of_a_value_takes_fuel() { + // Making the 20,000 hidden keys takes well under 3,000,000 units; the 500 crossings check + // 10,000,000 keys. + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 3_000_000, ..Limits::default() }); + with_take(&mut r); + let src = "var v = {}; for (var i = 0; i < 20000; i++) Object.defineProperty(v, Symbol(), {value: i}); \ + for (var j = 0; j < 500; j++) host.take(v);"; + match r.run(src) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } +} + #[test] fn errors_from_the_host_can_be_caught_and_an_abort_cannot() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 13ac5cd834..742e31330f 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2776,11 +2776,17 @@ impl Interp { if let Some(r) = self.exotic_to_primitive(*o, v, hint)? { return Ok(r); } + self.ordinary_to_primitive(*o, v, hint) + } + + /// [[DefaultValue]] (section 8.12.8) of the object `o`, which is `v`: ToPrimitive without the + /// `@@toPrimitive` method. + pub(crate) fn ordinary_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult { // Without a hint, a Date object converts as with the String hint. - let date = hint == Hint::Default && matches!(self.heap.object(*o).map(|ob| &ob.class), Some(Class::Date(_))); + let date = hint == Hint::Default && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_))); let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] }; for name in order { - let f = self.get_from(*o, &key(name), v)?; + let f = self.get_from(o, &key(name), v)?; if self.is_callable(&f) { let r = self.call(&f, v, &[])?; if !matches!(r, Value::Object(_)) { @@ -2791,6 +2797,8 @@ impl Interp { Err(self.type_error("cannot convert the object to a primitive value")) } + /// ToNumber (section 9.3). In a realm with [`crate::Options::es2015`], a string may also be a + /// `0b` or `0o` literal (ECMA-262 11th edition, section 7.1.3.1). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_number(&mut self, v: &Value) -> JsResult { Ok(match v { @@ -2798,7 +2806,7 @@ impl Interp { Value::Null => 0.0, Value::Bool(b) => f64::from(u8::from(*b)), Value::Number(n) => *n, - Value::String(s) => string_to_number(&flat_charged(self, s)?), + Value::String(s) => string_to_number(&flat_charged(self, s)?, self.options.es2015), Value::Symbol(_) => return Err(self.type_error("cannot convert a Symbol value to a number")), Value::Object(_) => { let p = self.to_primitive(v, Hint::Number)?; @@ -3035,7 +3043,7 @@ impl Interp { | (Value::Symbol(_), Value::Symbol(_)) | (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)), (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => { - return Ok(*n == string_to_number(&flat_charged(self, s)?)); + return Ok(*n == string_to_number(&flat_charged(self, s)?, self.options.es2015)); } (Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))), (_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))), @@ -3105,9 +3113,10 @@ impl Interp { } } - /// A host value as a JavaScript value. A string is charged to the heap, and one that does not - /// fit in it ends the run with the heap limit. Everything the caller still needs must be - /// reachable from the roots. + /// A host value as a JavaScript value. A string or a Symbol's description is charged to the + /// heap before it is built, and one that does not fit in it ends the run with the heap limit. + /// A Symbol in a realm without [`crate::Options::es2015`] throws a `TypeError`. Everything the + /// caller still needs must be reachable from the roots. #[allow(clippy::wrong_self_convention)] pub(crate) fn from_js_value(&mut self, v: crate::JsValue) -> JsResult { Ok(match v { @@ -3122,12 +3131,15 @@ impl Interp { Value::str(&s) } crate::JsValue::Object(_) => Value::Object(self.new_object()), + crate::JsValue::Symbol(_) if !self.options.es2015 => { + return Err(self.type_error("a host function returned a Symbol in a realm without Symbol")); + } crate::JsValue::Symbol(description) => { - let units: Option> = description.map(|d| d.encode_utf16().collect()); - let bytes = crate::heap::SYMBOL_BYTES + units.as_ref().map_or(0, |u| string_bytes(u.len())); + let bytes = crate::heap::SYMBOL_BYTES + description.as_ref().map_or(0, |d| string_bytes(d.encode_utf16().count())); self.reserve_heap(bytes)?; self.heap.bytes += bytes; - Value::Symbol(crate::symbol::Sym::new(units.map(Str::from_units), false)) + let description = description.map(|d| Str::from_units(d.encode_utf16().collect())); + Value::Symbol(crate::symbol::Sym::new(description, false)) } }) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index c5e45af08f..4cdb639c85 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -55,8 +55,9 @@ //! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and //! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. A //! Symbol converted to a string or a number without `String(symbol)` or `toString` throws a -//! `TypeError`. Every iterator step takes fuel, and every Symbol and registry entry counts against -//! the heap limit. +//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator +//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry +//! entry counts against the heap limit. #![forbid(unsafe_code)] pub mod ast; @@ -113,8 +114,9 @@ pub struct Options { /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, /// Give a realm the later editions' built-ins this engine has: `Symbol` with Symbol-keyed - /// properties and the iterators of arrays, strings and `arguments` objects. Off, a realm has - /// the ES5.1 built-ins only, as the app's scripts expect. + /// properties and the iterators of arrays, strings and `arguments` objects, with `0b` and `0o` + /// strings converting to numbers. Off, a realm has the ES5.1 built-ins only, as the app's + /// scripts expect. pub es2015: bool, } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 08d9913948..ae3021dada 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -110,7 +110,8 @@ impl Interrupt { } /// A value passed between a script and the host. An object is given by its class name, and a -/// Symbol by its description; a Symbol the host passes in is a new Symbol each time. +/// Symbol by its description; a Symbol the host passes in is a new Symbol each time, and one a +/// host function returns in a realm without [`Options::es2015`] throws a `TypeError`. #[derive(Clone, Debug, PartialEq)] pub enum JsValue { Undefined, diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 2c25ebd099..34fd489fa3 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -127,6 +127,7 @@ impl SymProps { let (_, prop) = self.entries.get_mut(i)?.take()?; if self.entries.len() > 16 && self.index.len() * 2 < self.entries.len() { self.entries.retain(Option::is_some); + self.entries.shrink_to_fit(); self.index = self.entries.iter().enumerate().filter_map(|(i, e)| e.as_ref().map(|(k, _)| (k.clone(), i))).collect(); } Some(prop) @@ -304,8 +305,9 @@ impl Interp { Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) } - /// The property `k` found on the object or its prototype chain. - pub(crate) fn find_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + /// The property `k` found on the object or its prototype chain. Each step to a prototype takes + /// a unit of fuel. + pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { @@ -313,6 +315,9 @@ impl Interp { return Ok(Some(p)); } cur = self.object(o)?.proto; + if cur.is_some() { + self.use_fuel()?; + } steps += 1; if steps > 1_000_000 { return Err(crate::interp::Abrupt::Internal("prototype chain too long".into())); @@ -464,7 +469,7 @@ impl Interp { } } - pub(crate) fn has_pk(&self, id: ObjId, k: &PropKey) -> JsResult { + pub(crate) fn has_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult { match k { PropKey::Str(name) => self.has_property(id, name), PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()), @@ -579,3 +584,24 @@ impl Interp { } } } + +#[cfg(test)] +mod tests { + use super::{Sym, SymProps}; + use crate::heap::{OPEN, Prop}; + use crate::value::Value; + + #[test] + fn removing_most_symbol_keys_gives_back_their_room_and_keeps_the_order() { + let mut m = SymProps::default(); + let keys: Vec = (0..100).map(|_| Sym::new(None, false)).collect(); + for k in &keys { + m.insert(k.clone(), Prop::Data { value: Value::Undefined, flags: OPEN }); + } + for k in &keys[..90] { + m.remove(k); + } + assert!(m.entries.capacity() < 64, "{}", m.entries.capacity()); + assert_eq!(m.iter().map(|(k, _)| k.clone()).collect::>(), keys[90..]); + } +} diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index d877e04106..5e372bdafd 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -219,6 +219,70 @@ fn an_array_iterator_keeps_its_object_while_reading_its_length_runs_script() { assert_eq!(string(src), "x false true"); } +#[test] +fn binary_and_octal_strings_are_numbers_in_an_es2015_realm_only() { + for length in ["0b10", "0o2", "2"] { + let src = format!( + "var it = Array.prototype.values.call({{0: 'first', 1: 'second', length: '{length}'}}); \ + var a = it.next(), b = it.next(); a.value + ' ' + b.value + ' ' + it.next().done" + ); + assert_eq!(string(&src), "first second true", "{length}"); + } + truth("Number('0b101') === 5 && +'0O17' === 15 && '0b11' == 3 && isNaN('0b2') && isNaN('-0o1')"); + let src = "isNaN(Number('0b10')) && isNaN(+'0o2') && '0b1' != 1"; + assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(src), Ok(JsValue::Bool(true))); +} + +#[test] +fn json_calls_the_to_primitive_method_of_a_wrapper() { + let hook = "w[Symbol.toPrimitive] = function (hint) { return hint === 'number' ? 2 : 'b'; };"; + truth(&format!("var w = new String('x'); {hook} JSON.stringify(w) === '\"b\"'")); + truth(&format!("var w = new String('x'); delete String.prototype.toString; {hook} JSON.stringify(w) === '\"b\"'")); + truth(&format!("var w = new String('x'); {hook} JSON.stringify({{a: 1, b: 2}}, [w]) === '{{\"b\":2}}'")); + truth(&format!("var w = new Number(5); {hook} JSON.stringify([w], null, w) === '[\\n 2\\n]'")); + truth("JSON.stringify([new String('x'), new Number(1)], null, new Number(1)) === '[\\n \"x\",\\n 1\\n]'"); +} + +#[test] +fn a_host_function_returns_a_symbol_only_in_an_es2015_realm() { + let symbol = |_: &[JsValue]| -> Result { Ok(JsValue::Symbol(Some("from host".into()))) }; + let mut realm = es2015(Limits::default()); + realm.define_function("make", symbol); + assert_eq!(realm.run("var s = make(); typeof s === 'symbol' && String(s) === 'Symbol(from host)' && s !== make()"), Ok(JsValue::Bool(true))); + let mut realm = Realm::with_options(Options::default(), Limits::default()); + realm.define_function("make", symbol); + let src = "try { make(); 'none'; } catch (e) { (e instanceof TypeError) + ' ' + typeof Symbol; }"; + assert_eq!(realm.run(src), Ok(JsValue::String("true undefined".into()))); +} + +#[test] +fn a_host_symbol_description_counts_against_the_heap_before_it_is_made() { + let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() }); + realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1 << 20))))); + match realm.run("make()") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{other:?}"), + } + let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() }); + realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1_000))))); + assert_eq!(realm.run("make().description.length"), Ok(JsValue::Number(1_000.0))); +} + +#[test] +fn a_symbol_lookup_takes_fuel_for_each_prototype() { + // Building the chain takes about 20,000 units; each lookup of an absent Symbol walks all 2,000 + // prototypes, so the 100 lookups take 200,000 more. + let src = "var s = Symbol(), o = {}; for (var i = 0; i < 2000; i++) o = Object.create(o); \ + for (var j = 0; j < 100; j++) s in o;"; + match es2015(Limits { fuel: 150_000, ..Limits::default() }).run(src) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + let src = "var s = Symbol(), root = {}, o = root; root[s] = 'found'; for (var i = 0; i < 50; i++) o = Object.create(o); \ + o[s] === 'found' && s in o && !o.hasOwnProperty(s)"; + truth(src); +} + #[test] fn iterator_steps_take_fuel() { let mut realm = es2015(Limits { fuel: 5_000, ..Limits::default() }); diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index 66005773e2..4911c6e36b 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -263,9 +263,10 @@ pub(crate) fn is_str_space(u: u16) -> bool { crate::chars::is_whitespace(u32::from(u)) || crate::chars::is_line_terminator(u32::from(u)) } -/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, NaN for -/// anything else. -pub(crate) fn string_to_number(units: &[u16]) -> f64 { +/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, with the `0b` +/// and `0o` literals of ECMA-262 11th edition, section 7.1.3.1, as well when `binary_octal` is +/// set; NaN for anything else. +pub(crate) fn string_to_number(units: &[u16], binary_octal: bool) -> f64 { let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len()); let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |i| i + 1); let Some(text) = units.get(start..end) else { return f64::NAN }; @@ -279,6 +280,15 @@ pub(crate) fn string_to_number(units: &[u16]) -> f64 { } return crate::chars::radix_value(hex.bytes().filter_map(|b| crate::chars::hex_value(u32::from(b))), 16).unwrap_or(f64::NAN); } + if binary_octal { + for (prefix, radix) in [("0b", 2), ("0B", 2), ("0o", 8), ("0O", 8)] { + let Some(digits) = s.strip_prefix(prefix) else { continue }; + if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) { + return f64::NAN; + } + return crate::chars::radix_value(digits.chars().filter_map(|c| c.to_digit(radix)), radix).unwrap_or(f64::NAN); + } + } let (sign, body) = match s.as_bytes().first() { Some(b'+') => (1.0, &s[1..]), Some(b'-') => (-1.0, &s[1..]), @@ -386,19 +396,32 @@ mod tests { ("-Infinity", f64::NEG_INFINITY), ]; for (s, want) in cases { - assert_eq!(string_to_number(&u(s)), *want, "{s:?}"); + assert_eq!(string_to_number(&u(s), false), *want, "{s:?}"); } for s in ["inf", "nan", "1_0", "0x", "1e", ".", "--1", "0x-1", "infinity", "1 2"] { - assert!(string_to_number(&u(s)).is_nan(), "{s:?}"); + assert!(string_to_number(&u(s), false).is_nan(), "{s:?}"); + } + } + + #[test] + fn binary_and_octal_strings_convert_only_when_asked() { + for (s, want) in [("0b10", 2.0), ("0B11", 3.0), (" 0o17 ", 15.0), ("0O7", 7.0), ("0x10", 16.0), ("2", 2.0)] { + assert_eq!(string_to_number(&u(s), true), want, "{s:?}"); + } + for s in ["0b", "0b2", "0o8", "-0b1", "+0o1", "0b1.0", "0o"] { + assert!(string_to_number(&u(s), true).is_nan(), "{s:?}"); + } + for s in ["0b10", "0o2"] { + assert!(string_to_number(&u(s), false).is_nan(), "{s:?}"); } } #[test] fn hex_strings_round_once_to_the_nearest_number() { - assert_eq!(string_to_number(&u("0xc83ce80553ee648")), 0xc83_ce80_553e_e648_u64 as f64); + assert_eq!(string_to_number(&u("0xc83ce80553ee648"), false), 0xc83_ce80_553e_e648_u64 as f64); // 2^136 + 2^83 + 1: a set bit past 128 bits rounds the half-way case up. let digits = format!("0x1{}8{}1", "0".repeat(13), "0".repeat(19)); - assert_eq!(string_to_number(&u(&digits)), 2f64.powi(136) + 2f64.powi(84)); + assert_eq!(string_to_number(&u(&digits), false), 2f64.powi(136) + 2f64.powi(84)); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3264973bf5..2579945202 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,7 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. 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. 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`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From e4751813293ca576c08eb8900e88910e6e7c98d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:56:22 -0800 Subject: [PATCH 3/7] JavaScript: Date.prototype[@@toPrimitive] and ToPrimitive fixes in ES2015 realms In a realm with `Options::es2015`, `Date.prototype[Symbol.toPrimitive]` converts with `toString` first for the hints "string" and "default" and with `valueOf` first for "number" (ECMA-262 11th edition, section 20.4.4.45). An object without an `@@toPrimitive` method, a Date whose own method is `null` or `undefined` included, converts without a hint with `valueOf` first (section 7.1.1.1), so `d + 1` gives 8 when `valueOf` returns 7. A realm without the option keeps the ES5 order for a Date. `JSON.stringify` converts a Number or String object with ToPrimitive. A `valueOf` or `toString` deleted from the object's own prototype is now looked up further along the chain, so `Object.prototype.toString` is called instead of the stored primitive value being returned. A Symbol that an object's `@@toPrimitive` method gives as a property key is rooted while the property is read or incremented, so it and its description still count against the heap when a getter starts a collection. --- crates/js/src/builtins/json.rs | 42 ++++----------------- crates/js/src/builtins/symbol.rs | 32 +++++++++++++--- crates/js/src/builtins_tests.rs | 4 ++ crates/js/src/interp.rs | 7 +++- crates/js/src/lib.rs | 6 ++- crates/js/src/symbol.rs | 8 ++-- crates/js/src/symbol_tests.rs | 65 ++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 8 files changed, 118 insertions(+), 48 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 6fc8544e9d..e01a47b085 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -565,47 +565,21 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K /// ToNumber of a Number object, or ToString of a String object (of either when `as_string` is /// set), as section 15.12.3 applies them in Str step 4, step 4.b.ii and step 5. Returns `None` -/// for any other value. When the method that [[DefaultValue]] (section 8.12.8) calls first is not -/// found on the object or on its prototype chain before the object's standard prototype, the -/// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that -/// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and -/// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found. -/// An `@@toPrimitive` method on the object, in a realm with [`crate::Options::es2015`], is called -/// before either (ECMA-262 11th edition, section 7.1.1). +/// for any other value. The conversion is ToPrimitive (section 9.1) with the Number or String +/// hint, so `valueOf` and `toString` are looked up along the object's whole prototype chain, and +/// in a realm with [`crate::Options::es2015`] an `@@toPrimitive` method on the object is called +/// first (ECMA-262 11th edition, section 7.1.1). fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult> { let Value::Object(o) = v else { return Ok(None) }; - let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) { - Some(Class::Number(n)) => (Value::Number(*n), interp.intrinsics.number_proto, as_string), - Some(Class::String(s)) => (Value::String(s.clone()), interp.intrinsics.string_proto, true), + let string = match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Number(_)) => as_string, + Some(Class::String(_)) => true, _ => return Ok(None), }; - let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; - let p = match interp.exotic_to_primitive(*o, v, hint)? { - Some(p) => p, - None if reaches_prototype(interp, *o, proto, name)? => primitive, - None => interp.ordinary_to_primitive(*o, v, hint)?, - }; + let p = interp.to_primitive(v, if string { Hint::String } else { Hint::Number })?; Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } -/// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before -/// any object on the way, `proto` included, has its own property `name`. -fn reaches_prototype(interp: &mut Interp, o: ObjId, proto: ObjId, name: &str) -> JsResult { - let k = key(name); - let mut cur = Some(o); - while let Some(id) = cur { - interp.use_fuel()?; - if interp.get_own_property(id, &k)?.is_some() { - return Ok(false); - } - if id == proto { - return Ok(true); - } - cur = interp.heap.object(id).and_then(|x| x.proto); - } - Ok(false) -} - /// Quote (section 15.12.3): the string in double quotes with the characters JSON escapes. fn write_quoted(interp: &mut Interp, out: &mut Builder, s: &[u16]) -> JsResult<()> { out.push_units(interp, &[QUOTE])?; diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index f0afe7b2f8..b671f51e42 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -1,12 +1,12 @@ //! `Symbol` (ECMA-262 11th edition, section 19.4, ): //! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of -//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10) and -//! `Function.prototype[@@hasInstance]` (section 19.2.3.6). Installed in a realm with -//! [`crate::Options::es2015`] only. +//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10), +//! `Function.prototype[@@hasInstance]` (section 19.2.3.6) and `Date.prototype[@@toPrimitive]` +//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only. use super::{arg, constructor, create_at, data, method, native, new_array}; use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; -use crate::interp::{Interp, JsResult}; +use crate::interp::{Hint, Interp, JsResult}; use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; use crate::value::{Str, Value}; @@ -37,7 +37,9 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?; interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?; interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?; - sym_method(interp, proto, to_primitive, "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + sym_method(interp, proto, to_primitive.clone(), "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + let date_proto = interp.intrinsics.date_proto; + sym_method(interp, date_proto, to_primitive, "[Symbol.toPrimitive]", date_to_primitive, 1, CONFIGURABLE)?; method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; @@ -138,6 +140,26 @@ fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) - this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol) } +/// `Date.prototype[@@toPrimitive](hint)` (section 20.4.4.45): OrdinaryToPrimitive of any object, +/// `toString` first for the hints `"string"` and `"default"` and `valueOf` first for `"number"`. +/// Any other hint, or a `this` that is not an object, throws a `TypeError`. +fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let Value::Object(o) = this else { + return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was called on a value that is not an object")); + }; + // The longest hint has 7 units, so a longer string is refused before it is flattened. + let name = match arg(args, 0) { + Value::String(s) if s.len() <= 7 => String::from_utf16_lossy(&s.flat()), + _ => String::new(), + }; + let hint = match name.as_str() { + "string" | "default" => Hint::String, + "number" => Hint::Number, + _ => return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was given a hint that is not \"string\", \"number\" or \"default\"")), + }; + interp.ordinary_to_primitive(o, &this, hint) +} + /// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the /// order they were added. fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 0a70e80433..c009dddc9a 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -684,6 +684,10 @@ fn json_stringify_unwraps_number_string_and_boolean_objects() { assert_eq!(string("Object.prototype.valueOf = function () { return 9; }; JSON.stringify(Object(3))"), "3"); assert_eq!(string("Object.getPrototypeOf(Object(1)).valueOf = function () { return 4; }; JSON.stringify(Object(3))"), "4"); assert_eq!(string("Object.getPrototypeOf(Object('')).toString = function () { return 'q'; }; JSON.stringify(Object('abc'))"), "\"q\""); + // Once the own prototype's method is deleted, the lookup goes on to Object.prototype. + let over = "Object.prototype.toString = function () { return '7'; };"; + assert_eq!(string(&format!("{over} delete String.prototype.toString; JSON.stringify(Object('abc'))")), "\"7\""); + assert_eq!(string(&format!("{over} delete Number.prototype.valueOf; delete Number.prototype.toString; JSON.stringify(Object(3))")), "7"); } #[test] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 742e31330f..3c6f73cb64 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2782,8 +2782,11 @@ impl Interp { /// [[DefaultValue]] (section 8.12.8) of the object `o`, which is `v`: ToPrimitive without the /// `@@toPrimitive` method. pub(crate) fn ordinary_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult { - // Without a hint, a Date object converts as with the String hint. - let date = hint == Hint::Default && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_))); + // Without a hint, a Date object converts as with the String hint. In a realm with + // `Options::es2015`, `Date.prototype[@@toPrimitive]` picks that order for a Date instead, + // and OrdinaryToPrimitive treats a missing hint as the Number hint (ECMA-262 11th edition, + // sections 7.1.1.1 and 20.4.4.45). + let date = hint == Hint::Default && !self.options.es2015 && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_))); let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] }; for name in order { let f = self.get_from(o, &key(name), v)?; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 4cdb639c85..4b02563e08 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -53,8 +53,10 @@ //! `hasInstance`, `toPrimitive` and `toStringTag` with the hooks ToPrimitive, `instanceof` and //! `Object.prototype.toString` read, Symbol-keyed properties with `Object.getOwnPropertySymbols`, //! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and -//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. A -//! Symbol converted to a string or a number without `String(symbol)` or `toString` throws a +//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. +//! `Date.prototype[@@toPrimitive]` converts a Date without a hint as with the String hint, and an +//! object without an `@@toPrimitive` method, a Date included, converts without a hint as with the +//! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a //! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator //! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry //! entry counts against the heap limit. diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 34fd489fa3..e89bbeb9f4 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -239,10 +239,10 @@ impl Interp { Value::Symbol(s) => f(self, PropKey::Sym(s.clone())), Value::Object(_) => { let p = self.to_primitive(v, Hint::String)?; - if let Value::Symbol(s) = p { - return f(self, PropKey::Sym(s)); - } - self.rooted(std::slice::from_ref(&p), |i| i.with_key(&p, |i, k| f(i, PropKey::Str(k)))) + self.rooted(std::slice::from_ref(&p), |i| match &p { + Value::Symbol(s) => f(i, PropKey::Sym(s.clone())), + _ => i.with_key(&p, |i, k| f(i, PropKey::Str(k))), + }) } _ => self.with_key(v, |i, k| f(i, PropKey::Str(k))), } diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index 5e372bdafd..a11c105107 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -241,6 +241,71 @@ fn json_calls_the_to_primitive_method_of_a_wrapper() { truth(&format!("var w = new String('x'); {hook} JSON.stringify({{a: 1, b: 2}}, [w]) === '{{\"b\":2}}'")); truth(&format!("var w = new Number(5); {hook} JSON.stringify([w], null, w) === '[\\n 2\\n]'")); truth("JSON.stringify([new String('x'), new Number(1)], null, new Number(1)) === '[\\n \"x\",\\n 1\\n]'"); + // A `@@toPrimitive` getter that deletes the prototype's method and gives `undefined` sends the + // lookup on to `Object.prototype`. + let getter = |method: &str| { + format!( + "Object.defineProperty(w, Symbol.toPrimitive, {{ get: function () {{ delete Object.getPrototypeOf(w).{method}; return undefined; }} }});" + ) + }; + let over = "Object.prototype.toString = function () { return '7'; };"; + truth(&format!("var w = new String('x'); {over} {} JSON.stringify(w) === '\"7\"'", getter("toString"))); + truth(&format!("var w = new Number(3); {over} delete Number.prototype.toString; {} JSON.stringify(w) === '7'", getter("valueOf"))); +} + +#[test] +fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_used() { + // `mk(n)` makes a string of `n` units. The key's accessor deletes itself from + // `Object.prototype`, so when the key is a Symbol only the read or write holds it and its + // description of 2,000,000 units, and then makes a string of 1,500,000 units. With `keep` + // (1,000,000 units) and a description still counted, that string does not fit; without one it + // does. + let src = |key: &str, access: &str| { + format!( + "function mk(n) {{ return new Array(n + 1).join('x'); }} \ + var keep = mk(1000000), made = null; \ + function use() {{ var p = Object.prototype; delete p[Object.getOwnPropertySymbols(p)[0] || 'k']; \ + made = mk(1500000); return 0; }} \ + var w = {{}}; w[Symbol.toPrimitive] = function () {{ var k = {key}; \ + Object.defineProperty(Object.prototype, k, {{ configurable: true, get: use, set: use }}); return k; }}; \ + {access}; made.length" + ) + }; + let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() }; + for access in ["({})[w]", "({})[w] = 1", "({})[w]++"] { + // A name as the key leaves the Symbol and its description to the collector, and the string + // fits. + assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 'k')", access)), Ok(JsValue::Number(1_500_000.0)), "{access}"); + match es2015(limits()).run(&src("Symbol(mk(2000000))", access)) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{access}: {other:?}"), + } + } +} + +#[test] +fn date_objects_convert_through_their_to_primitive_method() { + let date = "var d = new Date(0); d.valueOf = function () { return 7; }; d.toString = function () { return 'date'; };"; + truth(&format!("{date} d + 1 === 'date1' && d * 1 === 7 && String(d) === 'date' && (d == 'date')")); + // Without a method, a Date converts with `valueOf` first when no hint is given. + // The inherited method is read-only, so an assignment does not shadow it. + truth(&format!("{date} d[Symbol.toPrimitive] = null; d + 1 === 'date1'")); + truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: null }}); d + 1 === 8")); + truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: undefined }}); d + 1 === 8 && String(d) === 'date'")); + truth(&format!("{date} delete Date.prototype[Symbol.toPrimitive]; d + 1 === 8 && d == 7")); + // The method itself, on any object. + truth( + "var m = Date.prototype[Symbol.toPrimitive], p = Object.getOwnPropertyDescriptor(Date.prototype, Symbol.toPrimitive); \ + typeof m === 'function' && m.length === 1 && !p.writable && !p.enumerable && p.configurable", + ); + let o = "var o = { valueOf: function () { return 7; }, toString: function () { return 's'; } }, m = Date.prototype[Symbol.toPrimitive];"; + truth(&format!("{o} m.call(o, 'number') === 7 && m.call(o, 'string') === 's' && m.call(o, 'default') === 's'")); + for call in ["m.call(o)", "m.call(o, 'other')", "m.call(o, new String('number'))", "m.call(1, 'number')", "m.call(o, 'defaultx')"] { + throws(&format!("{o} {call}"), "TypeError"); + } + // A realm without the option keeps the String-hint order for a Date. + let src = format!("{date} d + 1 === 'date1' && d * 1 === 7"); + assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(&src), Ok(JsValue::Bool(true))); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2579945202..48ce92a005 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,7 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `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. 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` 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`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 93df144331b105009fc7fe966abd3bd8641079e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:35:00 -0800 Subject: [PATCH 4/7] JavaScript: keep Symbol keys and converted operands counted while script runs Object.defineProperties and Object.create now keep the Symbol keys of the properties object rooted until they are defined, so a getter that deletes a Symbol-keyed property already read no longer lets a collection drop the Symbol's description from the heap count. The + operator and the relational comparisons now keep the first operand's converted value rooted while the second operand's @@toPrimitive or valueOf runs, so a fresh Symbol or string from the first conversion stays counted against the heap limit. --- crates/js/src/builtins/object.rs | 10 ++++++- crates/js/src/interp.rs | 9 ++++-- crates/js/src/symbol_tests.rs | 51 ++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 48fdbb6eda..42947c7d7a 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -198,7 +198,15 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - for k in own_prop_keys(interp, p)? { + let keys = own_prop_keys(interp, p)?; + // A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted + // until they are defined on `o`. + for k in &keys { + if let PropKey::Sym(s) = k { + interp.temp_roots.push(Value::Symbol(s.clone())); + } + } + for k in keys { interp.use_fuel()?; if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) { continue; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 3c6f73cb64..405874dc96 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2993,7 +2993,8 @@ impl Interp { return self.xml_concat(a, b); } let pa = self.to_primitive(a, Hint::Default)?; - let pb = self.to_primitive(b, Hint::Default)?; + // The right side's conversion can run script, so the left side's result stays counted. + let pb = self.rooted(std::slice::from_ref(&pa), |i| i.to_primitive(b, Hint::Default))?; if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) { // Both are primitives, so this converts them without running script code; a Symbol // throws. @@ -3007,12 +3008,14 @@ impl Interp { /// The abstract relational comparison `x < y` (section 11.8.5): `None` when either side is /// NaN. fn less_than(&mut self, x: &Value, y: &Value, left_first: bool) -> JsResult> { + // The second conversion can run script, so the first one's result stays counted. let (px, py) = if left_first { let px = self.to_primitive(x, Hint::Number)?; - (px, self.to_primitive(y, Hint::Number)?) + let py = self.rooted(std::slice::from_ref(&px), |i| i.to_primitive(y, Hint::Number))?; + (px, py) } else { let py = self.to_primitive(y, Hint::Number)?; - (self.to_primitive(x, Hint::Number)?, py) + (self.rooted(std::slice::from_ref(&py), |i| i.to_primitive(x, Hint::Number))?, py) }; if let (Value::String(a), Value::String(b)) = (&px, &py) { // Both stay rooted, so the first copy is still counted while the second is made. diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index a11c105107..6ea28e1dee 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -283,6 +283,57 @@ fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_ } } +#[test] +fn define_properties_keeps_a_symbol_key_counted_after_a_getter_deletes_it() { + // The second Symbol-keyed descriptor's getter deletes the first property, drops `s` and makes + // a string of 1,500,000 units. With `keep` (1,000,000 units) and the first Symbol's + // description of 2,000,000 units still counted, that string does not fit; with a short + // description it does. + let src = |description: &str, define: &str| { + format!( + "function mk(n) {{ return new Array(n + 1).join('x'); }} \ + var keep = mk(1000000), made = null, s = Symbol({description}), props = {{}}; \ + props[s] = {{ value: 1, enumerable: true }}; \ + Object.defineProperty(props, Symbol('t'), {{ enumerable: true, get: function () {{ \ + delete props[s]; s = null; made = mk(1500000); return {{ value: 2 }}; }} }}); \ + var o = {define}; o[Object.getOwnPropertySymbols(o)[0]] + ' ' + made.length" + ) + }; + let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() }; + for define in ["Object.defineProperties({}, props)", "Object.create(null, props)"] { + assert_eq!(es2015(limits()).run(&src("'d'", define)), Ok(JsValue::String("1 1500000".into())), "{define}"); + match es2015(limits()).run(&src("mk(2000000)", define)) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{define}: {other:?}"), + } + } +} + +#[test] +fn an_operator_keeps_the_first_operand_converted_while_it_converts_the_second() { + // `a` converts to a Symbol with a description of 2,000,000 units that nothing else holds, and + // `b`'s conversion makes a string of 1,500,000 units. With `keep` (1,000,000 units) and the + // description still counted, that string does not fit; when `a` gives a number it does. + let src = |first: &str, op: &str| { + format!( + "function mk(n) {{ return new Array(n + 1).join('x'); }} \ + var keep = mk(1000000), made = null; \ + var a = {{}}; a[Symbol.toPrimitive] = function () {{ return {first}; }}; \ + var b = {{}}; b[Symbol.toPrimitive] = function () {{ made = mk(1500000); return 1; }}; \ + try {{ a {op} b; }} catch (e) {{ if (!(e instanceof TypeError)) throw e; }} \ + made.length === 1500000" + ) + }; + let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() }; + for op in ["+", "<", ">", "<=", ">="] { + assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 0)", op)), Ok(JsValue::Bool(true)), "{op}"); + match es2015(limits()).run(&src("Symbol(mk(2000000))", op)) { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {} + other => panic!("{op}: {other:?}"), + } + } +} + #[test] fn date_objects_convert_through_their_to_primitive_method() { let date = "var d = new Date(0); d.valueOf = function () { return 7; }; d.toString = function () { return 'date'; };"; From 30eb12aba37a97ff2abc0894a4d1dcdc48165303 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:15:47 -0800 Subject: [PATCH 5/7] 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. --- crates/engine/src/tests/script_run.rs | 27 ++ crates/js/src/ast.rs | 8 + crates/js/src/builtins.rs | 25 +- crates/js/src/builtins/generator.rs | 51 ++++ crates/js/src/builtins/iterator.rs | 2 +- crates/js/src/builtins/symbol.rs | 5 +- crates/js/src/bytecode.rs | 33 +++ crates/js/src/compiler.rs | 85 +++++- crates/js/src/generator.rs | 410 ++++++++++++++++++++++++++ crates/js/src/generator_tests.rs | 305 +++++++++++++++++++ crates/js/src/heap.rs | 24 +- crates/js/src/interp.rs | 83 +++++- crates/js/src/interp_tests.rs | 1 + crates/js/src/lib.rs | 16 +- crates/js/src/parser.rs | 156 ++++++++-- crates/js/src/realm.rs | 3 + crates/js/src/symbol.rs | 16 +- crates/js/tests/test262.rs | 100 +++++++ docs/mcp.md | 12 +- docs/target-app-parity.md | 3 +- 20 files changed, 1312 insertions(+), 53 deletions(-) create mode 100644 crates/js/src/builtins/generator.rs create mode 100644 crates/js/src/generator.rs create mode 100644 crates/js/src/generator_tests.rs diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..d6ca60461c 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -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())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..c8fddfdcc2 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -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, + 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, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 9fc8ba3539..9091441937 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,8 +3,9 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, 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 { - 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 { @@ -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 { - const HEAD: &str = "(function anonymous("; + create_dynamic_function(interp, args, false) +} + +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with +/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { + let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -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)), }; diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs new file mode 100644 index 0000000000..c8e46e09d6 --- /dev/null +++ b/crates/js/src/builtins/generator.rs @@ -0,0 +1,51 @@ +//! The generator built-ins (ECMA-262 11th edition, ): +//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and +//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits +//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the +//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator +//! function's `constructor`. + +use super::{data, native, unreachable_native}; +use crate::generator::ResumeMode; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { + let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) }; + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto); + + let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] { + let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?; + data(interp, generator_proto, name, Value::Object(m), HIDDEN)?; + } + interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?; + + let function_proto = interp.intrinsics.function_proto; + // %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from + // Function.prototype (section 25.2.3). + let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?; + data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?; + interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?; + + let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(generator_function) { + o.proto = Some(function); + } + data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?; + data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?; + + objects.generator_proto = generator_proto; + objects.generator_function_proto = generator_function_proto; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). +fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + super::create_dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs index 317b66ecc2..09462496a3 100644 --- a/crates/js/src/builtins/iterator.rs +++ b/crates/js/src/builtins/iterator.rs @@ -78,7 +78,7 @@ fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult { +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES))?; let proto = interp.intrinsics.object_proto; let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..109493a03d 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; - // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + // The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators + // and generators are installed. interp.symbols.objects = Some(Es2015Objects { symbol_proto: proto, array_iterator_proto: proto, string_iterator_proto: proto, array_values: has_instance, has_instance, + generator_proto: proto, + generator_function_proto: function_proto, }); Ok(()) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..91f7cfa5f6 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -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]) -> Result { 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(()), } } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..fe4c5cd95e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -99,6 +99,8 @@ struct FnCompiler<'a> { block_funcs: HashSet, /// The function declarations in blocks whose names are also var-scoped (Annex B.3.3). annex: HashSet, + /// 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, 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 = 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, } c.emit(Op::BodyEnv); } + if f.generator { + // The call has bound the arguments and run the default values; the body waits for + // the first `next` (ECMA-262 2015 section 14.4.11). + c.at(f.span.start); + c.emit(Op::GeneratorStart); + } c.stmts(&f.body)?; c.at(f.span.end.saturating_sub(1)); c.emit(Op::Undefined); diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs new file mode 100644 index 0000000000..5169dcb2d0 --- /dev/null +++ b/crates/js/src/generator.rs @@ -0,0 +1,410 @@ +//! Generator objects (ECMA-262 11th edition, , +//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`]. +//! +//! A call to a generator function runs its parameters' initialization and stops at +//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally` +//! blocks it is inside, moves into a new generator object, which the call returns. `next`, +//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same +//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit +//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A +//! suspended generator's frame is reachable only through its object, so the collector keeps it +//! while the object is reachable and frees it with the object. +//! +//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart + +use std::rc::Rc; + +use crate::LimitKind; +use crate::builtins::iterator::iter_result; +use crate::bytecode::Code; +use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; +use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::value::Value; + +/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). +/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResumeMode { + Next, + Throw, + Return, +} + +impl ResumeMode { + fn number(self) -> f64 { + match self { + ResumeMode::Next => 0.0, + ResumeMode::Throw => 1.0, + ResumeMode::Return => 2.0, + } + } + + fn of(v: &Value) -> JsResult { + match v { + Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next), + Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw), + Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return), + _ => internal("a resumption mode that is not one"), + } + } +} + +/// The estimated bytes of a suspended generator's frame besides its operands. +const GENERATOR_BYTES: usize = 128; + +/// The estimated bytes of each operand and `finally` entry a suspended frame holds. +const SLOT_BYTES: usize = 16; + +/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its +/// base and its `finally` entries, their stack slots counted from its base. +#[derive(Clone)] +pub(crate) struct SavedFrame { + pub(crate) code: Rc, + pc: usize, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, + env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, + pub(crate) completion: Value, + pub(crate) stack: Vec, + /// [`Interp::finally_sites`] entries. + pub(crate) sites: Vec<(ThrowSite, usize)>, + /// [`Interp::finally_marks`] entries. + pub(crate) marks: Vec<(ObjId, u32, usize)>, +} + +/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended. +#[derive(Clone)] +pub(crate) enum GenState { + SuspendedStart(SavedFrame), + SuspendedYield(SavedFrame), + Executing, + Completed, +} + +impl GenState { + /// The suspended frame, if the generator is suspended. + pub(crate) fn saved(&self) -> Option<&SavedFrame> { + match self { + GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s), + GenState::Executing | GenState::Completed => None, + } + } +} + +/// The bytes a suspended frame adds to its generator object, which a collection counts. +pub(crate) fn saved_bytes(s: &SavedFrame) -> usize { + GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len()))) +} + +/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was +/// resumed with and how, unless it had not started. +pub(crate) struct Resumed { + generator: ObjId, + saved: SavedFrame, + received: Option<(Value, ResumeMode)>, +} + +impl Interp { + fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> { + match self.heap.object_mut(g).map(|o| &mut o.class) { + Some(Class::Generator(s)) => Some(s), + _ => None, + } + } + + /// Marks the generator `g`, whose frame was popped without being saved, completed. + pub(crate) fn end_generator(&mut self, g: Option) { + if let Some(state) = g.and_then(|g| self.generator_state_mut(g)) + && let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed) + { + self.release_saved(&saved); + } + } + + /// Takes a saved frame that left its generator object off the heap's total. + fn release_saved(&mut self, saved: &SavedFrame) { + self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved)); + } + + /// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below. + fn deliver(&mut self, boundary: bool, v: Value) -> JsResult> { + if boundary { + return Ok(Some(v)); + } + self.push(v)?; + Ok(None) + } + + /// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`]. + fn save_frame(&mut self, frame: Frame) -> SavedFrame { + let base = frame.base; + let stack = self.stack.split_off(base.min(self.stack.len())); + let i = self.finally_sites.partition_point(|&(_, slot)| slot < base); + let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(id, mark, slot)| { + let below = slot < base; + if !below { + marks.push((id, mark, slot - base)); + } + below + }); + SavedFrame { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + stack, + sites, + marks, + } + } + + /// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor + /// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an + /// object, holding the frame, which the call returns. + pub(crate) fn op_generator_start(&mut self) -> JsResult> { + let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") }; + // A realm made without `Options::es2015` that reads the syntax later has no generator + // built-ins. + let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else { + return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them")); + }; + let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? { + Value::Object(p) => p, + _ => fallback, + }; + self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + let bytes = saved_bytes(&saved); + let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + self.deliver(boundary, Value::Object(g)) + } + + /// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame, + /// already past the instruction, goes into the generator object, and its caller gets the + /// iterator result. + pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult> { + let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") }; + if !raw { + let v = self.peek(0)?; + let result = iter_result(self, v, false)?; + self.replace(1, result)?; + } + 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 { + // Whether it has started, or `None` when it is running or completed. + let (g, started) = match this { + Value::Object(g) => match self.heap.object(g).map(|o| &o.class) { + Some(Class::Generator(s)) => match **s { + GenState::SuspendedStart(_) => (g, Some(false)), + GenState::SuspendedYield(_) => (g, Some(true)), + GenState::Executing => return Err(self.type_error("the generator is already running")), + GenState::Completed => (g, None), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }; + let Some(started) = started else { + return match mode { + ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)), + ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)), + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + }; + }; + if !started && mode != ResumeMode::Next { + self.end_generator(Some(g)); + return match mode { + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + _ => Ok(Prepared::Done(iter_result(self, sent, true)?)), + }; + } + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") }; + let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else { + return internal("a suspended generator without its frame"); + }; + self.release_saved(&saved); + let received = started.then_some((sent, mode)); + Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received }))) + } + + /// Pushes a resumed generator's frame, with the value it was resumed with and how on top of + /// its operands when it had yielded. + pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> { + let Resumed { generator, saved, received } = r; + if self.frames.len() >= self.limits.frames { + let bytes = saved_bytes(&saved); + if let Some(state) = self.generator_state_mut(generator) { + *state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) }; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let base = self.stack.len(); + self.drop_left_finally_sites(base); + let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved; + self.stack.extend(stack); + if let Some((value, mode)) = received { + self.stack.push(value); + self.stack.push(Value::Number(mode.number())); + } + self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base))); + self.frames.push(Frame { + code, + pc, + base, + env, + var_env, + env_depth, + this, + callee, + construct: None, + completion, + boundary, + generator: Some(generator), + }); + Ok(()) + } + + /// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`. + pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let received = self.peek(1)?; + self.pop()?; + self.pop()?; + match mode { + ResumeMode::Next => self.push(received), + ResumeMode::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(received)) + } + ResumeMode::Return => { + self.push(received)?; + self.jump_to(target) + } + } + } + + /// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or + /// `null`. + fn get_method(&mut self, v: &Value, name: &str) -> JsResult> { + let f = self.get_value(v, &key(name))?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error(&format!("the iterator's {name} is not a function"))); + } + Ok(Some(f)) + } + + /// [`Op::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(()) + } +} diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs new file mode 100644 index 0000000000..fcdd00033e --- /dev/null +++ b/crates/js/src/generator_tests.rs @@ -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))); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index d40e75609b..d5e21359ba 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -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), + /// A generator object and its state (ECMA-262 11th edition, section 25.4). + Generator(Box), ForIn(Box), /// 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, strings: &mut StringSizes) -> u crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), }, + Class::Generator(state) => { + if let Some(saved) = state.saved() { + work.push(saved.env.0); + work.push(saved.var_env.0); + work.extend(saved.callee.iter().map(|o| o.0)); + work.extend(saved.marks.iter().map(|&(id, _, _)| id.0)); + mark_value(&saved.this, work, strings); + mark_value(&saved.completion, work, strings); + for v in &saved.stack { + mark_value(v, work, strings); + } + mark_code(&saved.code, strings); + for ((code, _), _) in &saved.sites { + mark_code(code, strings); + } + extra = crate::generator::saved_bytes(saved); + } + } Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b05953b36c..acf645bbde 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4,7 +4,9 @@ //! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call //! only where the language needs a function's result in the middle of an operation (a getter or //! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are -//! counted against [`crate::Limits::reentry`]. +//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own, +//! which `yield` moves into the generator object, operands included, and a call to its `next`, +//! `return` or `throw` pushes again ([`crate::generator`]). //! //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap @@ -49,7 +51,7 @@ pub(crate) type JsResult = Result; /// with a NUL, which no identifier holds. const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73]; -fn internal(message: &str) -> JsResult { +pub(crate) fn internal(message: &str) -> JsResult { Err(Abrupt::Internal(message.into())) } @@ -173,22 +175,24 @@ pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. - base: usize, + pub(crate) base: usize, pub(crate) env: EnvId, pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. - env_depth: u32, - this: Value, - callee: Option, + pub(crate) env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, /// The object `new` made, returned unless the function returns an object. - construct: Option, - completion: Value, + pub(crate) construct: Option, + pub(crate) completion: Value, /// Returning from this frame returns from the Rust call that pushed it. - boundary: bool, + pub(crate) boundary: bool, + /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. + pub(crate) generator: Option, } /// Where the exception being thrown was raised: the code and the instruction. -type ThrowSite = (Rc, usize); +pub(crate) type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -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, 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), } /// 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> { + // 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(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index d0bed32c1d..1f17b90055 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -983,6 +983,7 @@ fn code(ops: Vec) -> Code { arrow: false, uses_this: false, param_init: false, + generator: false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 7804a5858d..44b6d4e92f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -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, //! ): `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; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index db034d1e2d..b90d9e3a66 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -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, + /// Where each yield expression read so far starts, in the order read, so the parameters of a + /// generator function and an arrow function's head can be checked for one. + yields: Vec, } impl<'s> Parser<'s> { @@ -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 { @@ -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 { 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 { + /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + generator: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with the function's own `yield` rule, not the enclosing code's. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let yields = self.yields.len(); + let result = self.function_rest(kind, name, start, generator); + // The `yield` expressions of this function are not in the code around it. + self.yields.truncate(yields); + self.ctx.generator = outer_generator; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result { + let params_start = self.tok.span.start; self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -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 = 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 { 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 { + let start = self.bump()?.span; + self.yields.push(start.start); + let delegate = !self.tok.newline_before && self.at(Punct::Star); + if delegate { + self.bump()?; + } + let arg = + if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None }; + Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start))) + } + /// The arrow function whose head is `expr`, read before the current `=>`: a name standing /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); + if self.yield_between(start.start, start.end) { + return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); + } let params = match self.ast.expr(expr) { Some(Expr::Ident(name)) => (vec![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 { 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 { + 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 { self.expect(Punct::Colon)?; @@ -1614,6 +1700,42 @@ fn property_key(token: &Token) -> Option { } } +/// The token can start an expression, so a `yield` before it on the same line takes an operand. +fn starts_expression(token: &Token, e4x: bool) -> bool { + match &token.kind { + TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true, + TokenKind::Keyword(k) => matches!( + k, + Keyword::This + | Keyword::Null + | Keyword::True + | Keyword::False + | Keyword::Function + | Keyword::New + | Keyword::Delete + | Keyword::Void + | Keyword::Typeof + ), + TokenKind::Punct(p) => { + matches!( + p, + Punct::LParen + | Punct::LBracket + | Punct::LBrace + | Punct::Plus + | Punct::Minus + | Punct::Bang + | Punct::Tilde + | Punct::PlusPlus + | Punct::MinusMinus + | Punct::Slash + | Punct::SlashEq + ) || (e4x && matches!(p, Punct::Lt | Punct::At)) + } + _ => false, + } +} + fn is_eval_or_arguments(name: &str) -> bool { name == "eval" || name == "arguments" } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 5d5ce411d0..123fe3b202 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -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(); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index e89bbeb9f4..ba307b0763 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects { pub(crate) array_values: ObjId, /// `Function.prototype[@@hasInstance]`. pub(crate) has_instance: ObjId, + /// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from. + pub(crate) generator_proto: ObjId, + /// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function. + pub(crate) generator_function_proto: ObjId, } /// The estimated bytes of a registry entry without its Symbol. @@ -208,7 +212,17 @@ impl Symbols { /// The objects the collector starts from. pub(crate) fn root_objects(&self) -> Vec { - self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + self.objects.map_or_else(Vec::new, |o| { + vec![ + o.symbol_proto, + o.array_iterator_proto, + o.string_iterator_proto, + o.array_values, + o.has_instance, + o.generator_proto, + o.generator_function_proto, + ] + }) } /// The bytes the registry's entries hold besides their Symbols, which a collection adds. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 19f1e77910..7a13690d81 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -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. diff --git a/docs/mcp.md b/docs/mcp.md index 4e071c4ff0..bcaef4853a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6cb0a7eb9..0e6a8d37b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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 ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From d73d0c0f9b9c4924484cbc31fc787e22fa90f66e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:27:41 -0800 Subject: [PATCH 6/7] JavaScript: a yield reserves only the heap its saved frame takes A yield reserved room for every finally entry on the interpreter, those of the frames under the generator's included, and for the result it hands back, while the saved frame keeps only its own operands and entries. Under deep callers in finally blocks a yield could stop at the heap limit with enough room for its frame. It now reserves what the saved frame keeps. The tests check the value a throw raises in a generator that has not started, and the fuel each call of a completed generator's next takes against a native method that takes none. docs/mcp.md and docs/target-app-parity.md say that an engine a .js script makes has Symbol and the iterators, and that one a .jsx script or a source string makes does not. The parity entry no longer says that spread is missing or that scripts call next() themselves. --- crates/js/src/generator.rs | 8 +++-- crates/js/src/generator_tests.rs | 53 ++++++++++++++++++++++++++++---- docs/mcp.md | 8 +++-- docs/target-app-parity.md | 2 +- 4 files changed, 59 insertions(+), 12 deletions(-) diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs index 5169dcb2d0..c033a025d3 100644 --- a/crates/js/src/generator.rs +++ b/crates/js/src/generator.rs @@ -200,8 +200,12 @@ impl Interp { 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()); + // What `save_frame` keeps: the frame's operands without the result, popped below, and its + // own `finally` entries, not those of the frames under it. + let base = self.frame()?.base; + let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base)); + let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count(); + let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks); let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); self.reserve_heap(bytes)?; let result = self.pop()?; diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index fcdd00033e..3eea94da23 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -100,7 +100,9 @@ fn throw_goes_into_a_suspended_generator() { 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"); + truth( + "var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done", + ); throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); } @@ -275,6 +277,40 @@ fn an_unreachable_suspended_generator_is_freed() { assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); } +/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`. +fn smallest_heap_limit(setup: &str, script: &str) -> usize { + let fits = |limit: usize| { + let mut realm = es2015(Limits::default()); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + realm.run(script).is_ok() + }; + let (mut low, mut high) = (0, 64 << 20); + assert!(fits(high), "{script}"); + while high - low > 256 { + let mid = low + (high - low) / 2; + if fits(mid) { + high = mid; + } else { + low = mid; + } + } + high +} + +#[test] +fn a_yield_reserves_only_what_its_frame_keeps() { + // At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks + // that a throw entered. Their entries stay with those frames, so the yield needs no more room + // than the one in `before`, which comes before those frames are pushed. + let setup = "function* g() { yield 1; } var it = g(); 0"; + let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0"; + let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0"; + let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before)); + assert!(inside < before + 4096, "inside {inside}, before {before}"); +} + #[test] fn generators_stay_within_the_limits() { let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); @@ -282,12 +318,17 @@ fn generators_stay_within_the_limits() { 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:?}"), + // Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next` + // take at least 1,000 more than the same calls of a native method that takes none. + let mut realm = es2015(Limits::default()); + let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let mut used = Vec::new(); + for callee in ["control", "it"] { + assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0))); + used.push(Limits::default().fuel - realm.fuel_left()); } + assert!(used[1] >= used[0] + 1000, "{used:?}"); // A deep `yield*` chain stops at the frame limit, and the realm can run again. let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { diff --git a/docs/mcp.md b/docs/mcp.md index c720283975..0e674ee2e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2661,9 +2661,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. -A script does not have `Symbol` or the iterators of arrays, strings and `arguments` objects: `typeof Symbol` is -`"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. The JavaScript engine's ECMAScript -2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes. +An engine that a `.js` script makes runs in the JavaScript engine's ECMAScript 2015 mode (`Options::es2015` in +`vectorcraft-js`) and has `Symbol` and the iterators of arrays, strings and `arguments` objects, as +`docs/target-app-parity.md` describes. An engine that a `.jsx` script or a `source` string makes does not have them: +`typeof Symbol` is `"undefined"`, and `Array.prototype.values`, `keys` and `entries` are not defined. An engine that +`#targetengine` keeps holds the built-ins of the run that made it, whichever kind of script runs in it later. Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 177831817e..e72bb9817a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1083,7 +1083,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `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` 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. `script.run` makes the realm for a `.js` script with the option; a realm made without it, as for a `.jsx` script or a `source` string, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. `yield*` reads an iterator through `Symbol.iterator`; spread does not, and reads values by the rule the entry on ECMAScript 2015 forms gives. The language does not have `for`-`of` or destructuring yet. `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 ]` 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`. From 895fc362e82e909082d7356e2850086d5461563b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:58:58 -0800 Subject: [PATCH 7/7] JavaScript: a bound function inherits from its target's prototype With ECMAScript 2015, Function.prototype.bind gave every bound function Function.prototype as its prototype, so a bound generator function's constructor was Function instead of GeneratorFunction. The bound function now takes the target's prototype, read before length and name (ECMA-262 2020 section 9.4.1.3). Without the option it keeps Function.prototype, as ES5 section 15.3.4.5 specifies. --- crates/js/src/builtins.rs | 16 ++++++++++------ crates/js/src/generator_tests.rs | 7 +++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 1314a04a03..6757c79cb2 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -672,6 +672,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) }; let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); + // With ECMAScript 2015 the bound function inherits from the target's prototype, read before + // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function + // inherits from %GeneratorFunction.prototype%. + let target_proto = interp.heap.object(target).and_then(|o| o.proto); // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. @@ -685,7 +689,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; if interp.options.es2015 { - return bind_es2015(interp, target, bound_this, bound_args, length); + return bind_es2015(interp, target, target_proto, bound_this, bound_args, length); } interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; @@ -707,9 +711,10 @@ fn prop_bytes(names: &[&str]) -> usize { /// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section /// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the -/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps -/// the `caller` and `arguments` that throw, as without the option. -fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { +/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its +/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as +/// without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { Value::String(s) => s, _ => Str::from(""), @@ -725,9 +730,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args crate::string_builtins::charge_units(interp, name_len)?; let mut units: Vec = "bound ".encode_utf16().collect(); units.extend_from_slice(&target_units); - let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); - let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + let f = interp.heap.alloc_object(Object::new(class, proto)); interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index 9c3ba3c139..e90943dbdd 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -184,6 +184,13 @@ fn generator_methods_and_the_generator_objects() { truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); } +#[test] +fn a_bound_generator_function_inherits_from_the_targets_prototype() { + truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function"); + truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3"); + truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype"); +} + #[test] fn yield_is_an_identifier_outside_generators_in_sloppy_code() { truth("var yield = 1; yield + 1 === 2");