mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
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.
This commit is contained in:
1 parent
e717698e02
commit
95d1f70041
13 files changed
+1395
-94
No files matched your search
@@ -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()));
|
||||
|
||||
@@ -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<ClassDef>),
|
||||
/// `super(arguments)` in a derived class's constructor.
|
||||
SuperCall(Vec<ExprId>),
|
||||
/// `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<Name>,
|
||||
/// The expression after `extends`.
|
||||
pub heritage: Option<ExprId>,
|
||||
/// 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<ClassElement>,
|
||||
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<VarDecl>),
|
||||
FunctionDecl(FunctionId),
|
||||
/// A class declaration, its name a `let`-like binding of the scope it stands in.
|
||||
Class(Box<ClassDef>),
|
||||
Expr(ExprId),
|
||||
Block(Vec<StmtId>),
|
||||
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)
|
||||
|
||||
@@ -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<u32>]) -> Result<Effect, String> {
|
||||
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<u32>]) -> Result<Effect, String> {
|
||||
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"),
|
||||
|
||||
@@ -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<EnvId> {
|
||||
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<Value> {
|
||||
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<ObjId>) -> JsResult<Option<EnvId>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<bool> {
|
||||
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<ObjId> {
|
||||
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<bool> {
|
||||
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<Value>, new_target: Option<ObjId>) -> 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<Value> = 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<Value> = 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)
|
||||
}
|
||||
}
|
||||
+166
-8
@@ -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<BlockScope>,
|
||||
templates: Vec<Template>,
|
||||
uses_this: bool,
|
||||
uses_new_target: bool,
|
||||
/// The function declarations at the top of the body, which are var-scoped.
|
||||
top_funcs: HashSet<StmtId>,
|
||||
/// The function declarations a block scope instantiates.
|
||||
@@ -143,6 +144,7 @@ impl<'a> FnCompiler<'a> {
|
||||
scopes: Vec::new(),
|
||||
templates: Vec::new(),
|
||||
uses_this: false,
|
||||
uses_new_target: false,
|
||||
top_funcs: HashSet::new(),
|
||||
block_funcs: HashSet::new(),
|
||||
annex: HashSet::new(),
|
||||
@@ -266,7 +268,7 @@ impl<'a> FnCompiler<'a> {
|
||||
};
|
||||
match stmt {
|
||||
Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))),
|
||||
Stmt::Lexical(..) => {}
|
||||
Stmt::Lexical(..) | Stmt::Class(_) => {}
|
||||
Stmt::FunctionDecl(fid) => {
|
||||
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
|
||||
return internal("function declaration without a name");
|
||||
@@ -358,19 +360,20 @@ impl<'a> FnCompiler<'a> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `let` and `const` names a statement list declares.
|
||||
/// The `let`, `const` and class names a statement list declares.
|
||||
fn lexical_names(&self, list: &[StmtId]) -> HashSet<Key> {
|
||||
list.iter()
|
||||
.filter_map(|&s| match self.ast.stmt(s) {
|
||||
Some(Stmt::Lexical(_, decls)) => Some(decls.iter().map(|d| key_of(&d.name.name))),
|
||||
Some(Stmt::Lexical(_, decls)) => Some(decls.iter().map(|d| key_of(&d.name.name)).collect::<Vec<_>>()),
|
||||
Some(Stmt::Class(class)) => Some(class.name.iter().map(|n| key_of(&n.name)).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The scope a statement list declares with [`crate::Options::es2015`]: its `let` and
|
||||
/// `const` names, and (`functions`) its function declarations. `None` when it declares none.
|
||||
/// The scope a statement list declares with [`crate::Options::es2015`]: its `let`, `const`
|
||||
/// and class names, and (`functions`) its function declarations. `None` when it declares none.
|
||||
fn list_scope(&mut self, list: &[StmtId], functions: bool) -> CResult<Option<u32>> {
|
||||
if !self.es2015 {
|
||||
return Ok(None);
|
||||
@@ -379,6 +382,7 @@ impl<'a> FnCompiler<'a> {
|
||||
for &s in list {
|
||||
match self.ast.stmt(s) {
|
||||
Some(Stmt::Lexical(kind, decls)) => scope.lets.extend(decls.iter().map(|d| (key_of(&d.name.name), *kind == LexKind::Const))),
|
||||
Some(Stmt::Class(class)) => scope.lets.extend(class.name.iter().map(|n| (key_of(&n.name), false))),
|
||||
Some(Stmt::FunctionDecl(fid)) if functions && !self.top_funcs.contains(&s) => {
|
||||
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
|
||||
return internal("function declaration without a name");
|
||||
@@ -431,10 +435,11 @@ impl<'a> FnCompiler<'a> {
|
||||
/// Compiles a nested function and returns its index in the function table.
|
||||
fn function(&mut self, fid: FunctionId) -> CResult<u32> {
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?;
|
||||
// An arrow function reads the `this` and `arguments` of the code around it.
|
||||
// An arrow function reads the `this`, `arguments` and `new.target` of the code around it.
|
||||
if code.arrow {
|
||||
self.uses_this |= code.uses_this;
|
||||
self.uses_arguments |= code.uses_arguments;
|
||||
self.uses_new_target |= code.uses_new_target;
|
||||
}
|
||||
self.functions.push(code);
|
||||
Ok(u32::try_from(self.functions.len() - 1).unwrap_or(u32::MAX))
|
||||
@@ -465,6 +470,14 @@ impl<'a> FnCompiler<'a> {
|
||||
Stmt::Var(decls) => self.var_decls(decls),
|
||||
Stmt::Lexical(_, decls) => self.lexical_decls(decls),
|
||||
Stmt::FunctionDecl(fid) => self.function_decl(id, *fid),
|
||||
Stmt::Class(class) => {
|
||||
self.class(class)?;
|
||||
let Some(name) = &class.name else { return internal("class declaration without a name") };
|
||||
self.at(name.span.start);
|
||||
let n = self.var_name(&name.name);
|
||||
self.emit(Op::InitVar(n));
|
||||
Ok(())
|
||||
}
|
||||
Stmt::Empty | Stmt::Debugger => Ok(()),
|
||||
Stmt::Expr(e) => {
|
||||
self.expr(*e)?;
|
||||
@@ -820,6 +833,12 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::Rot3);
|
||||
self.emit(Op::SetIndex);
|
||||
}
|
||||
Some(Expr::SuperMember(_) | Expr::SuperIndex(_)) => {
|
||||
self.super_ref(target)?;
|
||||
self.emit(Op::Pick(3));
|
||||
self.emit(Op::SuperSet);
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
self.emit(Op::Pop);
|
||||
@@ -859,6 +878,11 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::ForEachValue(2));
|
||||
self.emit(Op::SetIndex);
|
||||
}
|
||||
Some(Expr::SuperMember(_) | Expr::SuperIndex(_)) => {
|
||||
self.super_ref(target)?;
|
||||
self.emit(Op::ForEachValue(3));
|
||||
self.emit(Op::SuperSet);
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
self.emit(Op::Pop);
|
||||
@@ -1158,6 +1182,28 @@ impl<'a> FnCompiler<'a> {
|
||||
Expr::Template { quasis, exprs } => self.template(quasis, exprs)?,
|
||||
Expr::TaggedTemplate { .. } => self.chain(id)?,
|
||||
Expr::Spread(_) => return internal("spread outside an array literal or argument list"),
|
||||
Expr::Class(class) => self.class(class)?,
|
||||
Expr::SuperMember(_) | Expr::SuperIndex(_) => {
|
||||
self.super_ref(id)?;
|
||||
self.emit(Op::SuperGet);
|
||||
}
|
||||
Expr::SuperCall(args) => {
|
||||
self.emit(Op::SuperCtor);
|
||||
if self.has_spread(args) {
|
||||
self.spread_args(args)?;
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::SuperCallSpread);
|
||||
} else {
|
||||
self.args(args)?;
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::SuperCall(len_u32(args.len())));
|
||||
}
|
||||
self.emit(Op::BindThis);
|
||||
}
|
||||
Expr::NewTarget => {
|
||||
self.uses_new_target = true;
|
||||
self.emit(Op::NewTarget);
|
||||
}
|
||||
Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?,
|
||||
Expr::Unary { .. } => self.unary(id)?,
|
||||
Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?,
|
||||
@@ -1336,6 +1382,70 @@ impl<'a> FnCompiler<'a> {
|
||||
len_u32(self.templates.len() - 1)
|
||||
}
|
||||
|
||||
/// A class definition (ECMA-262 2015 section 14.5.14), leaving its constructor on the stack. A
|
||||
/// named class binds its name, uninitialized and constant, in a scope of its own around the
|
||||
/// heritage and the methods, and initializes it only after every method is defined (steps 21
|
||||
/// and 23), so a computed key that reads the name throws a `ReferenceError`.
|
||||
fn class(&mut self, class: &ClassDef) -> CResult<()> {
|
||||
self.at(class.span.start);
|
||||
let scope = class.name.as_ref().map(|n| self.push_scope(BlockScope { lets: vec![(key_of(&n.name), true)], funcs: Vec::new() }));
|
||||
if let Some(s) = scope {
|
||||
self.emit(Op::PushBlock(s));
|
||||
self.env_depth += 1;
|
||||
}
|
||||
if let Some(h) = class.heritage {
|
||||
self.expr(h)?;
|
||||
}
|
||||
let ctor = self.function(class.constructor)?;
|
||||
self.at(class.span.start);
|
||||
self.emit(Op::ClassStart { ctor, heritage: class.heritage.is_some() });
|
||||
for element in &class.elements {
|
||||
match &element.key {
|
||||
ClassKey::Fixed(k) => {
|
||||
let i = self.string(&k.to_utf16());
|
||||
self.emit(Op::String(i));
|
||||
}
|
||||
ClassKey::Computed(e) => self.expr(*e)?,
|
||||
}
|
||||
let func = self.function(element.function)?;
|
||||
let kind = match element.kind {
|
||||
MethodKind::Method => 0,
|
||||
MethodKind::Get => 1,
|
||||
MethodKind::Set => 2,
|
||||
};
|
||||
self.at(self.ast.function(element.function).map_or(class.span.start, |f| f.span.start));
|
||||
self.emit(Op::ClassMethod { func, kind, is_static: element.is_static });
|
||||
}
|
||||
self.emit(Op::Pop);
|
||||
if let (Some(name), Some(_)) = (&class.name, scope) {
|
||||
self.emit(Op::Dup);
|
||||
let n = self.var_name(&name.name);
|
||||
self.emit(Op::InitVar(n));
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pushes `this`, the prototype of the home object and the key of the `super` property `id`.
|
||||
/// `this` is read before the key is evaluated (ECMA-262 2020 section 12.3.5.1).
|
||||
fn super_ref(&mut self, id: ExprId) -> CResult<()> {
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.uses_this = true;
|
||||
self.emit(Op::This);
|
||||
match self.ast.expr(id) {
|
||||
Some(Expr::SuperMember(name)) => {
|
||||
let i = self.string(&name.name.encode_utf16().collect::<Vec<u16>>());
|
||||
self.emit(Op::String(i));
|
||||
}
|
||||
Some(Expr::SuperIndex(index)) => self.expr(*index)?,
|
||||
_ => return internal("not a super property"),
|
||||
}
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::SuperRef);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn object_literal(&mut self, props: &[crate::ast::Property]) -> CResult<()> {
|
||||
self.emit(Op::NewObject);
|
||||
for p in props {
|
||||
@@ -1345,6 +1455,16 @@ impl<'a> FnCompiler<'a> {
|
||||
self.expr(*e)?;
|
||||
self.emit(Op::InitProp(n));
|
||||
}
|
||||
// A method, and with ES2015 an accessor, has the object as its home object.
|
||||
PropertyValue::Method(f) => {
|
||||
let func = self.function(*f)?;
|
||||
self.emit(Op::InitMethod { func, kind: 0, name: n });
|
||||
}
|
||||
PropertyValue::Get(f) | PropertyValue::Set(f) if self.ast.function(*f).is_some_and(|f| f.home) => {
|
||||
let func = self.function(*f)?;
|
||||
let kind = if matches!(p.value, PropertyValue::Get(_)) { 1 } else { 2 };
|
||||
self.emit(Op::InitMethod { func, kind, name: n });
|
||||
}
|
||||
PropertyValue::Get(f) => {
|
||||
let i = self.function(*f)?;
|
||||
self.emit(Op::Closure(i));
|
||||
@@ -1393,6 +1513,11 @@ impl<'a> FnCompiler<'a> {
|
||||
base_has_this = true;
|
||||
eval_call = name == "eval";
|
||||
}
|
||||
Some(Expr::SuperMember(_) | Expr::SuperIndex(_)) if first_is_call => {
|
||||
self.super_ref(cur)?;
|
||||
self.emit(Op::SuperGetThis);
|
||||
base_has_this = true;
|
||||
}
|
||||
_ => self.expr(cur)?,
|
||||
}
|
||||
let count = suffixes.len();
|
||||
@@ -1534,6 +1659,17 @@ impl<'a> FnCompiler<'a> {
|
||||
self.xml_scope_ref(arg, *name)?;
|
||||
self.emit(Op::DeleteIndex);
|
||||
}
|
||||
// Deleting a `super` property is a `ReferenceError` once the reference is made
|
||||
// (ECMA-262 2015 section 12.5.4.2); `this` stands in for the result.
|
||||
Some(Expr::SuperMember(_) | Expr::SuperIndex(_)) => {
|
||||
self.super_ref(arg)?;
|
||||
self.emit(Op::Pop);
|
||||
self.emit(Op::Pop);
|
||||
let s = self.string(&"a super property cannot be deleted".encode_utf16().collect::<Vec<u16>>());
|
||||
let depth = self.depth;
|
||||
self.emit(Op::ThrowReferenceError(s));
|
||||
self.depth = depth;
|
||||
}
|
||||
_ => {
|
||||
self.expr(arg)?;
|
||||
self.emit(Op::Pop);
|
||||
@@ -1647,6 +1783,13 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::GetIndex);
|
||||
}
|
||||
}
|
||||
Some(Expr::SuperMember(_) | Expr::SuperIndex(_)) => {
|
||||
self.super_ref(target)?;
|
||||
if op.is_some() {
|
||||
self.emit(Op::SuperDup);
|
||||
self.emit(Op::SuperGet);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
if op.is_none() {
|
||||
@@ -1668,6 +1811,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::SetMember(n));
|
||||
}
|
||||
Some(Expr::Index { .. } | Expr::XmlScopeName(_)) => self.emit(Op::SetIndex),
|
||||
Some(Expr::SuperMember(_) | Expr::SuperIndex(_)) => self.emit(Op::SuperSet),
|
||||
_ => self.throw_invalid_target(),
|
||||
}
|
||||
Ok(())
|
||||
@@ -1695,6 +1839,10 @@ impl<'a> FnCompiler<'a> {
|
||||
self.xml_scope_ref(target, *name)?;
|
||||
self.emit(Op::IncIndex { prefix, dec });
|
||||
}
|
||||
Some(Expr::SuperMember(_) | Expr::SuperIndex(_)) => {
|
||||
self.super_ref(target)?;
|
||||
self.emit(Op::SuperInc { prefix, dec });
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
self.emit(Op::ToNumber);
|
||||
@@ -1762,6 +1910,10 @@ impl<'a> FnCompiler<'a> {
|
||||
arrow: meta.arrow,
|
||||
uses_this: self.uses_this,
|
||||
param_init: meta.param_init,
|
||||
class_ctor: meta.class_ctor,
|
||||
derived: meta.derived,
|
||||
method: meta.method,
|
||||
uses_new_target: self.uses_new_target,
|
||||
};
|
||||
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
|
||||
Ok(Rc::new(code))
|
||||
@@ -1780,6 +1932,9 @@ struct Meta {
|
||||
length: u32,
|
||||
arrow: bool,
|
||||
param_init: bool,
|
||||
class_ctor: bool,
|
||||
derived: bool,
|
||||
method: bool,
|
||||
}
|
||||
|
||||
fn len_u32(n: usize) -> u32 {
|
||||
@@ -1844,6 +1999,9 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
length: len_u32(length),
|
||||
arrow: f.kind == FunctionKind::Arrow,
|
||||
param_init,
|
||||
class_ctor: f.is_class_constructor(),
|
||||
derived: f.kind == FunctionKind::DerivedConstructor,
|
||||
method: f.home && !f.is_class_constructor(),
|
||||
};
|
||||
c.finish(hoisted, meta)
|
||||
}
|
||||
|
||||
@@ -408,13 +408,214 @@ fn for_each_takes_let_and_const_with_e4x() {
|
||||
assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
|
||||
}
|
||||
|
||||
// ---- classes ----
|
||||
|
||||
#[test]
|
||||
fn classes_make_constructors_with_methods_on_their_prototype() {
|
||||
truth("class A { constructor(x) { this.x = x; } get() { return this.x; } } new A(3).get() === 3");
|
||||
truth(
|
||||
"class A {} typeof A === 'function' && Object.getPrototypeOf(A) === Function.prototype && Object.getPrototypeOf(A.prototype) === Object.prototype",
|
||||
);
|
||||
truth("class A { m() {} } var d = Object.getOwnPropertyDescriptor(A.prototype, 'm'); d.writable && !d.enumerable && d.configurable");
|
||||
truth("class A {} var d = Object.getOwnPropertyDescriptor(A, 'prototype'); !d.writable && !d.enumerable && !d.configurable");
|
||||
truth("class A {} var d = Object.getOwnPropertyDescriptor(A.prototype, 'constructor'); d.value === A && !d.enumerable");
|
||||
truth("class A { m() {} } !A.prototype.m.hasOwnProperty('prototype')");
|
||||
truth("var k = 'dyn'; class A { [k + 1]() { return 1; } } new A().dyn1() === 1");
|
||||
truth("var C = class Named { who() { return Named; } }; new C().who() === C && typeof Named === 'undefined'");
|
||||
truth("class A { ;; m() { return 2; }; } new A().m() === 2");
|
||||
assert!(string("class A { m() { return 1; } } String(A)").starts_with("class A"));
|
||||
// A class body is strict mode code.
|
||||
truth("class A { m() { return this; } } A.prototype.m.call(undefined) === undefined");
|
||||
throws("class A { m() { undeclared = 1; } } new A().m();", "ReferenceError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_and_accessor_members_go_on_the_constructor_and_prototype() {
|
||||
truth("class A { static make() { return new A(); } } A.make() instanceof A");
|
||||
truth("class A { static get n() { return 4; } } A.n === 4 && !A.prototype.hasOwnProperty('n')");
|
||||
truth(
|
||||
"class A { constructor() { this._v = 1; } get v() { return this._v; } set v(x) { this._v = x * 2; } } var a = new A(); a.v = 5; a.v === 10",
|
||||
);
|
||||
truth(
|
||||
"class A { get v() { return 1; } set v(x) {} } var d = Object.getOwnPropertyDescriptor(A.prototype, 'v'); typeof d.get === 'function' && typeof d.set === 'function' && !d.enumerable",
|
||||
);
|
||||
truth(
|
||||
"class A { static() { return 's'; } get() { return 'g'; } set() { return 't'; } } var a = new A(); a.static() + a.get() + a.set() === 'sgt'",
|
||||
);
|
||||
throws("class A { static ['proto' + 'type']() {} }", "TypeError");
|
||||
syntax("class A { static prototype() {} }");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subclasses_inherit_and_reach_the_superclass_through_super() {
|
||||
truth(
|
||||
"class A { constructor(x) { this.x = x; } m() { return 'A' + this.x; } } \
|
||||
class B extends A { constructor(x) { super(x + 1); } m() { return 'B' + super.m(); } } \
|
||||
var b = new B(1); b.m() === 'BA2' && b instanceof A && Object.getPrototypeOf(B) === A",
|
||||
);
|
||||
truth("class A { constructor(...a) { this.n = a.length; } } class B extends A {} new B(1, 2, 3).n === 3");
|
||||
truth("class A { static s() { return 1; } } class B extends A { static s() { return super.s() + 1; } } B.s() === 2");
|
||||
truth("class A {} class B extends A { m() { super.x = 5; return this.x; } } var b = new B(); b.m() === 5 && !A.prototype.hasOwnProperty('x')");
|
||||
truth(
|
||||
"class A { get v() { return this.w; } } class B extends A { constructor() { super(); this.w = 7; } get v() { return super.v + 1; } } new B().v === 8",
|
||||
);
|
||||
// `super.n` reads the prototype's property and writes the instance's.
|
||||
truth(
|
||||
"class A {} A.prototype.n = 1; class B extends A { m() { super.n += 2; var a = this.n; super['n']++; return a * 10 + this.n; } } new B().m() === 32 && A.prototype.n === 1",
|
||||
);
|
||||
truth("class A { constructor() { this.made = new.target; } } class B extends A {} new B().made === B && new A().made === A");
|
||||
truth("class A {} class B extends A { constructor() { var f = () => super(); f(); this.ok = true; } } new B().ok");
|
||||
truth("function F() { this.f = 1; } class B extends F {} new B().f === 1");
|
||||
truth("class E extends Error { constructor(m) { super(m); } } var e = new E('x'); e instanceof E && e instanceof Error && e.message === 'x'");
|
||||
truth("class L extends Array {} var l = new L(); l.push(1); l instanceof L && l.length === 1");
|
||||
throws("class A {} class B extends A { m() { delete super.x; } } new B().m();", "ReferenceError");
|
||||
// The constructor's home object is the prototype (section 14.5.14, step 12), so `super.x` in
|
||||
// it reads the superclass's prototype, not the superclass.
|
||||
truth(
|
||||
"class A { m() { return 'p'; } static m() { return 's'; } } \
|
||||
class B extends A { constructor() { super(); this.r = super.m(); } } new B().r === 'p'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_literal_methods_are_enumerable_and_reach_super() {
|
||||
truth("var o = { m(x) { return x + 1; } }; o.m(1) === 2 && Object.keys(o).join() === 'm'");
|
||||
truth("var o = { m() {} }; !o.m.hasOwnProperty('prototype')");
|
||||
throws("var o = { m() {} }; new o.m();", "TypeError");
|
||||
// `super` reads the home object's prototype, `Object.prototype`, as it is at the access.
|
||||
truth(
|
||||
"Object.prototype.hi = function () { return 'base ' + this.n; }; var o = { n: 1, hi() { return 'o ' + super.hi(); } }; o.hi() === 'o base 1'",
|
||||
);
|
||||
truth("Object.prototype.v = 1; var o = { v: 9, m() { return super.v; } }; var a = o.m(); Object.prototype.v = 2; a === 1 && o.m() === 2");
|
||||
truth("Object.prototype.v = 3; var o = { v: 9, get g() { return super.v; } }; o.g === 3");
|
||||
truth("Object.prototype.v = 4; var o = { v: 9, m() { return (() => super.v)(); } }; o.m() === 4");
|
||||
truth("var o = { get: 1, set: 2, get() { return 3; } }; o.get() === 3 && o.set === 2");
|
||||
// A `super` write that cannot be made does nothing outside strict mode code.
|
||||
truth("var o = { m() { super.x = 1; Object.freeze(o); super.y = 2; return 1; } }; o.m() === 1 && o.x === 1 && !('y' in o)");
|
||||
throws("var o = { m() { 'use strict'; Object.freeze(o); super.y = 2; } }; o.m();", "TypeError");
|
||||
syntax("var o = { m() { super(); } };");
|
||||
syntax("var o = { f: function () { return super.x; } };");
|
||||
let r = Realm::new().run("var o = { m() {} };");
|
||||
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_before_super_is_a_reference_error() {
|
||||
throws("class A {} class B extends A { constructor() { this.x = 1; super(); } } new B();", "ReferenceError");
|
||||
throws("class A {} class B extends A { constructor() { var f = () => this; f(); super(); } } new B();", "ReferenceError");
|
||||
throws("class A {} class B extends A { constructor() {} } new B();", "ReferenceError");
|
||||
throws("class A {} class B extends A { constructor() { super(); super(); } } new B();", "ReferenceError");
|
||||
throws("class A {} class B extends A { constructor() { return 1; } } new B();", "TypeError");
|
||||
truth("class A {} class B extends A { constructor() { return { o: 1 }; } } new B().o === 1");
|
||||
truth("class A {} class B extends A { constructor() { var f = () => this; super(); this.f = f; } } var b = new B(); b.f() === b");
|
||||
// A handler in the constructor does not catch what its return throws.
|
||||
throws("class A {} class B extends A { constructor() { try { return; } catch (e) {} } } new B();", "ReferenceError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extends_null_and_bad_heritage() {
|
||||
truth("class N extends null {} Object.getPrototypeOf(N.prototype) === null && Object.getPrototypeOf(N) === Function.prototype");
|
||||
truth("class N extends null { constructor() { return Object.create(N.prototype); } } new N() instanceof N");
|
||||
throws("class N extends null {} new N();", "TypeError");
|
||||
throws("class B extends 3 {}", "TypeError");
|
||||
throws("var f = () => {}; class B extends f {}", "TypeError");
|
||||
throws("function F() {} F.prototype = 3; class B extends F {}", "TypeError");
|
||||
throws("class B extends B {}", "ReferenceError");
|
||||
throws("class A { m() {} } class B extends A.prototype.m {}", "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_is_called_only_with_new() {
|
||||
throws("class A {} A();", "TypeError");
|
||||
throws("class A {} A.call({});", "TypeError");
|
||||
throws("class A { m() {} } new A.prototype.m();", "TypeError");
|
||||
throws("class A { static m() {} } new A.m();", "TypeError");
|
||||
throws("class A {} class B extends A {} B();", "TypeError");
|
||||
truth("class A {} var Bound = A.bind(null); new Bound() instanceof A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_bindings_follow_let_rules() {
|
||||
throws("new A(); class A {}", "ReferenceError");
|
||||
truth("class A {} { class A { m() { return 2; } } } typeof A.prototype.m === 'undefined'");
|
||||
throws("class A { m() { A = 1; } } new A().m();", "TypeError");
|
||||
// The inner name is initialized only after every method is defined (section 14.5.14, steps
|
||||
// 21 and 23), so a computed key that reads it is a `ReferenceError`.
|
||||
throws("class A { [A]() {} }", "ReferenceError");
|
||||
throws("var C = class D { static [D]() {} };", "ReferenceError");
|
||||
truth("class A {} A = 1; A === 1");
|
||||
syntax("class A {} class A {}");
|
||||
syntax("if (1) class A {}");
|
||||
syntax("class {}");
|
||||
syntax("class A { constructor() {} constructor() {} }");
|
||||
syntax("class A { get constructor() {} }");
|
||||
syntax("class A { *g() {} }");
|
||||
syntax("class A { m() { super(); } }");
|
||||
syntax("class A extends Object { m() { super(); } }");
|
||||
syntax("function f() { super.x; }");
|
||||
syntax("super.x");
|
||||
syntax("new.target");
|
||||
syntax("class A { constructor() { var o = { f: function () { super.x; } }; } }");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_target_names_the_constructor_new_was_applied_to() {
|
||||
truth("function F() { return new.target; } new F() === F && F() === undefined");
|
||||
truth("function F() { return (() => new.target)(); } new F() === F");
|
||||
truth("function F() { this.t = new.target; } var B = F.bind(null); new B().t === F");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
let e = Realm::with_options(es_options(), Limits { frames: 500, ..Limits::default() }).run(src).unwrap_err();
|
||||
assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}");
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 50_000, ..Limits::default() });
|
||||
let e = realm.run("class A { constructor() { new B(); } } class B extends A {} new B();").unwrap_err();
|
||||
assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classes_survive_collections_while_they_are_made() {
|
||||
let src = "var total = 0; for (var i = 0; i < 200; i++) { \
|
||||
class A { constructor(x) { this.x = x; } m() { return this.x; } static s() { return 1; } get g() { return 1; } } \
|
||||
class B extends A { constructor() { super(1); } m() { return super.m() + 1; } } \
|
||||
total += new B().m() + B.s() + new B().g; } total";
|
||||
let mut completed = 0;
|
||||
for kib in (16..400).step_by(4) {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: kib << 10, ..Limits::default() });
|
||||
match realm.run(src) {
|
||||
Ok(v) => {
|
||||
assert_eq!(v, JsValue::Number(800.0), "{kib} KiB");
|
||||
completed += 1;
|
||||
}
|
||||
Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{kib} KiB: {e:?}"),
|
||||
}
|
||||
}
|
||||
assert!(completed > 0);
|
||||
}
|
||||
|
||||
// ---- the language mode ----
|
||||
|
||||
#[test]
|
||||
fn without_the_option_the_new_forms_are_syntax_errors() {
|
||||
for src in ["let x = 1; x", "const c = 1;", "var f = x => x;", "`t`", "function f(a = 1) {}", "function f(...r) {}", "f(...a)", "[...a]"] {
|
||||
for src in [
|
||||
"let x = 1; x",
|
||||
"const c = 1;",
|
||||
"var f = x => x;",
|
||||
"`t`",
|
||||
"function f(a = 1) {}",
|
||||
"function f(...r) {}",
|
||||
"f(...a)",
|
||||
"[...a]",
|
||||
"class A {}",
|
||||
"var C = class {};",
|
||||
"function F() { return new.target; }",
|
||||
] {
|
||||
let r = Realm::new().run(src);
|
||||
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
|
||||
let r = Realm::with_options(Options { e4x: true, ..Options::default() }, Limits::default()).run(src);
|
||||
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
|
||||
}
|
||||
// `let` stays a name outside strict mode code.
|
||||
assert_eq!(Realm::new().run("var let = 1; let"), Ok(JsValue::Number(1.0)));
|
||||
@@ -472,6 +673,13 @@ const FRAGMENTS: &[&str] = &[
|
||||
"case ",
|
||||
"default:",
|
||||
"break;",
|
||||
"class ",
|
||||
" extends ",
|
||||
"super",
|
||||
"static ",
|
||||
"get ",
|
||||
"constructor",
|
||||
"new.target",
|
||||
];
|
||||
|
||||
proptest! {
|
||||
|
||||
+95
-65
@@ -44,11 +44,12 @@ pub(crate) enum Abrupt {
|
||||
|
||||
pub(crate) type JsResult<T> = Result<T, Abrupt>;
|
||||
|
||||
/// The binding that holds an arrow function's `this` in the environment it closes over. It starts
|
||||
/// with a NUL, which no identifier holds.
|
||||
const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73];
|
||||
/// The binding that holds an arrow function's `this` in the environment it closes over, and a
|
||||
/// derived class constructor's `this` in its function environment. It starts with a NUL, which no
|
||||
/// identifier holds.
|
||||
pub(crate) const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73];
|
||||
|
||||
fn internal<T>(message: &str) -> JsResult<T> {
|
||||
pub(crate) fn internal<T>(message: &str) -> JsResult<T> {
|
||||
Err(Abrupt::Internal(message.into()))
|
||||
}
|
||||
|
||||
@@ -177,10 +178,15 @@ pub(crate) struct Frame {
|
||||
pub(crate) var_env: EnvId,
|
||||
/// `with` and catch environments entered and not yet left.
|
||||
env_depth: u32,
|
||||
this: Value,
|
||||
pub(crate) this: Value,
|
||||
callee: Option<ObjId>,
|
||||
/// The object `new` made, returned unless the function returns an object.
|
||||
construct: Option<ObjId>,
|
||||
/// `new.target` of a function that was constructed.
|
||||
pub(crate) new_target: Option<ObjId>,
|
||||
/// The environment of a derived class constructor's `this`, function object and
|
||||
/// `new.target`, which `super(…)` reads.
|
||||
pub(crate) this_env: Option<EnvId>,
|
||||
completion: Value,
|
||||
/// Returning from this frame returns from the Rust call that pushed it.
|
||||
boundary: bool,
|
||||
@@ -422,14 +428,14 @@ pub(crate) fn random_seed_from(os: Result<u64, getrandom::Error>) -> u64 {
|
||||
}
|
||||
|
||||
/// The estimated bytes of a binding or property named by `len` code units.
|
||||
fn binding_bytes(len: usize) -> usize {
|
||||
pub(crate) fn binding_bytes(len: usize) -> usize {
|
||||
PROP_BYTES + string_bytes(len)
|
||||
}
|
||||
|
||||
/// At least the bytes that a function object made from `code` adds to the heap: the function,
|
||||
/// its prototype object, their properties and the environment holding a function expression's
|
||||
/// own name.
|
||||
fn closure_bytes(code: &Code) -> usize {
|
||||
pub(crate) fn closure_bytes(code: &Code) -> usize {
|
||||
let props = if code.strict { 5 } else { 3 };
|
||||
let named = code.self_name.as_ref().map_or(0, |n| ENV_BYTES + binding_bytes(n.len()));
|
||||
2 * OBJECT_BYTES + props * binding_bytes("constructor".len()) + named
|
||||
@@ -445,13 +451,15 @@ fn declaration_bytes(code: &Code) -> usize {
|
||||
code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len())))
|
||||
}
|
||||
|
||||
/// A call to a function written in JavaScript, ready to enter.
|
||||
struct Entry {
|
||||
callee: ObjId,
|
||||
code: Rc<Code>,
|
||||
env: EnvId,
|
||||
this: Value,
|
||||
args: Vec<Value>,
|
||||
/// A call to a function written in JavaScript, ready to enter; `new_target` is set when it is
|
||||
/// constructed.
|
||||
pub(crate) struct Entry {
|
||||
pub(crate) callee: ObjId,
|
||||
pub(crate) code: Rc<Code>,
|
||||
pub(crate) env: EnvId,
|
||||
pub(crate) this: Value,
|
||||
pub(crate) args: Vec<Value>,
|
||||
pub(crate) new_target: Option<ObjId>,
|
||||
}
|
||||
|
||||
/// What a call resolved to.
|
||||
@@ -627,7 +635,7 @@ impl Interp {
|
||||
self.frames.last_mut().ok_or_else(|| Abrupt::Internal("no frame".into()))
|
||||
}
|
||||
|
||||
fn base(&self) -> usize {
|
||||
pub(crate) fn base(&self) -> usize {
|
||||
self.frames.last().map_or(0, |f| f.base)
|
||||
}
|
||||
|
||||
@@ -783,7 +791,8 @@ impl Interp {
|
||||
for f in &self.frames {
|
||||
roots.values.push(&f.this);
|
||||
roots.values.push(&f.completion);
|
||||
roots.objects.extend(f.callee.iter().chain(f.construct.iter()));
|
||||
roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()));
|
||||
roots.envs.extend(f.this_env);
|
||||
roots.envs.push(f.env);
|
||||
roots.envs.push(f.var_env);
|
||||
roots.codes.push(&f.code);
|
||||
@@ -940,7 +949,21 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
fn return_value(&mut self, v: Value) -> JsResult<Option<Value>> {
|
||||
fn return_value(&mut self, mut v: Value) -> JsResult<Option<Value>> {
|
||||
if let Some(env) = self.frames.last().filter(|f| f.code.derived).and_then(|f| f.this_env) {
|
||||
match self.derived_result(env, v) {
|
||||
Ok(result) => v = result,
|
||||
Err(e) => {
|
||||
// The error is thrown as the frame returns: from its last instruction, outside
|
||||
// every handler of its code, and reported at the return.
|
||||
self.note_site();
|
||||
if let Some(f) = self.frames.last_mut() {
|
||||
f.pc = f.code.ops.len();
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(frame) = self.frames.pop() else { return internal("return without a frame") };
|
||||
self.stack.truncate(frame.base);
|
||||
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
|
||||
@@ -961,7 +984,7 @@ impl Interp {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn name(&self, i: u32) -> JsResult<Key> {
|
||||
pub(crate) fn name(&self, i: u32) -> JsResult<Key> {
|
||||
self.frame()?.code.names.get(i as usize).cloned().ok_or_else(|| Abrupt::Internal("name out of range".into()))
|
||||
}
|
||||
|
||||
@@ -996,7 +1019,7 @@ impl Interp {
|
||||
self.push(s.map_or(Value::Undefined, Value::String))
|
||||
}
|
||||
Op::This => {
|
||||
let this = self.frame()?.this.clone();
|
||||
let this = self.this_value()?;
|
||||
self.push(this)
|
||||
}
|
||||
Op::Pop => self.pop().map(drop),
|
||||
@@ -1094,6 +1117,27 @@ impl Interp {
|
||||
self.replace(1, Value::String(s))
|
||||
}
|
||||
Op::TemplateObject(i) => self.op_template_object(i),
|
||||
Op::Pick(n) => {
|
||||
let v = self.peek(n as usize)?;
|
||||
self.push(v)
|
||||
}
|
||||
Op::ClassStart { ctor, heritage } => self.op_class_start(ctor, heritage),
|
||||
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::SuperRef => self.op_super_ref(),
|
||||
Op::SuperGet => self.op_super_get(false),
|
||||
Op::SuperGetThis => self.op_super_get(true),
|
||||
Op::SuperSet => self.op_super_set(),
|
||||
Op::SuperDup => self.op_dup(3),
|
||||
Op::SuperInc { prefix, dec } => self.op_super_inc(prefix, dec),
|
||||
Op::SuperCtor => self.op_super_ctor(),
|
||||
Op::SuperCall(n) => self.op_super_call(n),
|
||||
Op::SuperCallSpread => {
|
||||
let n = self.unpack_args()?;
|
||||
self.op_super_call(n)
|
||||
}
|
||||
Op::BindThis => self.op_bind_this(),
|
||||
Op::NewTarget => self.op_new_target(),
|
||||
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
|
||||
}
|
||||
}
|
||||
@@ -1197,7 +1241,7 @@ impl Interp {
|
||||
Ok(Resolved::Unresolved)
|
||||
}
|
||||
|
||||
fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult<Value> {
|
||||
pub(crate) fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult<Value> {
|
||||
match self.heap.env(env) {
|
||||
Some(Env::Decl { bindings, .. }) => Ok(bindings.get(name).map_or(Value::Undefined, |b| b.value.clone())),
|
||||
_ => internal("not a declarative environment"),
|
||||
@@ -1210,7 +1254,7 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The binding `name` of the declarative environment `env` is in its temporal dead zone.
|
||||
fn uninitialized(&self, env: EnvId, name: &[u16]) -> bool {
|
||||
pub(crate) fn uninitialized(&self, env: EnvId, name: &[u16]) -> bool {
|
||||
matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
|
||||
}
|
||||
|
||||
@@ -2067,10 +2111,13 @@ impl Interp {
|
||||
fn op_closure(&mut self, i: u32) -> JsResult<()> {
|
||||
let frame = self.frame()?;
|
||||
let (env, this) = (frame.env, frame.this.clone());
|
||||
// In an arrow function or a derived class constructor, `this` is already a binding of the
|
||||
// environment chain, which the new function reads as it is when it runs.
|
||||
let this_bound = frame.code.arrow || frame.code.derived;
|
||||
let Some(code) = frame.code.functions.get(i as usize).cloned() else { return internal("function out of range") };
|
||||
// An arrow function keeps the `this` of the code it is made in (ECMA-262 2015 section
|
||||
// 14.2.16), in an environment of its own that only the call reads.
|
||||
let env = if code.arrow && code.uses_this {
|
||||
let env = if code.arrow && code.uses_this && !this_bound {
|
||||
self.reserve_heap(ENV_BYTES + binding_bytes(ARROW_THIS.len()))?;
|
||||
let mut bindings = PropMap::default();
|
||||
bindings.insert(Rc::from(ARROW_THIS), Binding::new(this, false, false));
|
||||
@@ -2092,12 +2139,13 @@ impl Interp {
|
||||
let proto = self.intrinsics.function_proto;
|
||||
let length = code.length;
|
||||
let strict = code.strict;
|
||||
let arrow = code.arrow;
|
||||
// An arrow function or a class method has no `prototype` and cannot be constructed
|
||||
// (sections 14.2.16 and 14.3.8); a class constructor gets its `prototype` from the class.
|
||||
let plain = !(code.arrow || code.method || code.class_ctor);
|
||||
let self_name = code.self_name.clone();
|
||||
let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto)));
|
||||
self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?;
|
||||
// An arrow function has no `prototype` and cannot be constructed (section 14.2.16).
|
||||
if arrow {
|
||||
if !plain {
|
||||
return Ok(f);
|
||||
}
|
||||
let p = self.new_object();
|
||||
@@ -2115,7 +2163,7 @@ impl Interp {
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
fn env_insert(&mut self, env: EnvId, name: Key, b: Binding) -> JsResult<()> {
|
||||
pub(crate) fn env_insert(&mut self, env: EnvId, name: Key, b: Binding) -> JsResult<()> {
|
||||
let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) else { return internal("not a declarative environment") };
|
||||
let new = !bindings.contains(&name);
|
||||
let name_len = name.len();
|
||||
@@ -2535,7 +2583,7 @@ impl Interp {
|
||||
v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Function(_)))
|
||||
}
|
||||
|
||||
fn func_of(&self, v: &Value) -> Option<Func> {
|
||||
pub(crate) fn func_of(&self, v: &Value) -> Option<Func> {
|
||||
match &self.heap.object(v.as_object()?)?.class {
|
||||
Class::Function(f) => Some(f.clone()),
|
||||
_ => None,
|
||||
@@ -2548,9 +2596,12 @@ impl Interp {
|
||||
loop {
|
||||
let Some(func) = self.func_of(&f) else { return Err(self.type_error("the value is not a function")) };
|
||||
match func {
|
||||
Func::Closure { code, .. } if code.class_ctor => {
|
||||
return Err(self.type_error("a class constructor cannot be called without 'new'"));
|
||||
}
|
||||
Func::Closure { code, env } => {
|
||||
let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?;
|
||||
return Ok(Prepared::Closure(Entry { callee, code, env, this, args }));
|
||||
return Ok(Prepared::Closure(Entry { callee, code, env, this, args, new_target: None }));
|
||||
}
|
||||
Func::Native { kind: NativeKind::Call, .. } => {
|
||||
self.use_fuel()?;
|
||||
@@ -2681,52 +2732,26 @@ impl Interp {
|
||||
let n = argc as usize;
|
||||
let start =
|
||||
self.stack.len().checked_sub(n + 1).filter(|&s| s >= self.base()).ok_or_else(|| Abrupt::Internal("new below the stack".into()))?;
|
||||
let mut f = self.stack.get(start).cloned().unwrap_or(Value::Undefined);
|
||||
let mut args: Vec<Value> = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default();
|
||||
// A bound function constructs its target with its arguments first (section 15.3.4.5.2);
|
||||
// the bound function on the stack keeps them reachable.
|
||||
while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) {
|
||||
self.use_fuel()?;
|
||||
let mut all = bound_args.to_vec();
|
||||
all.append(&mut args);
|
||||
args = all;
|
||||
f = Value::Object(target);
|
||||
}
|
||||
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, env }) => {
|
||||
let Some(callee) = f.as_object() else { return internal("callee is not an object") };
|
||||
let proto = match self.get_from(callee, &key("prototype"), &f)? {
|
||||
Value::Object(p) => p,
|
||||
_ => self.intrinsics.object_proto,
|
||||
};
|
||||
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 }, Some(obj), false)
|
||||
}
|
||||
Some(Func::Native { f: native, constructor: true, .. }) => {
|
||||
let held = self.held_bytes;
|
||||
let r = native(self, Value::Undefined, &args, true);
|
||||
self.held_bytes = held;
|
||||
let v = r?;
|
||||
self.stack.truncate(start);
|
||||
self.push(v)
|
||||
}
|
||||
_ => Err(self.type_error("the value is not a constructor")),
|
||||
}
|
||||
let f = self.stack.get(start).cloned().unwrap_or(Value::Undefined);
|
||||
let args: Vec<Value> = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default();
|
||||
self.construct(start, f, args, None)
|
||||
}
|
||||
|
||||
/// Pushes a frame for a call to a function written in JavaScript, its operands already off
|
||||
/// the stack.
|
||||
fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let Entry { callee, code, env, this, args } = entry;
|
||||
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let Entry { callee, code, env, this, args, new_target } = entry;
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
let params = code.params.iter().fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
|
||||
let arguments =
|
||||
if code.uses_arguments { OBJECT_BYTES.saturating_add(args.len().saturating_add(4).saturating_mul(binding_bytes(10))) } else { 0 };
|
||||
let need = declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(params).saturating_add(arguments);
|
||||
let need = declaration_bytes(&code)
|
||||
.saturating_add(ENV_BYTES)
|
||||
.saturating_add(params)
|
||||
.saturating_add(arguments)
|
||||
.saturating_add(crate::class_ops::hidden_bytes(&code));
|
||||
if self.heap.bytes.saturating_add(need) > self.limits.heap_bytes {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(callee));
|
||||
@@ -2738,7 +2763,7 @@ impl Interp {
|
||||
reserved?;
|
||||
}
|
||||
let this = if code.arrow {
|
||||
if code.uses_this { self.binding_value(env, ARROW_THIS)? } else { Value::Undefined }
|
||||
if code.uses_this { self.arrow_this(env) } else { Value::Undefined }
|
||||
} else if code.strict {
|
||||
this
|
||||
} else {
|
||||
@@ -2749,6 +2774,7 @@ impl Interp {
|
||||
}
|
||||
};
|
||||
let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?;
|
||||
let this_env = self.function_bindings(&code, var_env, callee, new_target)?;
|
||||
let base = self.stack.len();
|
||||
self.frames.push(Frame {
|
||||
code,
|
||||
@@ -2760,6 +2786,8 @@ impl Interp {
|
||||
this,
|
||||
callee: Some(callee),
|
||||
construct,
|
||||
new_target,
|
||||
this_env,
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
});
|
||||
@@ -3173,6 +3201,8 @@ impl Interp {
|
||||
this,
|
||||
callee: None,
|
||||
construct: None,
|
||||
new_target: None,
|
||||
this_env: None,
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
});
|
||||
|
||||
@@ -983,6 +983,10 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
arrow: false,
|
||||
uses_this: false,
|
||||
param_init: false,
|
||||
class_ctor: false,
|
||||
derived: false,
|
||||
method: false,
|
||||
uses_new_target: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ pub mod ast;
|
||||
mod builtins;
|
||||
mod bytecode;
|
||||
mod chars;
|
||||
mod class_ops;
|
||||
mod compiler;
|
||||
mod date_builtins;
|
||||
mod error;
|
||||
@@ -85,8 +86,9 @@ mod xml_builtins;
|
||||
mod xpath;
|
||||
|
||||
pub use ast::{
|
||||
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name, Program,
|
||||
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
AssignOp, Ast, BinaryOp, CatchClause, ClassDef, ClassElement, ClassKey, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind,
|
||||
LexKind, LogicalOp, MethodKind, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp,
|
||||
VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
|
||||
+242
-11
@@ -13,8 +13,8 @@ use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::LineTable;
|
||||
use crate::ast::{
|
||||
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LexKind, LogicalOp, Name, Program, Property,
|
||||
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl,
|
||||
AssignOp, Ast, BinaryOp, CatchClause, ClassDef, ClassElement, ClassKey, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LexKind,
|
||||
LogicalOp, MethodKind, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl,
|
||||
};
|
||||
use crate::error::{SyntaxError, TOO_DEEP};
|
||||
use crate::lexer::{Goal, Lexer};
|
||||
@@ -56,6 +56,18 @@ struct Scope {
|
||||
function: bool,
|
||||
}
|
||||
|
||||
/// What `super` and `new.target` may do where the parser is (ECMA-262 2015 sections 12.3.5.1,
|
||||
/// 12.3.8.1, 14.1.2, 14.5.1 and 15.1.1): set for each function body and kept by arrow functions.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct SuperRules {
|
||||
/// `super.property` and `super[index]`: in a class's methods, accessors and constructor.
|
||||
property: bool,
|
||||
/// `super(arguments)`: in a derived class's constructor.
|
||||
call: bool,
|
||||
/// `new.target`: in any function other than an arrow function at the top of a script.
|
||||
new_target: bool,
|
||||
}
|
||||
|
||||
/// The parameters of a function as they are read: plain names, each name's default value, and a
|
||||
/// rest parameter.
|
||||
type Params = (Vec<Name>, Vec<Option<ExprId>>, Option<Name>);
|
||||
@@ -101,6 +113,8 @@ pub(crate) struct Parser<'s> {
|
||||
es2015: bool,
|
||||
/// The scopes open around the current token, outermost first (only with `es2015`).
|
||||
scopes: Vec<Scope>,
|
||||
/// What `super` and `new.target` may do in the function being read.
|
||||
supers: SuperRules,
|
||||
}
|
||||
|
||||
impl<'s> Parser<'s> {
|
||||
@@ -125,6 +139,7 @@ impl<'s> Parser<'s> {
|
||||
e4x: options.e4x,
|
||||
es2015: options.es2015,
|
||||
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
supers: SuperRules::default(),
|
||||
};
|
||||
parser.tok = parser.next_significant()?;
|
||||
Ok(parser)
|
||||
@@ -467,6 +482,17 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
return Ok(id);
|
||||
}
|
||||
if self.es2015 && self.at_keyword(Keyword::Class) {
|
||||
let start = self.tok.span;
|
||||
self.enter()?;
|
||||
let class = self.parse_class(true);
|
||||
self.leave();
|
||||
let class = class?;
|
||||
if let Some(name) = &class.name {
|
||||
self.declare_lexical(name, false)?;
|
||||
}
|
||||
return Ok(self.ast.push_stmt(Stmt::Class(Box::new(class)), self.span_from(start)));
|
||||
}
|
||||
if let Some(kind) = self.at_lexical_declaration() {
|
||||
let start = self.bump()?.span;
|
||||
self.enter()?;
|
||||
@@ -557,6 +583,9 @@ impl<'s> Parser<'s> {
|
||||
Ok(self.ast.push_stmt(Stmt::Debugger, self.span_from(start)))
|
||||
}
|
||||
Keyword::Default if self.at_default_xml_namespace() => self.parse_default_xml_namespace(start),
|
||||
// A class declaration stands only in a statement list, and an expression statement
|
||||
// cannot start with `class` (ECMA-262 2015 sections 13 and 13.5).
|
||||
Keyword::Class if self.es2015 => Err(self.error_at_token(&self.tok, "a class declaration cannot stand here; put it in a block")),
|
||||
_ => {
|
||||
let expr = self.parse_expression(false)?;
|
||||
self.semicolon()?;
|
||||
@@ -979,13 +1008,22 @@ impl<'s> Parser<'s> {
|
||||
|
||||
/// The parameters and body of a function, from `(`.
|
||||
fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result<crate::ast::FunctionId> {
|
||||
self.parse_function_with(kind, name, start, false)
|
||||
}
|
||||
|
||||
/// The parameters and body of a function, from `(`; `home` for one defined in a class body,
|
||||
/// where `super.property` may stand.
|
||||
fn parse_function_with(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, home: bool) -> Result<crate::ast::FunctionId> {
|
||||
self.enter()?;
|
||||
let result = self.function_rest(kind, name, start);
|
||||
let rules = SuperRules { property: home, call: kind == FunctionKind::DerivedConstructor, new_target: true };
|
||||
let outer = std::mem::replace(&mut self.supers, rules);
|
||||
let result = self.function_rest(kind, name, start, home);
|
||||
self.supers = outer;
|
||||
self.leave();
|
||||
result
|
||||
}
|
||||
|
||||
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result<crate::ast::FunctionId> {
|
||||
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, home: bool) -> Result<crate::ast::FunctionId> {
|
||||
self.expect(Punct::LParen)?;
|
||||
let mut params: Vec<Name> = Vec::new();
|
||||
let mut defaults: Vec<Option<ExprId>> = Vec::new();
|
||||
@@ -1034,7 +1072,7 @@ impl<'s> Parser<'s> {
|
||||
self.ctx = outer;
|
||||
let body = body?;
|
||||
self.expect(Punct::RBrace)?;
|
||||
let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) };
|
||||
let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start), home };
|
||||
self.check_params(&function, use_strict)?;
|
||||
Ok(self.ast.push_function(function))
|
||||
}
|
||||
@@ -1066,7 +1104,8 @@ impl<'s> Parser<'s> {
|
||||
self.expect(Punct::RBrace)?;
|
||||
}
|
||||
let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults };
|
||||
let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) };
|
||||
let function =
|
||||
Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start), home: false };
|
||||
self.check_params(&function, use_strict)?;
|
||||
let id = self.ast.push_function(function);
|
||||
Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start)))
|
||||
@@ -1224,7 +1263,7 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_)) => Ok(()),
|
||||
Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_) | Expr::SuperMember(_) | Expr::SuperIndex(_)) => Ok(()),
|
||||
Some(Expr::Call { .. }) if !self.ctx.strict => Ok(()),
|
||||
_ => Err(self.error_at_offset(self.ast.expr_span(expr).start, message)),
|
||||
}
|
||||
@@ -1318,10 +1357,16 @@ impl<'s> Parser<'s> {
|
||||
/// after its callee, and a `new` left without one constructs with no arguments.
|
||||
fn parse_left_hand_side(&mut self) -> Result<ExprId> {
|
||||
let mut news = Vec::new();
|
||||
while self.at_keyword(Keyword::New) {
|
||||
while self.at_keyword(Keyword::New) && !self.at_new_target() {
|
||||
news.push(self.bump()?.span);
|
||||
}
|
||||
let mut expr = self.parse_primary()?;
|
||||
let mut expr = if self.es2015 && self.at_keyword(Keyword::Super) {
|
||||
self.parse_super(news.is_empty())?
|
||||
} else if self.at_new_target() {
|
||||
self.parse_new_target()?
|
||||
} else {
|
||||
self.parse_primary()?
|
||||
};
|
||||
loop {
|
||||
match &self.tok.kind {
|
||||
TokenKind::Punct(Punct::DotDot) => expr = self.parse_xml_descendants(expr)?,
|
||||
@@ -1368,6 +1413,66 @@ impl<'s> Parser<'s> {
|
||||
Ok(expr)
|
||||
}
|
||||
|
||||
/// The current `new` starts `new.target` (with [`crate::Options::es2015`]).
|
||||
fn at_new_target(&self) -> bool {
|
||||
self.es2015 && self.at_keyword(Keyword::New) && self.peek().is_some_and(|t| t.is_punct(Punct::Dot))
|
||||
}
|
||||
|
||||
/// `new.target`, in a function (ECMA-262 2015 sections 12.3.8 and 15.1.1).
|
||||
fn parse_new_target(&mut self) -> Result<ExprId> {
|
||||
let new = self.bump()?;
|
||||
self.expect(Punct::Dot)?;
|
||||
if self.tok.ident() != Some("target") || self.tok.escaped {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected 'target' after 'new.' but found {}", describe(&self.tok))));
|
||||
}
|
||||
self.bump()?;
|
||||
if !self.supers.new_target {
|
||||
return Err(self.error_at_token(&new, "'new.target' is allowed only in functions"));
|
||||
}
|
||||
Ok(self.ast.push_expr(Expr::NewTarget, self.span_from(new.span)))
|
||||
}
|
||||
|
||||
/// `super(…)`, `super.name` or `super[…]`, where the function being read allows it
|
||||
/// (ECMA-262 2015 section 12.3.5); `call_allowed` is false after `new`.
|
||||
fn parse_super(&mut self, call_allowed: bool) -> Result<ExprId> {
|
||||
self.enter()?;
|
||||
let result = self.super_expr(call_allowed);
|
||||
self.leave();
|
||||
result
|
||||
}
|
||||
|
||||
fn super_expr(&mut self, call_allowed: bool) -> Result<ExprId> {
|
||||
let word = self.bump()?;
|
||||
let start = word.span;
|
||||
match &self.tok.kind {
|
||||
TokenKind::Punct(Punct::LParen) if call_allowed => {
|
||||
if !self.supers.call {
|
||||
return Err(self.error_at_token(&word, "'super()' is allowed only in the constructor of a class with 'extends'"));
|
||||
}
|
||||
let args = self.parse_arguments()?;
|
||||
Ok(self.ast.push_expr(Expr::SuperCall(args), self.span_from(start)))
|
||||
}
|
||||
TokenKind::Punct(Punct::Dot | Punct::LBracket) if !self.supers.property => {
|
||||
Err(self.error_at_token(&word, "'super' properties are allowed only in the methods and constructor of a class"))
|
||||
}
|
||||
TokenKind::Punct(Punct::Dot) => {
|
||||
self.bump()?;
|
||||
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a property name but found {}", describe(&self.tok))));
|
||||
};
|
||||
let token = self.bump()?;
|
||||
Ok(self.ast.push_expr(Expr::SuperMember(Name { name, span: token.span }), self.span_from(start)))
|
||||
}
|
||||
TokenKind::Punct(Punct::LBracket) => {
|
||||
self.bump()?;
|
||||
let index = self.parse_expression(false)?;
|
||||
self.expect(Punct::RBracket)?;
|
||||
Ok(self.ast.push_expr(Expr::SuperIndex(index), self.span_from(start)))
|
||||
}
|
||||
_ => Err(self.error_at_token(&word, "'super' must be followed by an argument list or a property access")),
|
||||
}
|
||||
}
|
||||
|
||||
/// An element of an array literal or an argument list: an assignment expression, or with
|
||||
/// [`crate::Options::es2015`] a spread (`...expression`).
|
||||
fn parse_element(&mut self) -> Result<ExprId> {
|
||||
@@ -1409,6 +1514,10 @@ impl<'s> Parser<'s> {
|
||||
TokenKind::Keyword(Keyword::True) => Expr::Bool(true),
|
||||
TokenKind::Keyword(Keyword::False) => Expr::Bool(false),
|
||||
TokenKind::Keyword(Keyword::Function) => return self.parse_function_expression(),
|
||||
TokenKind::Keyword(Keyword::Class) if self.es2015 => {
|
||||
let class = self.parse_class(false)?;
|
||||
return Ok(self.ast.push_expr(Expr::Class(Box::new(class)), self.span_from(start)));
|
||||
}
|
||||
TokenKind::Ident(name) => {
|
||||
let name = name.clone();
|
||||
self.check_identifier(&self.tok, &name)?;
|
||||
@@ -1528,6 +1637,122 @@ impl<'s> Parser<'s> {
|
||||
Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start)))
|
||||
}
|
||||
|
||||
/// A class declaration (`declaration`, which needs a name) or expression, from `class`
|
||||
/// (ECMA-262 2015 section 14.5). All of it is strict mode code.
|
||||
fn parse_class(&mut self, declaration: bool) -> Result<ClassDef> {
|
||||
let outer = self.ctx.strict;
|
||||
self.ctx.strict = true;
|
||||
let result = self.class_rest(declaration);
|
||||
self.ctx.strict = outer;
|
||||
result
|
||||
}
|
||||
|
||||
fn class_rest(&mut self, declaration: bool) -> Result<ClassDef> {
|
||||
let start = self.expect_keyword(Keyword::Class)?.span;
|
||||
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.binding_identifier()?) } else { None };
|
||||
if declaration && name.is_none() {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a class name but found {}", describe(&self.tok))));
|
||||
}
|
||||
let heritage = if self.at_keyword(Keyword::Extends) {
|
||||
self.bump()?;
|
||||
Some(self.parse_left_hand_side()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.expect(Punct::LBrace)?;
|
||||
let mut constructor = None;
|
||||
let mut elements = Vec::new();
|
||||
while !self.at(Punct::RBrace) {
|
||||
if self.eat(Punct::Semicolon)? {
|
||||
continue;
|
||||
}
|
||||
if self.tok.kind == TokenKind::Eof {
|
||||
return Err(self.unexpected());
|
||||
}
|
||||
let at = self.tok.clone();
|
||||
match self.parse_class_element(heritage.is_some())? {
|
||||
Ok(element) => elements.push(element),
|
||||
Err(_) if constructor.is_some() => return Err(self.error_at_token(&at, "a class can have only one constructor")),
|
||||
Err(f) => constructor = Some(f),
|
||||
}
|
||||
}
|
||||
self.bump()?;
|
||||
let span = self.span_from(start);
|
||||
let constructor = match constructor {
|
||||
Some(f) => f,
|
||||
None => self.default_constructor(heritage.is_some(), span),
|
||||
};
|
||||
if let Some(f) = self.ast.functions.get_mut(constructor.0 as usize) {
|
||||
f.span = span;
|
||||
}
|
||||
Ok(ClassDef { name, heritage, constructor, elements, span })
|
||||
}
|
||||
|
||||
/// A method or accessor of a class body (`Ok`), or its constructor (`Err`). `derived`: the
|
||||
/// class has `extends`.
|
||||
fn parse_class_element(&mut self, derived: bool) -> Result<std::result::Result<ClassElement, crate::ast::FunctionId>> {
|
||||
let is_static = self.tok.ident() == Some("static") && !self.tok.escaped && self.peek().is_some_and(|t| !t.is_punct(Punct::LParen));
|
||||
if is_static {
|
||||
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"));
|
||||
}
|
||||
// `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)));
|
||||
if accessor.is_some() {
|
||||
self.bump()?;
|
||||
}
|
||||
let kind = accessor.unwrap_or(MethodKind::Method);
|
||||
let key = if self.eat(Punct::LBracket)? {
|
||||
let e = self.parse_assignment(false)?;
|
||||
self.expect(Punct::RBracket)?;
|
||||
ClassKey::Computed(e)
|
||||
} else {
|
||||
ClassKey::Fixed(self.parse_property_key()?.0)
|
||||
};
|
||||
let named = |word: &str| matches!(&key, ClassKey::Fixed(k) if k.to_utf16().iter().copied().eq(word.encode_utf16()));
|
||||
if !is_static && named("constructor") {
|
||||
if kind != MethodKind::Method {
|
||||
return Err(self.error_at_offset(start.start, "a class constructor cannot be a getter or a setter"));
|
||||
}
|
||||
let ctor = if derived { FunctionKind::DerivedConstructor } else { FunctionKind::ClassConstructor };
|
||||
return Ok(Err(self.parse_function_with(ctor, None, start, true)?));
|
||||
}
|
||||
if is_static && named("prototype") {
|
||||
return Err(self.error_at_offset(start.start, "a class cannot have a static method named 'prototype'"));
|
||||
}
|
||||
let fkind = match kind {
|
||||
MethodKind::Method => FunctionKind::Method,
|
||||
MethodKind::Get => FunctionKind::Getter,
|
||||
MethodKind::Set => FunctionKind::Setter,
|
||||
};
|
||||
let function = self.parse_function_with(fkind, None, start, true)?;
|
||||
Ok(Ok(ClassElement { key, is_static, kind, function }))
|
||||
}
|
||||
|
||||
/// The constructor of a class written without one (ECMA-262 2015 section 14.5.14, step 10):
|
||||
/// empty, or in a derived class `constructor(...args) { super(...args); }`, its rest parameter
|
||||
/// under a name no script can write.
|
||||
fn default_constructor(&mut self, derived: bool, span: Span) -> crate::ast::FunctionId {
|
||||
let (kind, rest, body) = if derived {
|
||||
let args = Name { name: "\u{0}args".into(), span };
|
||||
let ident = self.ast.push_expr(Expr::Ident(args.name.clone()), span);
|
||||
let spread = self.ast.push_expr(Expr::Spread(ident), span);
|
||||
let call = self.ast.push_expr(Expr::SuperCall(vec![spread]), span);
|
||||
(FunctionKind::DerivedConstructor, Some(args), vec![self.ast.push_stmt(Stmt::Expr(call), span)])
|
||||
} else {
|
||||
(FunctionKind::ClassConstructor, None, Vec::new())
|
||||
};
|
||||
self.ast.push_function(Function { kind, name: None, params: Vec::new(), defaults: Vec::new(), rest, body, strict: true, span, home: true })
|
||||
}
|
||||
|
||||
/// `[a, , b]`: elements, a comma with nothing before it leaving a hole.
|
||||
fn parse_array(&mut self) -> Result<ExprId> {
|
||||
let start = self.expect(Punct::LBracket)?.span;
|
||||
@@ -1575,7 +1800,8 @@ impl<'s> Parser<'s> {
|
||||
let word = self.bump()?;
|
||||
if property_key(&self.tok).is_some() {
|
||||
let (key, _) = self.parse_property_key()?;
|
||||
let function = self.parse_function_rest(kind, None, start)?;
|
||||
// With ES2015 an accessor is a method, whose home object is the literal's object.
|
||||
let function = self.parse_function_with(kind, None, start, self.es2015)?;
|
||||
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
|
||||
return Ok(Property { key, value, span: self.span_from(start) });
|
||||
}
|
||||
@@ -1586,8 +1812,13 @@ impl<'s> Parser<'s> {
|
||||
self.property_value(key, start)
|
||||
}
|
||||
|
||||
/// `: value` after a data property's name.
|
||||
/// `: value` after a data property's name, or with ES2015 the parameters and body of a
|
||||
/// method (`m() {…}`, ECMA-262 2015 section 14.3).
|
||||
fn property_value(&mut self, key: PropertyKey, start: Span) -> Result<Property> {
|
||||
if self.es2015 && self.at(Punct::LParen) {
|
||||
let function = self.parse_function_with(FunctionKind::Method, None, start, true)?;
|
||||
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
|
||||
}
|
||||
self.expect(Punct::Colon)?;
|
||||
let value = self.parse_assignment(false)?;
|
||||
Ok(Property { key, value: PropertyValue::Init(value), span: self.span_from(start) })
|
||||
|
||||
@@ -29,7 +29,8 @@
|
||||
//! or test file cannot be read, or when no ES5 test runs.
|
||||
//!
|
||||
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
|
||||
//! arrow functions, templates, default and rest parameters) without and with that option, and
|
||||
//! arrow functions, templates, default and rest parameters, classes, `super` and `new.target`)
|
||||
//! without and with that option, and
|
||||
//! prints both counts; its failures with the option go to `es2015-failures.txt`.
|
||||
//!
|
||||
//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every
|
||||
@@ -659,10 +660,15 @@ const ES2015_FOLDERS: &[&str] = &[
|
||||
"expressions/template-literal",
|
||||
"expressions/tagged-template",
|
||||
"rest-parameters",
|
||||
"statements/class",
|
||||
"expressions/class",
|
||||
"expressions/super",
|
||||
"expressions/new.target",
|
||||
];
|
||||
|
||||
/// The feature tags of the forms [`Options::es2015`] reads.
|
||||
const ES2015_FEATURES: &[&str] = &["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters"];
|
||||
const ES2015_FEATURES: &[&str] =
|
||||
&["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters", "class", "super", "new.target"];
|
||||
|
||||
#[test]
|
||||
fn es2015_subset_runs() {
|
||||
|
||||
+6
-3
@@ -2620,9 +2620,12 @@ not UTF-8. The language is ES5.1, except that identifiers take the characters Un
|
||||
`.js` (in any case) also reads these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and
|
||||
`const` with block scope and their temporal dead zone, a new `let` binding for each `for` loop iteration, function
|
||||
declarations scoped to their block, arrow functions, template literals and tagged templates, default and rest
|
||||
parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects
|
||||
with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own
|
||||
until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and
|
||||
parameters, spread in array literals, calls and `new`, classes with `extends`, `static` members, accessors and
|
||||
computed method names, `super` calls and properties, `new.target`, and methods in object literals. Spread reads
|
||||
arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any
|
||||
other value; that rule is VectorCraft's own until iterators are added. A class can extend a class, a function, `null`
|
||||
or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the
|
||||
error types; extending another built-in throws a `TypeError`, a rule that is VectorCraft's own. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and
|
||||
an engine that `#targetengine` keeps reads each run the way that run's script does. A
|
||||
`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the
|
||||
app through the global object `vc`, and writes to the Script Console and runs other files through `$`:
|
||||
|
||||
@@ -1079,7 +1079,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`.
|
||||
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
|
||||
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays, strings (by code point) and objects with a `length` property, by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs 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; extending another built-in throws a `TypeError`, 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,125 tests of these forms: with the option, all 554 negative parse runs and 1,527 of 1,633 other runs pass (537 and 43 without it); of the 106 failing runs, 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`.
|
||||
- `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`.
|
||||
|
||||
Reference in new issue
Block a user