From 8d12b37da2401a55037f8e37379be2a0c6daf91b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:09:15 -0800 Subject: [PATCH] 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`.