From 95d1f700418f32db2c0bf99afb1bafa37c40bcf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:17:22 -0800 Subject: [PATCH] Scripts: .js scripts define classes with extends, super and new.target With Options::es2015, vectorcraft-js reads and runs ECMAScript 2015 classes: 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 throws a ReferenceError until super(...) returns, and its default constructor passes its arguments on. super.name and super[key] read, call and write through the prototype of the method's home object, in class methods and in object literal methods, which ES2015 allows in a .js script. new.target names the constructor new was applied to, in functions and their arrow functions. 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; extending any other built-in throws a TypeError. Each class and method takes fuel and counts against the heap limit, and deep constructor chains stop at the frame limit. A .jsx file and a source string stay ES5.1, where class syntax is a SyntaxError. The test262 runner adds the class, super and new.target tests to its ES2015 subset (1,125 tests). With the option, 554 of 554 negative parse runs and 1,527 of 1,633 other runs pass; the failing runs use Object.setPrototypeOf, RegExp.prototype.flags, function name properties, a configurable length, the caller and arguments restrictions, or super and new.target in direct eval. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/tests/script_run.rs | 23 ++ crates/js/src/ast.rs | 66 ++++ crates/js/src/bytecode.rs | 87 ++++- crates/js/src/class_ops.rs | 484 ++++++++++++++++++++++++++ crates/js/src/compiler.rs | 174 ++++++++- crates/js/src/es2015_tests.rs | 210 ++++++++++- crates/js/src/interp.rs | 160 +++++---- crates/js/src/interp_tests.rs | 4 + crates/js/src/lib.rs | 6 +- crates/js/src/parser.rs | 253 +++++++++++++- crates/js/tests/test262.rs | 10 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 3 +- 13 files changed, 1395 insertions(+), 94 deletions(-) create mode 100644 crates/js/src/class_ops.rs diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..2ee69f12c3 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -331,6 +331,29 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_defines_classes_and_a_jsx_script_cannot() { + let dir = fresh_folder("es2015-classes"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let modern = "class Shape { constructor(n) { this.n = n; } sides() { return this.n; } }\n\ + class Square extends Shape { constructor() { super(4); } sides() { return super.sides() * 10; } }\n\ + vc.log(new Square().sides());\nvc.log(eval('class E {} typeof E'));\n"; + let r = s.execute("script.run", &path(&write("shapes.js", modern))).unwrap(); + assert_eq!(r["log"], json!([40, "function"]), "{r}"); + for (name, text) in [("legacy.jsx", "class A {}"), ("object.jsx", "var o = { m() {} };")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + assert!(run(&mut s, "var C = class {};").unwrap_err().to_string().contains("SyntaxError")); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..409b5a25bb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -98,6 +98,8 @@ pub enum PropertyValue { Init(ExprId), Get(FunctionId), Set(FunctionId), + /// A method (`m() {…}`, ECMA-262 2015 section 14.3). + Method(FunctionId), } #[derive(Clone, Debug, PartialEq)] @@ -218,6 +220,54 @@ pub enum Expr { /// `...expression` in an array literal or an argument list, and as the last of an arrow /// function's parenthesized parameters while they are read. Spread(ExprId), + /// A class expression. + Class(Box), + /// `super(arguments)` in a derived class's constructor. + SuperCall(Vec), + /// `super.property` in a class's methods and constructor. + SuperMember(Name), + /// `super[index]`. + SuperIndex(ExprId), + /// `new.target`. + NewTarget, +} + +/// A class declaration or expression (ECMA-262 2015 section 14.5). +#[derive(Clone, Debug, PartialEq)] +pub struct ClassDef { + pub name: Option, + /// The expression after `extends`. + pub heritage: Option, + /// The constructor as written, or the default one a class without one gets. Its span is the + /// class's. + pub constructor: FunctionId, + /// The methods and accessors other than the constructor, in source order. + pub elements: Vec, + pub span: Span, +} + +/// A method or accessor in a class body. +#[derive(Clone, Debug, PartialEq)] +pub struct ClassElement { + pub key: ClassKey, + /// Defined on the constructor (`static`) rather than on its `prototype`. + pub is_static: bool, + pub kind: MethodKind, + pub function: FunctionId, +} + +/// A class element's name: written out, or computed (`[expression]`). +#[derive(Clone, Debug, PartialEq)] +pub enum ClassKey { + Fixed(PropertyKey), + Computed(ExprId), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MethodKind { + Method, + Get, + Set, } /// A piece of a template literal's text between its substitutions. @@ -314,6 +364,8 @@ pub enum Stmt { /// `let` or `const` declarations (a `const` always has an initializer). Lexical(LexKind, Vec), FunctionDecl(FunctionId), + /// A class declaration, its name a `let`-like binding of the scope it stands in. + Class(Box), Expr(ExprId), Block(Vec), Empty, @@ -377,6 +429,12 @@ pub enum FunctionKind { Setter, /// An arrow function; one with an expression body has a body of one `return` statement. Arrow, + /// A method in a class body. + Method, + /// The constructor of a class without `extends`. + ClassConstructor, + /// The constructor of a class with `extends`. + DerivedConstructor, } #[derive(Clone, Debug, PartialEq)] @@ -394,9 +452,17 @@ pub struct Function { /// or the code around it is strict. pub strict: bool, pub span: Span, + /// The function is defined in a class body (a method, an accessor or the constructor): it has + /// a home object for `super.property`. + pub home: bool, } impl Function { + /// The function is a class constructor. + pub fn is_class_constructor(&self) -> bool { + matches!(self.kind, FunctionKind::ClassConstructor | FunctionKind::DerivedConstructor) + } + /// The parameters are plain names: no default value and no rest parameter. pub fn simple_params(&self) -> bool { self.rest.is_none() && self.defaults.iter().all(Option::is_none) diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..08dff47905 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -36,6 +36,8 @@ pub(crate) enum Op { Swap, /// `a b c` → `b c a`. Rot3, + /// Pushes a copy of the value `n` places under the top one (`Pick(0)` is `Dup`). + Pick(u32), /// Pushes the value of the variable `names[i]`. GetVar(u32), /// Pushes the value of the variable and the `this` a call to it gets. @@ -205,6 +207,59 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `[superclass]` → `constructor prototype`: makes a class's prototype object and its + /// constructor from `functions[ctor]`, the superclass on the stack when `heritage` is true + /// (ECMA-262 2015 section 14.5.14). + ClassStart { + ctor: u32, + heritage: bool, + }, + /// `constructor prototype key` → `constructor prototype`: defines the method, getter (`kind` 1) + /// or setter (`kind` 2) made from `functions[func]` under the key, on the constructor when + /// `is_static` is true and otherwise on the prototype. + ClassMethod { + func: u32, + kind: u8, + is_static: bool, + }, + /// `object` → `object`: defines the enumerable method, getter (`kind` 1) or setter (`kind` + /// 2) made from `functions[func]` under `names[name]` on an object literal's object, its home + /// object (section 12.2.6.8). + InitMethod { + func: u32, + kind: u8, + name: u32, + }, + /// `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, + /// `this home key` → the property's value, read from the home object with `this` as the + /// receiver. + SuperGet, + /// `this home key` → `value this`, for a call. + SuperGetThis, + /// `this home key value` → `value`, written through the home object with `this` as the + /// receiver. + SuperSet, + /// `this home key` → `this home key this home key`. + SuperDup, + /// `this home key` → the old or new value: `++` or `--` on a `super` property. + SuperInc { + prefix: bool, + dec: bool, + }, + /// Pushes the constructor `super(…)` calls: the prototype of the running class constructor. + SuperCtor, + /// `constructor arg…` → the object it constructs, with the running constructor's + /// `new.target`. + SuperCall(u32), + /// `constructor array` → the object it constructs, with the array's elements as arguments. + SuperCallSpread, + /// `value` → `value`: binds the running derived constructor's `this` to the value; a + /// `ReferenceError` when it is bound already. + BindThis, + /// Pushes `new.target`. + NewTarget, } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -299,6 +354,15 @@ pub(crate) struct Code { /// The function has default or rest parameters: its parameters start uninitialized, its /// code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The code is a class constructor's: calling it without `new` is a `TypeError`. + pub(crate) class_ctor: bool, + /// The code is a derived class constructor's: its `this` is bound by `super(…)`. + pub(crate) derived: bool, + /// The code is a class method's or accessor's: it has no `prototype` and is not a + /// constructor. + pub(crate) method: bool, + /// The code reads `new.target`, itself or in an arrow function inside it. + pub(crate) uses_new_target: bool, } impl Code { @@ -347,6 +411,10 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::Dup2 => e(2, 4), Op::Swap | Op::ToKey => e(2, 2), Op::Rot3 => e(3, 3), + Op::Pick(n) => { + let below = n.checked_add(1).ok_or("operand too large")?; + e(below, below.checked_add(1).ok_or("operand too large")?) + } Op::GetVarThis(_) => e(0, 2), Op::SetVar(_) | Op::GetMember(_) | Op::DeleteMember(_) | Op::IncMember { .. } => e(1, 1), Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber | Op::ArrayHole | Op::ForInStart | Op::CheckObject => e(1, 1), @@ -381,6 +449,19 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), Op::ToStr => e(1, 1), + Op::ClassStart { heritage, .. } => e(u32::from(heritage), 2), + Op::ClassMethod { .. } => e(3, 2), + Op::InitMethod { .. } => e(1, 1), + Op::SuperRef => e(2, 3), + Op::SuperGet => e(3, 1), + Op::SuperGetThis => e(3, 2), + Op::SuperSet => e(4, 1), + Op::SuperDup => e(3, 6), + Op::SuperInc { .. } => e(3, 1), + Op::SuperCtor | Op::NewTarget => e(0, 1), + Op::SuperCall(n) => e(n.checked_add(1).ok_or("operand too large")?, 1), + Op::SuperCallSpread => e(2, 1), + Op::BindThis => e(1, 1), }) } @@ -411,7 +492,11 @@ 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) => check(i, code.functions.len(), "function"), + Op::Closure(i) | Op::ClassStart { ctor: i, .. } | Op::ClassMethod { func: i, .. } => check(i, code.functions.len(), "function"), + Op::InitMethod { func, name, .. } => { + check(func, code.functions.len(), "function")?; + check(name, code.names.len(), "name") + } Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs new file mode 100644 index 0000000000..a6cf6d2949 --- /dev/null +++ b/crates/js/src/class_ops.rs @@ -0,0 +1,484 @@ +//! Classes, `super` and `new.target` (ECMA-262 2015 sections 12.3.5, 12.3.8 and 14.5), and +//! `new` with a `new.target` (sections 7.3.13 and 9.2.2). +//! +//! The running code reaches what these need through bindings whose names start with a NUL, +//! which no identifier holds: +//! +//! - `\0this` holds a derived class constructor's `this`, uninitialized until `super(…)` returns, +//! and the `this` an arrow function closes over. +//! - `\0func` holds a derived class constructor's function object, whose prototype `super(…)` +//! constructs. +//! - `\0newtarget` holds `new.target` for the arrow functions inside a function. +//! - `\0home` holds the home object of a class method, in an environment of the method's own. + +use std::rc::Rc; + +use crate::bytecode::Code; +use crate::heap::{ + Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, Func, HIDDEN, Key, 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::value::{Str, Value}; + +const FUNC: &[u16] = &[0, 0x66, 0x75, 0x6E, 0x63]; +const NEW_TARGET: &[u16] = &[0, 0x6E, 0x65, 0x77, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74]; +const HOME: &[u16] = &[0, 0x68, 0x6F, 0x6D, 0x65]; + +/// The most bound functions `new` and `IsConstructor` unwrap in one chain. +const MAX_BOUND_CHAIN: usize = 10_000; + +/// The bytes of the hidden bindings [`Interp::function_bindings`] adds for `code`. +pub(crate) fn hidden_bytes(code: &Code) -> usize { + if code.derived { + binding_bytes(ARROW_THIS.len()) + binding_bytes(FUNC.len()) + binding_bytes(NEW_TARGET.len()) + } else if code.uses_new_target && !code.arrow { + binding_bytes(NEW_TARGET.len()) + } else { + 0 + } +} + +impl Interp { + /// The nearest declarative environment from `start` outward that holds `name`. + fn hidden_env(&self, start: EnvId, name: &[u16]) -> Option { + let mut cur = Some(start); + while let Some(e) = cur { + match self.heap.env(e)? { + Env::Decl { bindings, outer } => { + if bindings.contains(name) { + return Some(e); + } + cur = *outer; + } + Env::Obj { outer, .. } => cur = *outer, + } + } + None + } + + /// The value of the hidden binding `name` nearest the running code, or `undefined`. + fn hidden_value(&self, name: &[u16]) -> JsResult { + let env = self.frame()?.env; + match self.hidden_env(env, name) { + Some(e) => self.binding_value(e, name), + None => Ok(Value::Undefined), + } + } + + /// Adds the hidden bindings of a call to `code` to its function environment `env`: a derived + /// class constructor's `this`, function object and `new.target`, and the `new.target` of a + /// function whose arrow functions read it. Gives the environment of a derived constructor's + /// `this`. The caller has reserved [`hidden_bytes`] of `code`. + pub(crate) fn function_bindings(&mut self, code: &Code, env: EnvId, callee: ObjId, new_target: Option) -> JsResult> { + let nt = new_target.map_or(Value::Undefined, Value::Object); + if code.derived { + self.env_insert(env, Rc::from(ARROW_THIS), Binding::lexical(false))?; + self.env_insert(env, Rc::from(FUNC), Binding::new(Value::Object(callee), false, false))?; + self.env_insert(env, Rc::from(NEW_TARGET), Binding::new(nt, false, false))?; + return Ok(Some(env)); + } + if code.uses_new_target && !code.arrow { + self.env_insert(env, Rc::from(NEW_TARGET), Binding::new(nt, false, false))?; + } + Ok(None) + } + + /// The `this` an arrow function closing over `env` starts with: `undefined` while a derived + /// constructor's `this` is not yet bound. + pub(crate) fn arrow_this(&self, env: EnvId) -> Value { + match self.hidden_env(env, ARROW_THIS) { + Some(e) if !self.uninitialized(e, ARROW_THIS) => self.binding_value(e, ARROW_THIS).unwrap_or(Value::Undefined), + _ => Value::Undefined, + } + } + + fn this_not_bound(&mut self) -> Abrupt { + self.throw(ErrorType::Reference, "'this' is used before super() is called") + } + + /// The value of `this` in the running code (ResolveThisBinding, section 8.3.2). In a derived + /// class constructor and the arrow functions inside it, reading it before `super(…)` returns + /// is a `ReferenceError`. + pub(crate) fn this_value(&mut self) -> JsResult { + let frame = self.frame()?; + if (frame.code.arrow || frame.code.derived) + && let Some(e) = self.hidden_env(frame.env, ARROW_THIS) + { + if self.uninitialized(e, ARROW_THIS) { + return Err(self.this_not_bound()); + } + return self.binding_value(e, ARROW_THIS); + } + Ok(self.frame()?.this.clone()) + } + + /// What a derived class constructor whose `this` is in `env` gives for the return value `v` + /// (section 9.2.2, steps 13 to 15). + pub(crate) fn derived_result(&mut self, env: EnvId, v: Value) -> JsResult { + match v { + Value::Object(_) => Ok(v), + Value::Undefined if self.uninitialized(env, ARROW_THIS) => Err(self.this_not_bound()), + Value::Undefined => self.binding_value(env, ARROW_THIS), + _ => Err(self.type_error("a derived class constructor must return an object or undefined")), + } + } + + /// IsConstructor (section 7.2.4). + pub(crate) fn is_constructor(&self, v: &Value) -> bool { + let mut v = v.clone(); + for _ in 0..MAX_BOUND_CHAIN { + match self.func_of(&v) { + Some(Func::Closure { code, .. }) => return !(code.arrow || code.method), + Some(Func::Native { constructor, .. }) => return constructor, + Some(Func::Bound { target, .. }) => v = Value::Object(target), + _ => return false, + } + } + false + } + + /// Does the built-in constructor `f` make objects that a subclass may give its own + /// prototype? It does when its `prototype` is one of the realm's built-in prototypes. + fn subclassable(&self, f: ObjId) -> JsResult { + let Some(Prop::Data { value: Value::Object(p), .. }) = self.get_own_property(f, &key("prototype"))? else { return Ok(false) }; + let i = &self.intrinsics; + Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto] + .contains(&p) + || i.error_protos.contains(&p)) + } + + /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). + fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { + match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? { + Value::Object(p) => Ok(p), + _ => Ok(fallback), + } + } + + /// Does the prototype chain from `start` reach `target`? + fn chain_reaches(&self, start: ObjId, target: ObjId) -> JsResult { + let mut cur = Some(start); + let mut steps = 0usize; + while let Some(o) = cur { + if o == target { + return Ok(true); + } + steps += 1; + if steps > 1_000_000 { + return Ok(true); + } + cur = self.object(o)?.proto; + } + Ok(false) + } + + /// Constructs `f` with `args` and `new_target` (`f` itself when `None`) and pushes the + /// result, or the frame that makes it, after taking the stack back to `start`. The operands + /// at `start` and above keep `f` and `args` reachable. + pub(crate) fn construct(&mut self, start: usize, f: Value, mut args: Vec, new_target: Option) -> JsResult<()> { + let mut f = f; + let mut new_target = new_target; + // A bound function constructs its target with its arguments first, and a `new.target` + // that is the bound function becomes the target (section 9.4.1.2). + let mut steps = 0usize; + while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { + self.use_fuel()?; + steps += 1; + if steps > MAX_BOUND_CHAIN { + return Err(self.type_error("the value is not a constructor")); + } + let mut all = bound_args.to_vec(); + all.append(&mut args); + args = all; + if new_target.is_some() && new_target == f.as_object() { + new_target = Some(target); + } + f = Value::Object(target); + } + let Some(callee) = f.as_object() else { return Err(self.type_error("the value is not a constructor")) }; + let nt = new_target.unwrap_or(callee); + match self.func_of(&f) { + Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), + Some(Func::Closure { code, env }) if code.derived => { + self.stack.truncate(start); + self.enter_function(Entry { callee, code, env, this: Value::Undefined, args, new_target: Some(nt) }, None, false) + } + Some(Func::Closure { code, env }) => { + let fallback = self.intrinsics.object_proto; + let proto = self.prototype_from(nt, fallback)?; + let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + self.stack.truncate(start); + self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args, new_target: Some(nt) }, Some(obj), false) + } + Some(Func::Native { f: native, constructor: true, .. }) => { + let subclass = nt != callee; + if subclass && !self.subclassable(callee)? { + return Err(self.type_error("this built-in cannot be subclassed")); + } + let intrinsic = match self.get_own_property(callee, &key("prototype"))? { + Some(Prop::Data { value: Value::Object(p), .. }) => Some(p), + _ => None, + }; + let v = if subclass && intrinsic == Some(self.intrinsics.object_proto) { + // `Object` constructed for a subclass makes an ordinary object, whatever its + // argument (section 19.1.1.1, step 1). + let fallback = self.intrinsics.object_proto; + let proto = self.prototype_from(nt, fallback)?; + Value::Object(self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))) + } else { + let held = self.held_bytes; + let r = native(self, Value::Undefined, &args, true); + self.held_bytes = held; + let v = r?; + if subclass && let Value::Object(o) = v { + let proto = self.rooted(std::slice::from_ref(&v), |i| { + let fallback = intrinsic.unwrap_or(i.intrinsics.object_proto); + i.prototype_from(nt, fallback) + })?; + if self.object(o)?.proto == intrinsic && !self.chain_reaches(proto, o)? { + self.object_mut(o)?.proto = Some(proto); + } + } + v + }; + self.stack.truncate(start); + self.push(v) + } + _ => Err(self.type_error("the value is not a constructor")), + } + } + + /// `heritage?` → `F proto`: the constructor and prototype of a class whose constructor is + /// `functions[ctor]` (ClassDefinitionEvaluation, section 14.5.14, steps 5 to 18). + pub(crate) fn op_class_start(&mut self, ctor: u32, heritage: bool) -> JsResult<()> { + self.use_fuel()?; + let (proto_parent, ctor_parent) = if heritage { + let h = self.peek(0)?; + match h { + Value::Null => (None, self.intrinsics.function_proto), + Value::Object(c) if self.is_constructor(&h) => match self.get_from(c, &key("prototype"), &h)? { + Value::Object(p) => (Some(p), c), + Value::Null => (None, c), + _ => return Err(self.type_error("the prototype of the class's superclass is not an object or null")), + }, + _ => return Err(self.type_error("a class can extend only a constructor or null")), + } + } else { + (Some(self.intrinsics.object_proto), self.intrinsics.function_proto) + }; + let frame = self.frame()?; + let env = frame.env; + let Some(code) = frame.code.functions.get(ctor as usize).cloned() else { return internal("function out of range") }; + let need = (2 * OBJECT_BYTES) + .saturating_add(ENV_BYTES) + .saturating_add(binding_bytes(HOME.len())) + .saturating_add(closure_bytes(&code)) + .saturating_add(binding_bytes("prototype".len())) + .saturating_add(binding_bytes("constructor".len())); + let roots: Vec = proto_parent.map(Value::Object).into_iter().collect(); + self.rooted(&roots, |i| i.reserve_heap(need))?; + let proto = self.heap.alloc_object(Object::new(Class::Ordinary, proto_parent)); + // The constructor's home object is the prototype, as for the other prototype methods + // (section 14.5.14, step 12). + let home = self.home_env(proto, env); + let f = self.make_closure(code, home)?; + self.object_mut(f)?.proto = Some(ctor_parent); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?; + self.define(proto, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; + if heritage { + self.pop()?; + } + self.push(Value::Object(f))?; + self.push(Value::Object(proto)) + } + + /// An environment inside `outer` whose home object is `home`. + fn home_env(&mut self, home: ObjId, outer: EnvId) -> EnvId { + let mut bindings = PropMap::default(); + bindings.insert(Rc::from(HOME), Binding::new(Value::Object(home), false, false)); + self.heap.bytes += string_bytes(HOME.len()); + self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) }) + } + + /// `F proto key` → `F proto`: defines the method `functions[func]` (`kind` 0), getter (1) or + /// setter (2) named `key` on the prototype, or with `is_static` on the constructor (section + /// 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 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) + } + + /// `object` → `object`: defines an object literal's method or accessor `functions[func]` + /// under `names[name]` (section 12.2.6.8). + 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) + } + + /// 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<()> { + 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 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))?; + let home = self.home_env(target, env); + let f = self.make_closure(code, home)?; + 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) + } + + /// `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). + pub(crate) fn op_super_ref(&mut self) -> JsResult<()> { + let kv = self.peek(0)?; + let k = self.to_key(&kv)?; + 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))) + } + + /// The three operands of a `super` property: `this`, the prototype and the key. + fn super_operands(&mut self, depth: usize) -> JsResult<(Value, ObjId, Key)> { + let k = self.peek(depth)?; + let proto = self.peek(depth + 1)?; + let this = self.peek(depth + 2)?; + let k = self.to_key(&k)?; + let Value::Object(p) = proto else { + let name = String::from_utf16_lossy(&k); + return Err(self.type_error(&format!("cannot use super property '{name}': the home object has no prototype"))); + }; + Ok((this, p, k)) + } + + /// `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)?; + self.replace(3, v)?; + if with_this { self.push(this) } else { Ok(()) } + } + + /// `this home key value` → `value`. + pub(crate) fn op_super_set(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let (this, p, k) = self.super_operands(1)?; + self.super_put(p, k, v.clone(), &this)?; + self.replace(4, v) + } + + /// `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 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)?; + self.replace(3, Value::Number(if prefix { new } else { old })) + } + + /// [[Set]] of `k` on `proto` with `receiver` as `this` (OrdinarySet, section 9.1.9). A write + /// that cannot be made throws a `TypeError` in strict mode code and does nothing otherwise + /// (PutValue, section 6.2.3.2). + fn super_put(&mut self, proto: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult<()> { + let throw = self.frame()?.code.strict; + let why = match self.find_property(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"), + _ => None, + }; + 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)? { + 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() }), + None => (*r, Desc::data(v, WRITABLE | ENUMERABLE | CONFIGURABLE)), + }, + (None, _) => return self.super_reject(throw, &k, "`this` is a primitive value"), + }; + self.define_own_property(r, k, &desc, throw).map(drop) + } + + fn super_reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { + if !throw { + return Ok(()); + } + let name = String::from_utf16_lossy(k); + Err(self.type_error(&format!("cannot assign to property '{name}': {why}"))) + } + + /// Pushes the constructor `super(…)` calls: the prototype of the running derived class + /// constructor (GetSuperConstructor, section 12.3.5.2). + pub(crate) fn op_super_ctor(&mut self) -> JsResult<()> { + let Value::Object(f) = self.hidden_value(FUNC)? else { return Err(self.throw(ErrorType::Syntax, "'super' is allowed only in constructors")) }; + let proto = self.object(f)?.proto.map_or(Value::Null, Value::Object); + self.push(proto) + } + + /// `ctor args…` → the object `ctor` constructs with the running code's `new.target` + /// (section 12.3.5.1, steps 6 to 9). + pub(crate) fn op_super_call(&mut self, argc: u32) -> JsResult<()> { + let n = argc as usize; + let start = + self.stack.len().checked_sub(n + 1).filter(|&s| s >= self.base()).ok_or_else(|| Abrupt::Internal("super call below the stack".into()))?; + let ctor = self.stack.get(start).cloned().unwrap_or(Value::Undefined); + if !self.is_constructor(&ctor) { + return Err(self.type_error("the superclass is not a constructor")); + } + let Value::Object(nt) = self.hidden_value(NEW_TARGET)? else { return Err(self.type_error("super() needs new.target")) }; + let args: Vec = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default(); + self.construct(start, ctor, args, Some(nt)) + } + + /// `value` → `value`: binds the running derived class constructor's `this` to the object + /// `super(…)` made; a second binding is a `ReferenceError` (section 8.1.1.3.1). + pub(crate) fn op_bind_this(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let frame = self.frame()?; + let (start, own) = (frame.env, frame.this_env); + let Some(env) = self.hidden_env(start, ARROW_THIS) else { return internal("super() outside a derived constructor") }; + if !self.uninitialized(env, ARROW_THIS) { + return Err(self.throw(ErrorType::Reference, "super() was already called")); + } + if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) + && let Some(b) = bindings.get_mut(ARROW_THIS) + { + b.value = v.clone(); + b.uninitialized = false; + } + if own == Some(env) { + self.frame_mut()?.this = v; + } + Ok(()) + } + + /// Pushes `new.target` (section 12.3.8.1). + pub(crate) fn op_new_target(&mut self) -> JsResult<()> { + let frame = self.frame()?; + let v = if frame.code.arrow { self.hidden_value(NEW_TARGET)? } else { frame.new_target.map_or(Value::Undefined, Value::Object) }; + self.push(v) + } +} diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..5f4a82ecb4 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -17,8 +17,8 @@ use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ - AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId, - TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, ClassDef, ClassKey, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, MethodKind, + PropertyValue, Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; use crate::bytecode::{BlockScope, Code, CodeKind, Handler, Op, Source, Template, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; @@ -93,6 +93,7 @@ struct FnCompiler<'a> { scopes: Vec, templates: Vec