Scripts: class and object literal methods are named, computed methods keep their home object

The merge of main left object literal methods without a `name`, since
main named them with SetFunctionName and the branch defines them through
InitMethod. Methods and accessors defined with a home object are now
named as they are defined: after their key, with `get ` or `set ` before
an accessor's name and a Symbol's description in brackets.

- A named class's constructor takes the class's name before its methods
  are defined, so a static `name` member replaces it. An anonymous class
  takes the name it is assigned to unless a static member defines `name`.
- Computed methods and accessors in object literals have the object as
  their home object (new InitMethodKey), so `super` works in them.
- Class method keys and `super[key]` keep Symbol keys instead of
  converting them to strings.
- Classes have generator methods (`*m() {}`); a generator constructor is
  a syntax error.
- docs/target-app-parity.md and docs/mcp.md describe the new behavior;
  the class line drops test262 counts measured before main added
  destructuring, generators and function names.
This commit is contained in:
dotCooCoo committed 2026-11-27 23:02:32 -08:00
1 parent 09c58a297d
commit 2b2ff867a5
8 files changed
+212 -36

No files matched your search

+10 -1
View File
@@ -251,6 +251,12 @@ pub(crate) enum Op {
kind: u8,
name: u32,
},
/// `object key` → `object`: [`Op::InitMethod`] under a computed key, already a name or a
/// Symbol.
InitMethodKey {
func: u32,
kind: u8,
},
/// `this key` → `this home key`: the key as a property name, with the prototype of the
/// running method's home object between, for a `super` property (section 12.3.5.3).
SuperRef,
@@ -575,6 +581,7 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::ClassStart { heritage, .. } => e(u32::from(heritage), 2),
Op::ClassMethod { .. } => e(3, 2),
Op::InitMethod { .. } => e(1, 1),
Op::InitMethodKey { .. } => e(2, 1),
Op::SuperRef => e(2, 3),
Op::SuperGet => e(3, 1),
Op::SuperGetThis => e(3, 2),
@@ -629,7 +636,9 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> {
| Op::InitVar(i)
| Op::LoadParam(i)
| Op::AnnexB(i) => check(i, code.names.len(), "name"),
Op::Closure(i) | Op::ClassStart { ctor: i, .. } | Op::ClassMethod { func: i, .. } => check(i, code.functions.len(), "function"),
Op::Closure(i) | Op::ClassStart { ctor: i, .. } | Op::ClassMethod { func: i, .. } | Op::InitMethodKey { func: i, .. } => {
check(i, code.functions.len(), "function")
}
Op::InitMethod { func, name, .. } => {
check(func, code.functions.len(), "function")?;
check(name, code.names.len(), "name")
+101 -26
View File
@@ -13,12 +13,13 @@
use std::rc::Rc;
use crate::bytecode::Code;
use crate::bytecode::{Code, NamePrefix};
use crate::heap::{
Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, Func, HIDDEN, Key, OBJECT_BYTES, ObjId, Object, Prop, PropMap, WRITABLE, key,
Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, Func, HIDDEN, OBJECT_BYTES, ObjId, Object, Prop, PropMap, WRITABLE, key,
string_bytes,
};
use crate::interp::{ARROW_THIS, Abrupt, Desc, Entry, ErrorType, Interp, JsResult, binding_bytes, closure_bytes, internal};
use crate::symbol::PropKey;
use crate::value::{Str, Value};
const FUNC: &[u16] = &[0, 0x66, 0x75, 0x6E, 0x63];
@@ -329,7 +330,7 @@ impl Interp {
/// 14.3.8 and 14.5.14, step 21).
pub(crate) fn op_class_method(&mut self, func: u32, kind: u8, is_static: bool) -> JsResult<()> {
let kv = self.peek(0)?;
let k: Key = self.to_key(&kv)?;
let k = self.to_prop_key(&kv)?;
let Value::Object(target) = self.peek(if is_static { 2 } else { 1 })? else { return internal("class operand is not an object") };
self.define_method(target, k, func, kind, false)?;
self.pop().map(drop)
@@ -340,64 +341,138 @@ impl Interp {
pub(crate) fn op_init_method(&mut self, func: u32, kind: u8, name: u32) -> JsResult<()> {
let k = self.name(name)?;
let Value::Object(target) = self.peek(0)? else { return internal("object literal is not an object") };
self.define_method(target, k, func, kind, true)
self.define_method(target, PropKey::Str(k), func, kind, true)
}
/// `object key` → `object`: defines an object literal's method or accessor `functions[func]`
/// under a computed key, already a name or a Symbol (section 12.2.6.8).
pub(crate) fn op_init_method_key(&mut self, func: u32, kind: u8) -> JsResult<()> {
let kv = self.peek(0)?;
let k = self.to_prop_key(&kv)?;
let Value::Object(target) = self.peek(1)? else { return internal("object literal is not an object") };
self.define_method(target, k, func, kind, true)?;
self.pop().map(drop)
}
/// Defines the method (`kind` 0), getter (1) or setter (2) made from `functions[func]` of the
/// running code under `k` on `target`, its home object (MakeMethod, section 14.3.8). The
/// caller keeps `target` reachable.
fn define_method(&mut self, target: ObjId, k: Key, func: u32, kind: u8, enumerable: bool) -> JsResult<()> {
/// running code under `k` on `target`, its home object (MakeMethod, section 14.3.8), and
/// names the function after `k`, with `get ` or `set ` before an accessor's name (section
/// 9.2.11). The caller keeps `target` and a Symbol key reachable.
fn define_method(&mut self, target: ObjId, k: PropKey, func: u32, kind: u8, enumerable: bool) -> JsResult<()> {
self.use_fuel()?;
let frame = self.frame()?;
let env = frame.env;
let Some(code) = frame.code.functions.get(func as usize).cloned() else { return internal("function out of range") };
let named = code.own_name.is_some();
let key_bytes = match &k {
PropKey::Str(name) => binding_bytes(name.len()),
PropKey::Sym(_) => binding_bytes(0),
};
let need = OBJECT_BYTES
.saturating_add(ENV_BYTES)
.saturating_add(binding_bytes(HOME.len()))
.saturating_add(closure_bytes(&code))
.saturating_add(binding_bytes(k.len()));
let root = Value::String(Str::from_rc(k.clone()));
self.rooted(&[root], |i| i.reserve_heap(need))?;
.saturating_add(key_bytes);
let root = match &k {
PropKey::Str(name) => Value::String(Str::from_rc(name.clone())),
PropKey::Sym(s) => Value::Symbol(s.clone()),
};
self.rooted(std::slice::from_ref(&root), |i| i.reserve_heap(need))?;
let home = self.home_env(target, env);
let f = self.make_closure(code, home)?;
if named {
let prefix = match kind {
0 => NamePrefix::None,
1 => NamePrefix::Get,
_ => NamePrefix::Set,
};
self.rooted(&[Value::Object(f), root], |i| {
let name = i.key_name(prefix, &k)?;
i.set_function_name(f, name)
})?;
}
let (enumerable, configurable) = (Some(enumerable), Some(true));
let desc = match kind {
0 => Desc { value: Some(Value::Object(f)), writable: Some(true), enumerable, configurable, ..Desc::default() },
1 => Desc { get: Some(Some(f)), enumerable, configurable, ..Desc::default() },
_ => Desc { set: Some(Some(f)), enumerable, configurable, ..Desc::default() },
};
self.rooted(&[Value::Object(f)], |i| i.define_own_property(target, k, &desc, true)).map(drop)
self.rooted(&[Value::Object(f)], |i| i.define_own_pk(target, k, &desc, true)).map(drop)
}
/// The `name` of a function defined under `k`: the name with `prefix` before it, or a
/// Symbol's description in brackets, or `prefix` alone for a Symbol without one (SetFunctionName,
/// section 9.2.11).
fn key_name(&mut self, prefix: NamePrefix, k: &PropKey) -> JsResult<Value> {
match k {
PropKey::Str(name) if prefix == NamePrefix::None => Ok(Value::String(Str::from_rc(name.clone()))),
PropKey::Str(name) => self.wrap_str(prefix.text(), Some(&Str::from_rc(name.clone())), ""),
PropKey::Sym(s) => match s.description() {
Some(d) => {
let d = d.clone();
self.wrap_str(&format!("{}[", prefix.text()), Some(&d), "]")
}
None => self.wrap_str(prefix.text(), None, ""),
},
}
}
/// `this key` → `this home key`: the prototype of the running method's home object, `null`
/// when it has none, and the key as a property name (MakeSuperPropertyReference, section
/// 12.3.5.3).
/// when it has none, and the key as a property name or a Symbol (MakeSuperPropertyReference,
/// section 12.3.5.3).
pub(crate) fn op_super_ref(&mut self) -> JsResult<()> {
let kv = self.peek(0)?;
let k = self.to_key(&kv)?;
let k = match self.to_prop_key(&kv)? {
PropKey::Str(name) => Value::String(Str::from_rc(name)),
PropKey::Sym(s) => Value::Symbol(s),
};
let Value::Object(home) = self.hidden_value(HOME)? else { return Err(self.throw(ErrorType::Syntax, "'super' is allowed only in methods")) };
let proto = self.object(home)?.proto.map_or(Value::Null, Value::Object);
self.replace(1, proto)?;
self.push(Value::String(Str::from_rc(k)))
self.push(k)
}
/// The three operands of a `super` property: `this`, the prototype and the key.
fn super_operands(&mut self, depth: usize) -> JsResult<(Value, ObjId, Key)> {
fn super_operands(&mut self, depth: usize) -> JsResult<(Value, ObjId, PropKey)> {
let k = self.peek(depth)?;
let proto = self.peek(depth + 1)?;
let this = self.peek(depth + 2)?;
let k = self.to_key(&k)?;
let k = self.to_prop_key(&k)?;
let Value::Object(p) = proto else {
let name = String::from_utf16_lossy(&k);
let name = self.pk_name(&k)?;
return Err(self.type_error(&format!("cannot use super property '{name}': the home object has no prototype")));
};
Ok((this, p, k))
}
/// The key as text for a message.
fn pk_name(&mut self, k: &PropKey) -> JsResult<String> {
match k {
PropKey::Str(name) => Ok(String::from_utf16_lossy(name)),
PropKey::Sym(s) => self.sym_name(s),
}
}
/// The property `k` of `start` or an object it inherits from.
fn find_pk(&mut self, start: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
match k {
PropKey::Str(name) => self.find_property(start, name),
PropKey::Sym(s) => self.find_sym(start, s),
}
}
/// [[Get]] of `k` from `start` with `receiver` as `this`.
fn get_pk_from(&mut self, start: ObjId, k: &PropKey, receiver: &Value) -> JsResult<Value> {
match k {
PropKey::Str(name) => self.get_from(start, name, receiver),
PropKey::Sym(s) => self.get_sym_from(start, s, receiver),
}
}
/// `this home key` → `value`, or with `with_this` → `value this`.
pub(crate) fn op_super_get(&mut self, with_this: bool) -> JsResult<()> {
let (this, p, k) = self.super_operands(0)?;
let v = self.get_from(p, &k, &this)?;
let v = self.get_pk_from(p, &k, &this)?;
self.replace(3, v)?;
if with_this { self.push(this) } else { Ok(()) }
}
@@ -413,7 +488,7 @@ impl Interp {
/// `this home key` → the old or new number of a `++` or `--` on a `super` property.
pub(crate) fn op_super_inc(&mut self, prefix: bool, dec: bool) -> JsResult<()> {
let (this, p, k) = self.super_operands(0)?;
let v = self.get_from(p, &k, &this)?;
let v = self.get_pk_from(p, &k, &this)?;
let old = self.to_number(&v)?;
let new = if dec { old - 1.0 } else { old + 1.0 };
self.super_put(p, k, Value::Number(new), &this)?;
@@ -424,9 +499,9 @@ impl Interp {
/// that cannot be made throws a `TypeError` in strict mode code and in code from a source with
/// [`crate::bytecode::Source::strict_writes`], and does nothing otherwise (PutValue, section
/// 6.2.3.2).
fn super_put(&mut self, proto: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult<()> {
fn super_put(&mut self, proto: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult<()> {
let throw = self.strict_writes();
let why = match self.find_property(proto, &k)? {
let why = match self.find_pk(proto, &k)? {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => Some("it has only a getter"),
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Some("it is read-only"),
@@ -434,7 +509,7 @@ impl Interp {
};
let (r, desc) = match (why, receiver) {
(Some(why), _) => return self.super_reject(throw, &k, why),
(None, Value::Object(r)) => match self.get_own_property(*r, &k)? {
(None, Value::Object(r)) => match self.get_own_pk(*r, &k)? {
Some(Prop::Accessor { .. }) => return self.super_reject(throw, &k, "it is an accessor"),
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.super_reject(throw, &k, "it is read-only"),
Some(Prop::Data { .. }) => (*r, Desc { value: Some(v), ..Desc::default() }),
@@ -442,14 +517,14 @@ impl Interp {
},
(None, _) => return self.super_reject(throw, &k, "`this` is a primitive value"),
};
self.define_own_property(r, k, &desc, throw).map(drop)
self.define_own_pk(r, k, &desc, throw).map(drop)
}
fn super_reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> {
fn super_reject(&mut self, throw: bool, k: &PropKey, why: &str) -> JsResult<()> {
if !throw {
return Ok(());
}
let name = String::from_utf16_lossy(k);
let name = self.pk_name(k)?;
Err(self.type_error(&format!("cannot assign to property '{name}': {why}")))
}
+21 -1
View File
@@ -1655,6 +1655,14 @@ impl<'a> FnCompiler<'a> {
let ctor = self.function(class.constructor)?;
self.at(class.span.start);
self.emit(Op::ClassStart { ctor, heritage: class.heritage.is_some() });
// A named class's constructor is named after it before its methods are defined, so a
// static method `name` replaces that name (ECMA-262 2015 section 14.5.15).
if let Some(name) = &class.name {
let n = self.name_key(key_of(&name.name));
self.emit(Op::Pick(1));
self.emit(Op::SetFunctionName(n));
self.emit(Op::Pop);
}
for element in &class.elements {
match &element.key {
ClassKey::Fixed(k) => {
@@ -1766,6 +1774,16 @@ impl<'a> FnCompiler<'a> {
}
self.emit(Op::InitIndex);
}
// A method or an accessor with a home object is named as it is defined.
PropertyValue::Method(f) | PropertyValue::Get(f) | PropertyValue::Set(f) if self.ast.function(*f).is_some_and(|f| f.home) => {
let func = self.function(*f)?;
let kind = match value {
PropertyValue::Get(_) => 1,
PropertyValue::Set(_) => 2,
_ => 0,
};
self.emit(Op::InitMethodKey { func, kind });
}
PropertyValue::Get(f) | PropertyValue::Set(f) => {
let getter = matches!(value, PropertyValue::Get(_));
let i = self.function(*f)?;
@@ -1784,11 +1802,13 @@ impl<'a> FnCompiler<'a> {
}
/// The expression is an anonymous function definition (ECMA-262 2015 section 14.1.9): a
/// function expression without a name or an arrow function, parenthesized or not.
/// function expression without a name or an arrow function, parenthesized or not, or a class
/// expression without a name.
fn is_anonymous_function(&self, e: ExprId) -> bool {
match self.ast.expr(self.ast.unparenthesized(e)) {
Some(Expr::Arrow(_)) => true,
Some(Expr::Function(fid)) => self.ast.function(*fid).is_some_and(|f| f.name.is_none()),
Some(Expr::Class(class)) => class.name.is_none(),
_ => false,
}
}
+59 -1
View File
@@ -1205,6 +1205,64 @@ fn classes_make_constructors_with_methods_on_their_prototype() {
throws("class A { m() { undeclared = 1; } } new A().m();", "ReferenceError");
}
#[test]
fn classes_and_their_methods_are_named_after_their_keys() {
let named = |f: &str| {
format!(
"(function (f) {{ var d = Object.getOwnPropertyDescriptor(f, 'name'); return d.value + (d.writable || d.enumerable ? '!' : '') + (d.configurable ? '' : '!'); }})({f})"
)
};
let src = "var d = Symbol('d'), e = Symbol(); class A { m() {} get g() {} set s(v) {} static [Symbol.iterator]() {} static [d]() {} [e]() {} ['c' + 1]() {} }";
assert_eq!(string(&format!("{src} {}", named("A"))), "A");
assert_eq!(string(&format!("{src} {}", named("A.prototype.m"))), "m");
assert_eq!(string(&format!("{src} {}", named("Object.getOwnPropertyDescriptor(A.prototype, 'g').get"))), "get g");
assert_eq!(string(&format!("{src} {}", named("Object.getOwnPropertyDescriptor(A.prototype, 's').set"))), "set s");
assert_eq!(string(&format!("{src} {}", named("A[Symbol.iterator]"))), "[Symbol.iterator]");
assert_eq!(string(&format!("{src} {}", named("A.prototype.c1"))), "c1");
truth(&format!("{src} A[d].name === '[d]' && A.prototype[e].name === ''"));
// A static `name` member replaces the class's name.
truth("class B { static name() { return 1; } } typeof B.name === 'function' && B.name() === 1");
// An anonymous class takes the name of what it is assigned to.
truth("var C = class {}; var o = { D: class {} }; C.name === 'C' && o.D.name === 'D' && (class {}).name === ''");
truth("var E = class { static name() {} }; typeof E.name === 'function'");
truth("var G = class { static ['foo']() {} static [Symbol.iterator]() {} }; G.name === 'G'");
truth("var H = class { static ['na' + 'me']() {} }; typeof H.name === 'function'");
truth("var I = class { static get name() { return 'x'; } }; I.name === 'x'");
truth("var F = class Inner {}; F.name === 'Inner'");
}
#[test]
fn classes_have_generator_methods() {
let src = "class P { *items() { yield 1; } } class A extends P { *m(n) { yield n; yield* super.items(); } static *[Symbol.iterator]() { yield 'a'; yield 'b'; } }";
truth(&format!("{src} var it = new A().m(5); it.next().value === 5 && it.next().value === 1 && it.next().done"));
truth(&format!("{src} [...A].join() === 'a,b' && A.prototype.m.name === 'm'"));
truth(&format!(
"{src} var d = Object.getOwnPropertyDescriptor(A.prototype, 'm'); !d.enumerable && Object.getPrototypeOf(new A().m()) === A.prototype.m.prototype"
));
throws(&format!("{src} new A.prototype.m()"), "TypeError");
syntax("class A { static *prototype() {} }");
syntax("class A { *m() { yield = 1; } }");
truth("class A { *get() { yield 2; } } new A().get().next().value === 2");
}
#[test]
fn computed_methods_and_accessors_of_object_literals_have_a_home_object() {
let src = "var p = { x: 1 }; var k = Symbol('k'); var o = { __proto__: p, ['m']() { return super.x; }, get [k]() { return super.x + 1; }, set ['s'](v) { super.x = v; } };";
truth(&format!("{src} o.m() === 1 && o[k] === 2 && o.m.name === 'm'"));
truth(&format!("{src} o.s = 5; o.x === 5 && p.x === 1 && Object.getOwnPropertyDescriptor(o, k).get.name === 'get [k]'"));
truth(&format!("{src} Object.getOwnPropertyDescriptor(o, 'm').enumerable && !o.m.hasOwnProperty('prototype')"));
throws(&format!("{src} new o.m()"), "TypeError");
}
#[test]
fn super_properties_read_and_write_symbol_keys() {
let src = "var s = Symbol('s'); class P {} P.prototype[s] = 5; class Q extends P { f() { return super[s]; } g() { super[s] = 7; return this[s]; } h() { super[s]++; return this[s]; } }";
truth(&format!("{src} new Q().f() === 5"));
truth(&format!("{src} var q = new Q(); q.g() === 7 && q.hasOwnProperty(s) && P.prototype[s] === 5"));
truth(&format!("{src} new Q().h() === 6"));
truth("var s = Symbol(); var o = { __proto__: { [s]() { return 3; } }, m() { return super[s](); } }; o.m() === 3");
}
#[test]
fn static_and_accessor_members_go_on_the_constructor_and_prototype() {
truth("class A { static make() { return new A(); } } A.make() instanceof A");
@@ -1514,7 +1572,7 @@ fn class_bindings_follow_let_rules() {
syntax("class {}");
syntax("class A { constructor() {} constructor() {} }");
syntax("class A { get constructor() {} }");
syntax("class A { *g() {} }");
syntax("class A { *constructor() {} }");
syntax("class A { m() { super(); } }");
syntax("class A extends Object { m() { super(); } }");
syntax("function f() { super.x; }");
+13
View File
@@ -1309,6 +1309,7 @@ impl Interp {
}
Op::ClassMethod { func, kind, is_static } => self.op_class_method(func, kind, is_static),
Op::InitMethod { func, kind, name } => self.op_init_method(func, kind, name),
Op::InitMethodKey { func, kind } => self.op_init_method_key(func, kind),
Op::SuperRef => self.op_super_ref(),
Op::SuperGet => self.op_super_get(false),
Op::SuperGetThis => self.op_super_get(true),
@@ -2465,6 +2466,18 @@ impl Interp {
/// Gives `f` its `name` (ECMA-262 2015 section 9.2.11): not writable, not enumerable,
/// configurable.
pub(crate) fn set_function_name(&mut self, f: ObjId, name: Value) -> JsResult<()> {
// A class whose static members define `name` keeps that member (section 12.14.4,
// step 1.e): its own `name` is no longer the empty string it was made with.
let object = self.object(f)?;
let class_ctor = matches!(&object.class, Class::Function(Func::Closure { code, .. }) if code.class_ctor);
let default = match object.props.get(&key("name")) {
None => true,
Some(Prop::Data { value: Value::String(s), .. }) => s.len() == 0,
Some(_) => false,
};
if class_ctor && !default {
return Ok(());
}
// The empty `name` an ECMAScript 2015 function is made with is replaced in place.
if !self.object(f)?.props.contains(&key("name")) {
self.rooted(&[name.clone(), Value::Object(f)], |i| i.reserve_heap(PROP_BYTES + string_bytes("name".len())))?;
+6 -5
View File
@@ -1973,16 +1973,14 @@ impl<'s> Parser<'s> {
self.bump()?;
}
let start = self.tok.span;
if self.at(Punct::Star) {
return Err(self.error_at_token(&self.tok, "generator methods are not supported"));
}
let generator = self.eat(Punct::Star)?;
// `get` and `set` start an accessor only when written without escapes and followed by a name.
let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) {
Some("get") => Some(MethodKind::Get),
Some("set") => Some(MethodKind::Set),
_ => None,
}
.filter(|_| self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
.filter(|_| !generator && self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket)));
if accessor.is_some() {
self.bump()?;
}
@@ -1999,6 +1997,9 @@ impl<'s> Parser<'s> {
if kind != MethodKind::Method {
return Err(self.error_at_offset(start.start, "a class constructor cannot be a getter or a setter"));
}
if generator {
return Err(self.error_at_offset(start.start, "a class constructor cannot be a generator"));
}
let ctor = if derived { FunctionKind::DerivedConstructor } else { FunctionKind::ClassConstructor };
return Ok(Err(self.parse_function_with(ctor, None, start, true, false)?));
}
@@ -2010,7 +2011,7 @@ impl<'s> Parser<'s> {
MethodKind::Get => FunctionKind::Getter,
MethodKind::Set => FunctionKind::Setter,
};
let function = self.parse_function_with(fkind, None, start, true, false)?;
let function = self.parse_function_with(fkind, None, start, true, generator)?;
Ok(Ok(ClassElement { key, is_static, kind, function }))
}
+1 -1
View File
@@ -2733,7 +2733,7 @@ an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-in
20.2.4.2). A function's `length` can be redefined. The built-in functions get their names the first time a run reads
ECMAScript 2015, and keep them in later `.jsx` runs of an engine that `#targetengine` keeps. A `.js` script also has
generator functions (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/):
`function*` declarations and expressions, `*name() {…}` methods in object literals, `yield`, and `yield*`, which
`function*` declarations and expressions, `*name() {…}` methods in object literals and classes, `yield`, and `yield*`, which
passes `next`, `throw` and `return` on to the iterator it delegates to. Calling a generator function returns a
generator object whose `next`, `return` and `throw` run its body to the next `yield`; `return` runs the body's
`finally` blocks, and resuming a generator while its body runs throws a `TypeError`. Each resumption takes fuel and
+1 -1
View File
@@ -1149,7 +1149,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, and computed method names; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods written in object literals, which are enumerable. `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `super` and `new.target` in code given to direct `eval`, function `name` properties and computed keys outside classes are not supported yet. With the class, `super` and `new.target` tests added, `cargo xtask test262` reads 1,175 tests of these forms: with the option, all 554 negative parse runs and 1,527 of 1,731 other runs pass (537 and 43 without it). Of the 204 failing runs, 98 do not parse because the tests also use forms `vectorcraft-js` does not read (destructuring, `for`-`of`, generators, binary and octal number literals, trailing commas in parameter lists, async arrow functions, and a later edition's rule for escapes in tagged templates); of the other 106, 36 use `Object.setPrototypeOf` or `RegExp.prototype.flags`, which `vectorcraft-js` does not have, 62 expect function `name` properties, a configurable `length` or the `caller` and `arguments` restrictions, and 8 use `super` or `new.target` in direct `eval`. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `super` and `new.target` in code given to direct `eval` are not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
- `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`.
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.