mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 09:46:19 +01:00
Merge branch feat/js-es2015-symbol-iterators into feat/js-es2015-generators
This commit is contained in:
commit
f1f0911ddb
21 files changed
+1917
-112
No files matched your search
@@ -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<Value> {
|
||||
// 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<Value> {
|
||||
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<Value> {
|
||||
@@ -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<Value> {
|
||||
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 ----
|
||||
|
||||
@@ -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::<Vec<_>>()))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
//! The iterators of arrays, strings and `arguments` objects (ECMA-262 11th edition,
|
||||
//! <https://262.ecma-international.org/11.0/>): `%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<ObjId>, next: f64, kind: ArrayKind },
|
||||
/// [[IteratedString]], flat, and [[StringIteratorNextIndex]] in code units.
|
||||
String { text: Option<Str>, 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<Value> {
|
||||
Ok(this)
|
||||
}
|
||||
|
||||
/// CreateIterResultObject (section 7.4.7): `{ value, done }`.
|
||||
fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult<Value> {
|
||||
interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES))?;
|
||||
let proto = interp.intrinsics.object_proto;
|
||||
let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)));
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<f64> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -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),
|
||||
@@ -565,39 +565,19 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K
|
||||
|
||||
/// ToNumber of a Number object, or ToString of a String object (of either when `as_string` is
|
||||
/// set), as section 15.12.3 applies them in Str step 4, step 4.b.ii and step 5. Returns `None`
|
||||
/// for any other value. When the method that [[DefaultValue]] (section 8.12.8) calls first is not
|
||||
/// found on the object or on its prototype chain before the object's standard prototype, the
|
||||
/// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that
|
||||
/// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and
|
||||
/// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found.
|
||||
/// for any other value. The conversion is ToPrimitive (section 9.1) with the Number or String
|
||||
/// hint, so `valueOf` and `toString` are looked up along the object's whole prototype chain, and
|
||||
/// in a realm with [`crate::Options::es2015`] an `@@toPrimitive` method on the object is called
|
||||
/// first (ECMA-262 11th edition, section 7.1.1).
|
||||
fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult<Option<Value>> {
|
||||
let Value::Object(o) = v else { return Ok(None) };
|
||||
let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) {
|
||||
Some(Class::Number(n)) => (Value::Number(*n), interp.intrinsics.number_proto, as_string),
|
||||
Some(Class::String(s)) => (Value::String(s.clone()), interp.intrinsics.string_proto, true),
|
||||
let string = match interp.heap.object(*o).map(|x| &x.class) {
|
||||
Some(Class::Number(_)) => as_string,
|
||||
Some(Class::String(_)) => true,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") };
|
||||
let p = 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)?) }))
|
||||
}
|
||||
|
||||
/// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before
|
||||
/// any object on the way, `proto` included, has its own property `name`.
|
||||
fn reaches_prototype(interp: &mut Interp, o: ObjId, proto: ObjId, name: &str) -> JsResult<bool> {
|
||||
let k = key(name);
|
||||
let mut cur = Some(o);
|
||||
while let Some(id) = cur {
|
||||
interp.use_fuel()?;
|
||||
if interp.get_own_property(id, &k)?.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
if id == proto {
|
||||
return Ok(true);
|
||||
}
|
||||
cur = interp.heap.object(id).and_then(|x| x.proto);
|
||||
}
|
||||
Ok(false)
|
||||
let p = interp.to_primitive(v, if string { Hint::String } else { Hint::Number })?;
|
||||
Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) }))
|
||||
}
|
||||
|
||||
/// Quote (section 15.12.3): the string in double quotes with the characters JSON escapes.
|
||||
@@ -637,7 +617,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(()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Key>) -> JsResult<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<Vec<PropKey>> {
|
||||
let mut keys: Vec<PropKey> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Va
|
||||
/// `Object.defineProperty` (section 15.2.3.6).
|
||||
fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
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,20 @@ 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)? {
|
||||
let keys = own_prop_keys(interp, p)?;
|
||||
// A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted
|
||||
// until they are defined on `o`.
|
||||
for k in &keys {
|
||||
if let PropKey::Sym(s) = k {
|
||||
interp.temp_roots.push(Value::Symbol(s.clone()));
|
||||
}
|
||||
}
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
if !interp.get_own_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 +219,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 +231,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<Value> {
|
||||
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 +248,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult<Value> {
|
||||
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 +280,9 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) ->
|
||||
fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! `Symbol` (ECMA-262 11th edition, section 19.4, <https://262.ecma-international.org/11.0/>):
|
||||
//! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of
|
||||
//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10),
|
||||
//! `Function.prototype[@@hasInstance]` (section 19.2.3.6) and `Date.prototype[@@toPrimitive]`
|
||||
//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only.
|
||||
|
||||
use super::{arg, constructor, create_at, data, method, native, new_array};
|
||||
use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes};
|
||||
use crate::interp::{Hint, 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.clone(), "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?;
|
||||
let date_proto = interp.intrinsics.date_proto;
|
||||
sym_method(interp, date_proto, to_primitive, "[Symbol.toPrimitive]", date_to_primitive, 1, CONFIGURABLE)?;
|
||||
|
||||
method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?;
|
||||
let function_proto = interp.intrinsics.function_proto;
|
||||
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<ObjId> {
|
||||
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<Str>, registered: bool, extra: usize) -> JsResult<Sym> {
|
||||
let bytes = SYMBOL_BYTES.saturating_add(extra);
|
||||
let roots: Vec<Value> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Sym> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol)
|
||||
}
|
||||
|
||||
/// `Date.prototype[@@toPrimitive](hint)` (section 20.4.4.45): OrdinaryToPrimitive of any object,
|
||||
/// `toString` first for the hints `"string"` and `"default"` and `valueOf` first for `"number"`.
|
||||
/// Any other hint, or a `this` that is not an object, throws a `TypeError`.
|
||||
fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let Value::Object(o) = this else {
|
||||
return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was called on a value that is not an object"));
|
||||
};
|
||||
// The longest hint has 7 units, so a longer string is refused before it is flattened.
|
||||
let name = match arg(args, 0) {
|
||||
Value::String(s) if s.len() <= 7 => String::from_utf16_lossy(&s.flat()),
|
||||
_ => String::new(),
|
||||
};
|
||||
let hint = match name.as_str() {
|
||||
"string" | "default" => Hint::String,
|
||||
"number" => Hint::Number,
|
||||
_ => return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was given a hint that is not \"string\", \"number\" or \"default\"")),
|
||||
};
|
||||
interp.ordinary_to_primitive(o, &this, hint)
|
||||
}
|
||||
|
||||
/// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the
|
||||
/// order they were added.
|
||||
fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
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<Value> {
|
||||
interp.ordinary_has_instance(&arg(args, 0), &this).map(Value::Bool)
|
||||
}
|
||||
@@ -684,6 +684,10 @@ fn json_stringify_unwraps_number_string_and_boolean_objects() {
|
||||
assert_eq!(string("Object.prototype.valueOf = function () { return 9; }; JSON.stringify(Object(3))"), "3");
|
||||
assert_eq!(string("Object.getPrototypeOf(Object(1)).valueOf = function () { return 4; }; JSON.stringify(Object(3))"), "4");
|
||||
assert_eq!(string("Object.getPrototypeOf(Object('')).toString = function () { return 'q'; }; JSON.stringify(Object('abc'))"), "\"q\"");
|
||||
// Once the own prototype's method is deleted, the lookup goes on to Object.prototype.
|
||||
let over = "Object.prototype.toString = function () { return '7'; };";
|
||||
assert_eq!(string(&format!("{over} delete String.prototype.toString; JSON.stringify(Object('abc'))")), "\"7\"");
|
||||
assert_eq!(string(&format!("{over} delete Number.prototype.valueOf; delete Number.prototype.toString; JSON.stringify(Object(3))")), "7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option<u32> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the digit values `digits` in `radix` (8 or 16), rounded once to the nearest number
|
||||
/// The value of the digit values `digits` in `radix` (2, 8 or 16), rounded once to the nearest number
|
||||
/// with ties to even (sections 7.8.3 and 9.3.1), or `None` when there are no digits. Digits are
|
||||
/// kept exactly in a `u128` while they fit; past that, each later digit counts only for its
|
||||
/// position and for whether any of the dropped bits is set.
|
||||
|
||||
+40
-7
@@ -227,6 +227,10 @@ pub(crate) enum Class {
|
||||
RegExp(Rc<crate::regexp_vm::Regex>),
|
||||
/// 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<crate::builtins::iterator::IterState>),
|
||||
ForIn(Box<ForIn>),
|
||||
/// 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<ObjId>,
|
||||
pub(crate) extensible: bool,
|
||||
pub(crate) props: PropMap<Prop>,
|
||||
/// The properties whose keys are Symbols, once the object has one.
|
||||
pub(crate) syms: Option<Box<crate::symbol::SymProps>>,
|
||||
}
|
||||
|
||||
impl Object {
|
||||
pub(crate) fn new(class: Class, proto: Option<ObjId>) -> Self {
|
||||
Self { class, proto, extensible: true, props: PropMap::default() }
|
||||
Self { class, proto, extensible: true, props: PropMap::default(), syms: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,6 +421,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;
|
||||
|
||||
@@ -577,16 +585,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<u32>, 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<u32>, 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 {
|
||||
@@ -654,10 +680,12 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, 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 {
|
||||
@@ -684,6 +712,11 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, 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::<usize>();
|
||||
}
|
||||
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);
|
||||
@@ -710,7 +743,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, 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) {
|
||||
|
||||
+17
-1
@@ -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")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,6 +269,14 @@ impl Interp {
|
||||
return Err(self.data_error(r, ErrorType::Type, &what));
|
||||
}
|
||||
};
|
||||
// Each Symbol key the scan may visit takes a unit of fuel first.
|
||||
let syms = self.object(id)?.syms.as_ref().map_or(0, |m| m.len());
|
||||
if syms > 0 {
|
||||
crate::regexp_vm::use_fuel_n(self, syms as u64)?;
|
||||
}
|
||||
if self.object(id)?.syms.as_ref().is_some_and(|m| m.iter().any(|(_, p)| p.enumerable())) {
|
||||
return Err(self.data_error(r, ErrorType::Type, "has a Symbol-keyed property, not plain data"));
|
||||
}
|
||||
r.ancestors.push(id);
|
||||
let out = match shape {
|
||||
Shape::Array(length) => self.read_array(id, length, r),
|
||||
@@ -528,7 +537,14 @@ impl Interp {
|
||||
|
||||
/// `v` as the string `String(v)` gives, within the limits of a crossing.
|
||||
fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult<Data> {
|
||||
let s = self.to_str(v)?;
|
||||
let s = match v {
|
||||
// `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1).
|
||||
Value::Symbol(k) => match self.descriptive_string(k)? {
|
||||
Value::String(s) => s,
|
||||
_ => return Err(Abrupt::Internal("a Symbol's descriptive string is not a string".into())),
|
||||
},
|
||||
_ => self.to_str(v)?,
|
||||
};
|
||||
self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?;
|
||||
Ok(Data::String(s.to_rust_string()))
|
||||
}
|
||||
|
||||
@@ -325,6 +325,45 @@ fn a_text_function_takes_each_argument_as_string_gives_it() {
|
||||
assert!(e.message.contains("no text"), "{}", e.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_crosses_as_the_text_string_gives_it_and_never_as_data() {
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
let seen = with_take(&mut r);
|
||||
let texts: Rc<RefCell<Vec<Data>>> = Rc::default();
|
||||
let log = texts.clone();
|
||||
let f: HostFunction = Rc::new(move |args| {
|
||||
log.borrow_mut().extend(args);
|
||||
Ok(Data::Undefined)
|
||||
});
|
||||
r.define_host_object("text", vec![("of".into(), HostItem::TextFunction(f))]).unwrap();
|
||||
r.run("text.of(Symbol('tag'), Symbol())").unwrap();
|
||||
assert_eq!(texts.borrow().as_slice(), [Data::String("Symbol(tag)".into()), Data::String("Symbol()".into())]);
|
||||
// An enumerable Symbol-keyed property is refused; one that is not enumerable is left out.
|
||||
let probe = "var e = 'none'; var v = {a: 1}; v[Symbol('k')] = 2; try { host.take(v); } catch (x) { e = x.name + '|' + x.message; } e";
|
||||
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
|
||||
assert!(out.starts_with("TypeError|") && out.contains("has a Symbol-keyed property"), "{out}");
|
||||
let probe = "var e = 'none'; var v = [1]; v[Symbol('k')] = 2; try { host.take({list: v}); } catch (x) { e = x.name + '|' + x.message; } e";
|
||||
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
|
||||
assert!(out.starts_with("TypeError|") && out.contains(".list has a Symbol-keyed property"), "{out}");
|
||||
assert!(seen.borrow().is_empty(), "the function ran");
|
||||
r.run("var v = {a: 1}; Object.defineProperty(v, Symbol('k'), {value: 2}); host.take(v);").unwrap();
|
||||
assert_eq!(seen.borrow().as_slice(), [Data::Object(vec![("a".into(), Data::Number(1.0))])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checking_the_symbol_keys_of_a_value_takes_fuel() {
|
||||
// Making the 20,000 hidden keys takes well under 3,000,000 units; the 500 crossings check
|
||||
// 10,000,000 keys.
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 3_000_000, ..Limits::default() });
|
||||
with_take(&mut r);
|
||||
let src = "var v = {}; for (var i = 0; i < 20000; i++) Object.defineProperty(v, Symbol(), {value: i}); \
|
||||
for (var j = 0; j < 500; j++) host.take(v);";
|
||||
match r.run(src) {
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_from_the_host_can_be_caught_and_an_abort_cannot() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
+123
-43
@@ -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};
|
||||
|
||||
@@ -323,6 +324,9 @@ pub(crate) struct Interp {
|
||||
pub(crate) error_mark: Option<u32>,
|
||||
/// [`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
|
||||
@@ -557,6 +561,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;
|
||||
@@ -791,6 +796,8 @@ 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);
|
||||
roots.envs.push(self.global_lex);
|
||||
roots.envs.extend(self.temp_envs.iter().copied());
|
||||
@@ -801,7 +808,8 @@ impl Interp {
|
||||
// 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.
|
||||
@@ -965,13 +973,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)
|
||||
}
|
||||
|
||||
@@ -1469,12 +1477,13 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The prototype a primitive's properties are looked up on.
|
||||
fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult<ObjId> {
|
||||
pub(crate) fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult<ObjId> {
|
||||
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" };
|
||||
@@ -1573,7 +1582,7 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
|
||||
pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
|
||||
if throw {
|
||||
let key = String::from_utf16_lossy(k);
|
||||
return Err(self.type_error(&format!("cannot define property '{key}': {why}")));
|
||||
@@ -1727,7 +1736,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}")));
|
||||
@@ -1833,7 +1842,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);
|
||||
}
|
||||
@@ -1890,6 +1899,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" };
|
||||
@@ -1913,8 +1924,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<()> {
|
||||
@@ -1931,7 +1945,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(()) }
|
||||
}
|
||||
@@ -1944,8 +1958,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)
|
||||
}
|
||||
|
||||
@@ -1970,25 +1984,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<Value> {
|
||||
let v = self.get_value(base, &name)?;
|
||||
fn inc_property(&mut self, base: &Value, key: PropKey, prefix: bool, dec: bool) -> JsResult<Value> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -2003,7 +2017,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)
|
||||
}
|
||||
|
||||
@@ -2931,6 +2945,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)
|
||||
}
|
||||
|
||||
@@ -3321,21 +3336,36 @@ 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<Value> {
|
||||
let Value::Object(o) = v else { return Ok(v.clone()) };
|
||||
// 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(_)));
|
||||
if let Some(r) = self.exotic_to_primitive(*o, v, hint)? {
|
||||
return Ok(r);
|
||||
}
|
||||
self.ordinary_to_primitive(*o, v, hint)
|
||||
}
|
||||
|
||||
/// [[DefaultValue]] (section 8.12.8) of the object `o`, which is `v`: ToPrimitive without the
|
||||
/// `@@toPrimitive` method.
|
||||
pub(crate) fn ordinary_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult<Value> {
|
||||
// Without a hint, a Date object converts as with the String hint. In a realm with
|
||||
// `Options::es2015`, `Date.prototype[@@toPrimitive]` picks that order for a Date instead,
|
||||
// and OrdinaryToPrimitive treats a missing hint as the Number hint (ECMA-262 11th edition,
|
||||
// sections 7.1.1.1 and 20.4.4.45).
|
||||
let date = hint == Hint::Default && !self.options.es2015 && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_)));
|
||||
let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] };
|
||||
for name in order {
|
||||
let f = self.get_from(*o, &key(name), v)?;
|
||||
let f = self.get_from(o, &key(name), v)?;
|
||||
if self.is_callable(&f) {
|
||||
let r = self.call(&f, v, &[])?;
|
||||
if !matches!(r, Value::Object(_)) {
|
||||
@@ -3346,6 +3376,8 @@ impl Interp {
|
||||
Err(self.type_error("cannot convert the object to a primitive value"))
|
||||
}
|
||||
|
||||
/// ToNumber (section 9.3). In a realm with [`crate::Options::es2015`], a string may also be a
|
||||
/// `0b` or `0o` literal (ECMA-262 11th edition, section 7.1.3.1).
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
pub(crate) fn to_number(&mut self, v: &Value) -> JsResult<f64> {
|
||||
Ok(match v {
|
||||
@@ -3353,7 +3385,8 @@ impl Interp {
|
||||
Value::Null => 0.0,
|
||||
Value::Bool(b) => f64::from(u8::from(*b)),
|
||||
Value::Number(n) => *n,
|
||||
Value::String(s) => string_to_number(&flat_charged(self, s)?),
|
||||
Value::String(s) => string_to_number(&flat_charged(self, s)?, self.options.es2015),
|
||||
Value::Symbol(_) => return Err(self.type_error("cannot convert a Symbol value to a number")),
|
||||
Value::Object(_) => {
|
||||
let p = self.to_primitive(v, Hint::Number)?;
|
||||
return self.to_number(&p);
|
||||
@@ -3361,7 +3394,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"),
|
||||
@@ -3374,12 +3409,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<Str> {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -3430,6 +3475,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))))
|
||||
}
|
||||
@@ -3508,8 +3554,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3523,10 +3569,13 @@ impl Interp {
|
||||
return self.xml_concat(a, b);
|
||||
}
|
||||
let pa = self.to_primitive(a, Hint::Default)?;
|
||||
let pb = self.to_primitive(b, Hint::Default)?;
|
||||
// The right side's conversion can run script, so the left side's result stays counted.
|
||||
let pb = self.rooted(std::slice::from_ref(&pa), |i| i.to_primitive(b, Hint::Default))?;
|
||||
if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) {
|
||||
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)?))
|
||||
@@ -3535,12 +3584,14 @@ impl Interp {
|
||||
/// The abstract relational comparison `x < y` (section 11.8.5): `None` when either side is
|
||||
/// NaN.
|
||||
fn less_than(&mut self, x: &Value, y: &Value, left_first: bool) -> JsResult<Option<bool>> {
|
||||
// The second conversion can run script, so the first one's result stays counted.
|
||||
let (px, py) = if left_first {
|
||||
let px = self.to_primitive(x, Hint::Number)?;
|
||||
(px, self.to_primitive(y, Hint::Number)?)
|
||||
let py = self.rooted(std::slice::from_ref(&px), |i| i.to_primitive(y, Hint::Number))?;
|
||||
(px, py)
|
||||
} else {
|
||||
let py = self.to_primitive(y, Hint::Number)?;
|
||||
(self.to_primitive(x, Hint::Number)?, py)
|
||||
(self.rooted(std::slice::from_ref(&py), |i| i.to_primitive(x, Hint::Number))?, py)
|
||||
};
|
||||
if let (Value::String(a), Value::String(b)) = (&px, &py) {
|
||||
// Both stay rooted, so the first copy is still counted while the second is made.
|
||||
@@ -3571,29 +3622,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)?));
|
||||
return Ok(*n == string_to_number(&flat_charged(self, s)?, self.options.es2015));
|
||||
}
|
||||
(Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))),
|
||||
(_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))),
|
||||
(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<bool> {
|
||||
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<bool> {
|
||||
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) };
|
||||
@@ -3624,12 +3691,14 @@ 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)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A host value as a JavaScript value. A string is charged to the heap, and one that does not
|
||||
/// fit in it ends the run with the heap limit. Everything the caller still needs must be
|
||||
/// reachable from the roots.
|
||||
/// A host value as a JavaScript value. A string or a Symbol's description is charged to the
|
||||
/// heap before it is built, and one that does not fit in it ends the run with the heap limit.
|
||||
/// A Symbol in a realm without [`crate::Options::es2015`] throws a `TypeError`. Everything the
|
||||
/// caller still needs must be reachable from the roots.
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
pub(crate) fn from_js_value(&mut self, v: crate::JsValue) -> JsResult<Value> {
|
||||
Ok(match v {
|
||||
@@ -3644,6 +3713,16 @@ impl Interp {
|
||||
Value::str(&s)
|
||||
}
|
||||
crate::JsValue::Object(_) => Value::Object(self.new_object()),
|
||||
crate::JsValue::Symbol(_) if !self.options.es2015 => {
|
||||
return Err(self.type_error("a host function returned a Symbol in a realm without Symbol"));
|
||||
}
|
||||
crate::JsValue::Symbol(description) => {
|
||||
let bytes = crate::heap::SYMBOL_BYTES + description.as_ref().map_or(0, |d| string_bytes(d.encode_utf16().count()));
|
||||
self.reserve_heap(bytes)?;
|
||||
self.heap.bytes += bytes;
|
||||
let description = description.map(|d| Str::from_units(d.encode_utf16().collect()));
|
||||
Value::Symbol(crate::symbol::Sym::new(description, false))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3703,7 +3782,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<bool>, bit: u8| match field {
|
||||
Some(true) => bit,
|
||||
Some(false) => 0,
|
||||
@@ -3723,7 +3802,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<Prop> {
|
||||
pub(crate) fn merge_desc(current: &Prop, desc: &Desc) -> Option<Prop> {
|
||||
let flags = current.flags();
|
||||
let configurable = flags & CONFIGURABLE != 0;
|
||||
if !configurable {
|
||||
@@ -3779,6 +3858,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,
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,20 @@
|
||||
//! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays, strings (by code point) and objects
|
||||
//! with a `length`, by index; other values are a `TypeError`. Destructuring, `for … of`, classes,
|
||||
//! generators and modules stay syntax errors.
|
||||
//!
|
||||
//! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4,
|
||||
//! <https://262.ecma-international.org/11.0/>): `Symbol.for` and `Symbol.keyFor` over a registry
|
||||
//! 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.
|
||||
//! `Date.prototype[@@toPrimitive]` converts a Date without a hint as with the String hint, and an
|
||||
//! object without an `@@toPrimitive` method, a Date included, converts without a hint as with the
|
||||
//! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a
|
||||
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
|
||||
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
|
||||
//! entry counts against the heap limit.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
@@ -78,6 +92,7 @@ mod regexp;
|
||||
mod regexp_builtins;
|
||||
mod regexp_vm;
|
||||
mod string_builtins;
|
||||
mod symbol;
|
||||
mod token;
|
||||
mod value;
|
||||
mod xml;
|
||||
@@ -114,6 +129,10 @@ pub struct Options {
|
||||
/// template literals (tagged ones included), default and rest parameters, and spread in array
|
||||
/// literals, calls and `new`. Off, they are syntax errors and the language is ES5.1's. Code a
|
||||
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
|
||||
/// On, a realm also has the later editions' built-ins this engine has: `Symbol` with
|
||||
/// Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects, with
|
||||
/// `0b` and `0o` strings converting to numbers. Off, a realm has the ES5.1 built-ins only, as
|
||||
/// the app's scripts expect.
|
||||
pub es2015: bool,
|
||||
}
|
||||
|
||||
@@ -226,6 +245,8 @@ mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
#[cfg(test)]
|
||||
mod symbol_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod text_tests;
|
||||
|
||||
@@ -109,7 +109,9 @@ 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, and one a
|
||||
/// host function returns in a realm without [`Options::es2015`] throws a `TypeError`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum JsValue {
|
||||
Undefined,
|
||||
@@ -118,6 +120,7 @@ pub enum JsValue {
|
||||
Number(f64),
|
||||
String(String),
|
||||
Object(String),
|
||||
Symbol(Option<String>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -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<Value> {
|
||||
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(""),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
//! Symbols (ECMA-262 11th edition, section 6.1.5, <https://262.ecma-international.org/11.0/>) 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<SymData>);
|
||||
|
||||
struct SymData {
|
||||
description: Option<Str>,
|
||||
/// `Symbol.for` made it, and the registry holds it under its description.
|
||||
registered: bool,
|
||||
}
|
||||
|
||||
impl Sym {
|
||||
pub(crate) fn new(description: Option<Str>, 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<u16>, u64) {
|
||||
let mut units: Vec<u16> = "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<H: Hasher>(&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<Option<(Sym, Prop)>>,
|
||||
index: HashMap<Sym, usize>,
|
||||
}
|
||||
|
||||
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<Prop> {
|
||||
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.entries.shrink_to_fit();
|
||||
self.index = self.entries.iter().enumerate().filter_map(|(i, e)| e.as_ref().map(|(k, _)| (k.clone(), i))).collect();
|
||||
}
|
||||
Some(prop)
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.index.len()
|
||||
}
|
||||
|
||||
pub(crate) fn iter(&self) -> impl Iterator<Item = (&Sym, &Prop)> {
|
||||
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<Value>,
|
||||
}
|
||||
|
||||
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<WellKnown>,
|
||||
/// Each key `Symbol.for` was given, with its Symbol as a value.
|
||||
pub(crate) registry: HashMap<Rc<[u16]>, Value>,
|
||||
pub(crate) objects: Option<Es2015Objects>,
|
||||
}
|
||||
|
||||
impl Symbols {
|
||||
/// The values the collector starts from.
|
||||
pub(crate) fn root_values(&self) -> impl Iterator<Item = &Value> {
|
||||
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<ObjId> {
|
||||
self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance])
|
||||
}
|
||||
|
||||
/// 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<PropKey> {
|
||||
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<T>(&mut self, v: &Value, f: impl FnOnce(&mut Self, PropKey) -> JsResult<T>) -> JsResult<T> {
|
||||
match v {
|
||||
Value::Symbol(s) => f(self, PropKey::Sym(s.clone())),
|
||||
Value::Object(_) => {
|
||||
let p = self.to_primitive(v, Hint::String)?;
|
||||
self.rooted(std::slice::from_ref(&p), |i| match &p {
|
||||
Value::Symbol(s) => f(i, PropKey::Sym(s.clone())),
|
||||
_ => i.with_key(&p, |i, k| f(i, PropKey::Str(k))),
|
||||
})
|
||||
}
|
||||
_ => self.with_key(v, |i, k| f(i, PropKey::Str(k))),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Sym::message_name`] as code units, its reading charged as fuel.
|
||||
pub(crate) fn sym_name_units(&mut self, k: &Sym) -> JsResult<Vec<u16>> {
|
||||
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<String> {
|
||||
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<Value> {
|
||||
let body = match body {
|
||||
Some(b) => crate::string_builtins::flat_charged(self, b)?,
|
||||
None => Rc::from([]),
|
||||
};
|
||||
let (prefix, suffix): (Vec<u16>, Vec<u16>) = (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<Value> {
|
||||
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<bool> {
|
||||
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<Option<Prop>> {
|
||||
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. Each step to a prototype takes
|
||||
/// a unit of fuel.
|
||||
pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
|
||||
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;
|
||||
if cur.is_some() {
|
||||
self.use_fuel()?;
|
||||
}
|
||||
steps += 1;
|
||||
if steps > 1_000_000 {
|
||||
return Err(crate::interp::Abrupt::Internal("prototype chain too long".into()));
|
||||
}
|
||||
}
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<bool> {
|
||||
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<bool> {
|
||||
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<Vec<Sym>> {
|
||||
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<Option<Prop>> {
|
||||
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(&mut self, id: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
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<bool> {
|
||||
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<Value> {
|
||||
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<bool> {
|
||||
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<Sym> {
|
||||
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<Option<Value>> {
|
||||
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<Option<bool>> {
|
||||
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<Option<bool>> {
|
||||
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<Option<ObjId>> {
|
||||
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<Option<Str>> {
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Sym, SymProps};
|
||||
use crate::heap::{OPEN, Prop};
|
||||
use crate::value::Value;
|
||||
|
||||
#[test]
|
||||
fn removing_most_symbol_keys_gives_back_their_room_and_keeps_the_order() {
|
||||
let mut m = SymProps::default();
|
||||
let keys: Vec<Sym> = (0..100).map(|_| Sym::new(None, false)).collect();
|
||||
for k in &keys {
|
||||
m.insert(k.clone(), Prop::Data { value: Value::Undefined, flags: OPEN });
|
||||
}
|
||||
for k in &keys[..90] {
|
||||
m.remove(k);
|
||||
}
|
||||
assert!(m.entries.capacity() < 64, "{}", m.entries.capacity());
|
||||
assert_eq!(m.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(), keys[90..]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
//! `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 binary_and_octal_strings_are_numbers_in_an_es2015_realm_only() {
|
||||
for length in ["0b10", "0o2", "2"] {
|
||||
let src = format!(
|
||||
"var it = Array.prototype.values.call({{0: 'first', 1: 'second', length: '{length}'}}); \
|
||||
var a = it.next(), b = it.next(); a.value + ' ' + b.value + ' ' + it.next().done"
|
||||
);
|
||||
assert_eq!(string(&src), "first second true", "{length}");
|
||||
}
|
||||
truth("Number('0b101') === 5 && +'0O17' === 15 && '0b11' == 3 && isNaN('0b2') && isNaN('-0o1')");
|
||||
let src = "isNaN(Number('0b10')) && isNaN(+'0o2') && '0b1' != 1";
|
||||
assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(src), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_calls_the_to_primitive_method_of_a_wrapper() {
|
||||
let hook = "w[Symbol.toPrimitive] = function (hint) { return hint === 'number' ? 2 : 'b'; };";
|
||||
truth(&format!("var w = new String('x'); {hook} JSON.stringify(w) === '\"b\"'"));
|
||||
truth(&format!("var w = new String('x'); delete String.prototype.toString; {hook} JSON.stringify(w) === '\"b\"'"));
|
||||
truth(&format!("var w = new String('x'); {hook} JSON.stringify({{a: 1, b: 2}}, [w]) === '{{\"b\":2}}'"));
|
||||
truth(&format!("var w = new Number(5); {hook} JSON.stringify([w], null, w) === '[\\n 2\\n]'"));
|
||||
truth("JSON.stringify([new String('x'), new Number(1)], null, new Number(1)) === '[\\n \"x\",\\n 1\\n]'");
|
||||
// A `@@toPrimitive` getter that deletes the prototype's method and gives `undefined` sends the
|
||||
// lookup on to `Object.prototype`.
|
||||
let getter = |method: &str| {
|
||||
format!(
|
||||
"Object.defineProperty(w, Symbol.toPrimitive, {{ get: function () {{ delete Object.getPrototypeOf(w).{method}; return undefined; }} }});"
|
||||
)
|
||||
};
|
||||
let over = "Object.prototype.toString = function () { return '7'; };";
|
||||
truth(&format!("var w = new String('x'); {over} {} JSON.stringify(w) === '\"7\"'", getter("toString")));
|
||||
truth(&format!("var w = new Number(3); {over} delete Number.prototype.toString; {} JSON.stringify(w) === '7'", getter("valueOf")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_used() {
|
||||
// `mk(n)` makes a string of `n` units. The key's accessor deletes itself from
|
||||
// `Object.prototype`, so when the key is a Symbol only the read or write holds it and its
|
||||
// description of 2,000,000 units, and then makes a string of 1,500,000 units. With `keep`
|
||||
// (1,000,000 units) and a description still counted, that string does not fit; without one it
|
||||
// does.
|
||||
let src = |key: &str, access: &str| {
|
||||
format!(
|
||||
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
|
||||
var keep = mk(1000000), made = null; \
|
||||
function use() {{ var p = Object.prototype; delete p[Object.getOwnPropertySymbols(p)[0] || 'k']; \
|
||||
made = mk(1500000); return 0; }} \
|
||||
var w = {{}}; w[Symbol.toPrimitive] = function () {{ var k = {key}; \
|
||||
Object.defineProperty(Object.prototype, k, {{ configurable: true, get: use, set: use }}); return k; }}; \
|
||||
{access}; made.length"
|
||||
)
|
||||
};
|
||||
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
|
||||
for access in ["({})[w]", "({})[w] = 1", "({})[w]++"] {
|
||||
// A name as the key leaves the Symbol and its description to the collector, and the string
|
||||
// fits.
|
||||
assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 'k')", access)), Ok(JsValue::Number(1_500_000.0)), "{access}");
|
||||
match es2015(limits()).run(&src("Symbol(mk(2000000))", access)) {
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
|
||||
other => panic!("{access}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn define_properties_keeps_a_symbol_key_counted_after_a_getter_deletes_it() {
|
||||
// The second Symbol-keyed descriptor's getter deletes the first property, drops `s` and makes
|
||||
// a string of 1,500,000 units. With `keep` (1,000,000 units) and the first Symbol's
|
||||
// description of 2,000,000 units still counted, that string does not fit; with a short
|
||||
// description it does.
|
||||
let src = |description: &str, define: &str| {
|
||||
format!(
|
||||
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
|
||||
var keep = mk(1000000), made = null, s = Symbol({description}), props = {{}}; \
|
||||
props[s] = {{ value: 1, enumerable: true }}; \
|
||||
Object.defineProperty(props, Symbol('t'), {{ enumerable: true, get: function () {{ \
|
||||
delete props[s]; s = null; made = mk(1500000); return {{ value: 2 }}; }} }}); \
|
||||
var o = {define}; o[Object.getOwnPropertySymbols(o)[0]] + ' ' + made.length"
|
||||
)
|
||||
};
|
||||
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
|
||||
for define in ["Object.defineProperties({}, props)", "Object.create(null, props)"] {
|
||||
assert_eq!(es2015(limits()).run(&src("'d'", define)), Ok(JsValue::String("1 1500000".into())), "{define}");
|
||||
match es2015(limits()).run(&src("mk(2000000)", define)) {
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
|
||||
other => panic!("{define}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_operator_keeps_the_first_operand_converted_while_it_converts_the_second() {
|
||||
// `a` converts to a Symbol with a description of 2,000,000 units that nothing else holds, and
|
||||
// `b`'s conversion makes a string of 1,500,000 units. With `keep` (1,000,000 units) and the
|
||||
// description still counted, that string does not fit; when `a` gives a number it does.
|
||||
let src = |first: &str, op: &str| {
|
||||
format!(
|
||||
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
|
||||
var keep = mk(1000000), made = null; \
|
||||
var a = {{}}; a[Symbol.toPrimitive] = function () {{ return {first}; }}; \
|
||||
var b = {{}}; b[Symbol.toPrimitive] = function () {{ made = mk(1500000); return 1; }}; \
|
||||
try {{ a {op} b; }} catch (e) {{ if (!(e instanceof TypeError)) throw e; }} \
|
||||
made.length === 1500000"
|
||||
)
|
||||
};
|
||||
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
|
||||
for op in ["+", "<", ">", "<=", ">="] {
|
||||
assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 0)", op)), Ok(JsValue::Bool(true)), "{op}");
|
||||
match es2015(limits()).run(&src("Symbol(mk(2000000))", op)) {
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
|
||||
other => panic!("{op}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_objects_convert_through_their_to_primitive_method() {
|
||||
let date = "var d = new Date(0); d.valueOf = function () { return 7; }; d.toString = function () { return 'date'; };";
|
||||
truth(&format!("{date} d + 1 === 'date1' && d * 1 === 7 && String(d) === 'date' && (d == 'date')"));
|
||||
// Without a method, a Date converts with `valueOf` first when no hint is given.
|
||||
// The inherited method is read-only, so an assignment does not shadow it.
|
||||
truth(&format!("{date} d[Symbol.toPrimitive] = null; d + 1 === 'date1'"));
|
||||
truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: null }}); d + 1 === 8"));
|
||||
truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: undefined }}); d + 1 === 8 && String(d) === 'date'"));
|
||||
truth(&format!("{date} delete Date.prototype[Symbol.toPrimitive]; d + 1 === 8 && d == 7"));
|
||||
// The method itself, on any object.
|
||||
truth(
|
||||
"var m = Date.prototype[Symbol.toPrimitive], p = Object.getOwnPropertyDescriptor(Date.prototype, Symbol.toPrimitive); \
|
||||
typeof m === 'function' && m.length === 1 && !p.writable && !p.enumerable && p.configurable",
|
||||
);
|
||||
let o = "var o = { valueOf: function () { return 7; }, toString: function () { return 's'; } }, m = Date.prototype[Symbol.toPrimitive];";
|
||||
truth(&format!("{o} m.call(o, 'number') === 7 && m.call(o, 'string') === 's' && m.call(o, 'default') === 's'"));
|
||||
for call in ["m.call(o)", "m.call(o, 'other')", "m.call(o, new String('number'))", "m.call(1, 'number')", "m.call(o, 'defaultx')"] {
|
||||
throws(&format!("{o} {call}"), "TypeError");
|
||||
}
|
||||
// A realm without the option keeps the String-hint order for a Date.
|
||||
let src = format!("{date} d + 1 === 'date1' && d * 1 === 7");
|
||||
assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(&src), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_function_returns_a_symbol_only_in_an_es2015_realm() {
|
||||
let symbol = |_: &[JsValue]| -> Result<JsValue, String> { Ok(JsValue::Symbol(Some("from host".into()))) };
|
||||
let mut realm = es2015(Limits::default());
|
||||
realm.define_function("make", symbol);
|
||||
assert_eq!(realm.run("var s = make(); typeof s === 'symbol' && String(s) === 'Symbol(from host)' && s !== make()"), Ok(JsValue::Bool(true)));
|
||||
let mut realm = Realm::with_options(Options::default(), Limits::default());
|
||||
realm.define_function("make", symbol);
|
||||
let src = "try { make(); 'none'; } catch (e) { (e instanceof TypeError) + ' ' + typeof Symbol; }";
|
||||
assert_eq!(realm.run(src), Ok(JsValue::String("true undefined".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_symbol_description_counts_against_the_heap_before_it_is_made() {
|
||||
let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() });
|
||||
realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1 << 20)))));
|
||||
match realm.run("make()") {
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() });
|
||||
realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1_000)))));
|
||||
assert_eq!(realm.run("make().description.length"), Ok(JsValue::Number(1_000.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_lookup_takes_fuel_for_each_prototype() {
|
||||
// Building the chain takes about 20,000 units; each lookup of an absent Symbol walks all 2,000
|
||||
// prototypes, so the 100 lookups take 200,000 more.
|
||||
let src = "var s = Symbol(), o = {}; for (var i = 0; i < 2000; i++) o = Object.create(o); \
|
||||
for (var j = 0; j < 100; j++) s in o;";
|
||||
match es2015(Limits { fuel: 150_000, ..Limits::default() }).run(src) {
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let src = "var s = Symbol(), root = {}, o = root; root[s] = 'found'; for (var i = 0; i < 50; i++) o = Object.create(o); \
|
||||
o[s] === 'found' && s in o && !o.hasOwnProperty(s)";
|
||||
truth(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterator_steps_take_fuel() {
|
||||
let mut realm = es2015(Limits { fuel: 5_000, ..Limits::default() });
|
||||
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:?}"),
|
||||
}
|
||||
}
|
||||
+58
-8
@@ -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<u16>, 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())
|
||||
}
|
||||
@@ -236,9 +263,10 @@ pub(crate) fn is_str_space(u: u16) -> bool {
|
||||
crate::chars::is_whitespace(u32::from(u)) || crate::chars::is_line_terminator(u32::from(u))
|
||||
}
|
||||
|
||||
/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, NaN for
|
||||
/// anything else.
|
||||
pub(crate) fn string_to_number(units: &[u16]) -> f64 {
|
||||
/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, with the `0b`
|
||||
/// and `0o` literals of ECMA-262 11th edition, section 7.1.3.1, as well when `binary_octal` is
|
||||
/// set; NaN for anything else.
|
||||
pub(crate) fn string_to_number(units: &[u16], binary_octal: bool) -> f64 {
|
||||
let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len());
|
||||
let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |i| i + 1);
|
||||
let Some(text) = units.get(start..end) else { return f64::NAN };
|
||||
@@ -252,6 +280,15 @@ pub(crate) fn string_to_number(units: &[u16]) -> f64 {
|
||||
}
|
||||
return crate::chars::radix_value(hex.bytes().filter_map(|b| crate::chars::hex_value(u32::from(b))), 16).unwrap_or(f64::NAN);
|
||||
}
|
||||
if binary_octal {
|
||||
for (prefix, radix) in [("0b", 2), ("0B", 2), ("0o", 8), ("0O", 8)] {
|
||||
let Some(digits) = s.strip_prefix(prefix) else { continue };
|
||||
if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
|
||||
return f64::NAN;
|
||||
}
|
||||
return crate::chars::radix_value(digits.chars().filter_map(|c| c.to_digit(radix)), radix).unwrap_or(f64::NAN);
|
||||
}
|
||||
}
|
||||
let (sign, body) = match s.as_bytes().first() {
|
||||
Some(b'+') => (1.0, &s[1..]),
|
||||
Some(b'-') => (-1.0, &s[1..]),
|
||||
@@ -359,19 +396,32 @@ mod tests {
|
||||
("-Infinity", f64::NEG_INFINITY),
|
||||
];
|
||||
for (s, want) in cases {
|
||||
assert_eq!(string_to_number(&u(s)), *want, "{s:?}");
|
||||
assert_eq!(string_to_number(&u(s), false), *want, "{s:?}");
|
||||
}
|
||||
for s in ["inf", "nan", "1_0", "0x", "1e", ".", "--1", "0x-1", "infinity", "1 2"] {
|
||||
assert!(string_to_number(&u(s)).is_nan(), "{s:?}");
|
||||
assert!(string_to_number(&u(s), false).is_nan(), "{s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_and_octal_strings_convert_only_when_asked() {
|
||||
for (s, want) in [("0b10", 2.0), ("0B11", 3.0), (" 0o17 ", 15.0), ("0O7", 7.0), ("0x10", 16.0), ("2", 2.0)] {
|
||||
assert_eq!(string_to_number(&u(s), true), want, "{s:?}");
|
||||
}
|
||||
for s in ["0b", "0b2", "0o8", "-0b1", "+0o1", "0b1.0", "0o"] {
|
||||
assert!(string_to_number(&u(s), true).is_nan(), "{s:?}");
|
||||
}
|
||||
for s in ["0b10", "0o2"] {
|
||||
assert!(string_to_number(&u(s), false).is_nan(), "{s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_strings_round_once_to_the_nearest_number() {
|
||||
assert_eq!(string_to_number(&u("0xc83ce80553ee648")), 0xc83_ce80_553e_e648_u64 as f64);
|
||||
assert_eq!(string_to_number(&u("0xc83ce80553ee648"), false), 0xc83_ce80_553e_e648_u64 as f64);
|
||||
// 2^136 + 2^83 + 1: a set bit past 128 bits rounds the half-way case up.
|
||||
let digits = format!("0x1{}8{}1", "0".repeat(13), "0".repeat(19));
|
||||
assert_eq!(string_to_number(&u(&digits)), 2f64.powi(136) + 2f64.powi(84));
|
||||
assert_eq!(string_to_number(&u(&digits), false), 2f64.powi(136) + 2f64.powi(84));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -39,6 +39,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.
|
||||
@@ -844,6 +849,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(&script, negative_type.as_deref(), options)) {
|
||||
Ok(Ok(())) => counts.passed += 1,
|
||||
Ok(Err(why)) => {
|
||||
counts.failed += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): {why}\n"));
|
||||
}
|
||||
Err(_) => {
|
||||
counts.failed += 1;
|
||||
counts.panicked += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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();
|
||||
|
||||
@@ -2652,6 +2652,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`
|
||||
|
||||
@@ -1083,6 +1083,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
|
||||
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`.
|
||||
- With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`.
|
||||
- `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `<!DOCTYPE>` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`.
|
||||
|
||||
Reference in new issue
Block a user