Skip to content

Truly independent web browser

LibJS: Inline constructs of classes with instance fields

Andreas Kling02bf8b39a9e7
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 9b62562864d..e3635aeb7f2 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -1732,6 +1732,52 @@ impl<'a> GraphBuilder<'a> {
Ok(Some(Flow::Ended))
}
+ /// `BindThisFromSuperCall` in an inlined construct of a derived
+ /// constructor with fields or private methods, whose `this` is still
+ /// empty there (see `calls_super_once_before_returning()`): its slow
+ /// path, which runs in the published frames of the inlined calls, binds
+ /// `this` and initializes the instance elements. Its result is `this`
+ /// once it continues. Returns `None` for other constructors.
+ pub(super) fn try_build_bind_this_initializing_instance_elements(
+ &mut self,
+ instruction: &Instruction,
+ result: Operand,
+ ) -> Result<Option<Flow>, CompileFailure> {
+ if self
+ .function
+ .inline
+ .as_ref()
+ .and_then(|call| call.derived_construct)
+ .is_none()
+ || !self.function.executable.has_instance_elements
+ {
+ return Ok(None);
+ }
+ let this_register = Operand::from_raw(THIS_VALUE_REGISTER);
+ let this_value = self.read(this_register)?;
+ if self.graph.constant_value(this_value) != Some(value::EMPTY) {
+ return Err(CompileFailure::InvalidBytecode {
+ pc: self.function.pc,
+ reason: "super() of an inlined derived construct with this bound",
+ });
+ }
+ let invalid = CompileFailure::InvalidBytecode {
+ pc: self.function.pc,
+ reason: "BindThisFromSuperCall has no slow path call",
+ };
+ let info = super::handling::handling(OpCode::BindThisFromSuperCall)
+ .generic()
+ .ok_or(invalid)?;
+ // NB: The published frame of the derived constructor has the empty this value of the frame state, which the
+ // slow path binds.
+ let flow = self.try_build_slow_path_call(instruction, info)?.ok_or(invalid)?;
+ // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
+ // 9. Perform ? BindThisValue(thisER, result).
+ let result = self.read(result)?;
+ self.write(this_register, result)?;
+ Ok(Some(flow))
+ }
+
/// `BindThisFromSuperCall` in an inlined construct of a derived
/// constructor, whose `this` is still empty there (see
/// `calls_super_once_before_returning()`) and which has no fields.
@@ -1824,9 +1870,11 @@ impl<'a> GraphBuilder<'a> {
}
/// `this` of an inlined construct of `function`: the object its
- /// construct creates, an empty plain object of the prototype in its
- /// "prototype", which must still be the one it was at compile time.
- fn construct_this(&mut self, function: CellId, construct: &ConstructTarget) -> NodeId {
+ /// construct creates, a plain object of the prototype in its
+ /// "prototype", which must still be the one it was at compile time,
+ /// with the `fields` of the base constructor (see
+ /// `ExecutableSnapshot::literal_instance_fields`).
+ fn construct_this(&mut self, function: CellId, construct: &ConstructTarget, fields: &[(u32, u64)]) -> NodeId {
// 10.1.13 OrdinaryCreateFromConstructor ( constructor, intrinsicDefaultProto [ , internalSlotsList ] ), https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
let constructor = self.boxed_object(function);
let constructor = self.constant(constructor);
@@ -1839,15 +1887,24 @@ impl<'a> GraphBuilder<'a> {
);
self.load_constant_named(constructor, construct.prototype_offset, construct.prototype);
self.embed(construct.this_shape);
- self.emit(
+ let property_count = fields.iter().map(|(offset, _)| offset + 1).max().unwrap_or(0);
+ let this = self.emit(
Op::AllocateObject {
shape: construct.this_shape,
- property_count: 0,
- reserve: construct.reserve,
+ property_count,
+ reserve: construct.reserve.max(property_count),
},
Vec::new(),
Some(Repr::Tagged),
- )
+ );
+ // 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget
+ // 6.b. Let initializeResult be Completion(InitializeInstanceElements(thisArgument, F)).
+ // NB: The fields have literal values, so this cannot throw, and `this` has their shape already.
+ for &(offset, value) in fields {
+ let value = self.constant(value);
+ self.emit(Op::InitializeNamed { offset }, vec![this, value], None);
+ }
+ this
}
/// The value of `value` for an inlined call.
@@ -1982,7 +2039,10 @@ impl<'a> GraphBuilder<'a> {
}
let qualifies = match kind {
InlinedCallKind::Call => true,
- InlinedCallKind::Construct => returns_no_object(&callee_function),
+ InlinedCallKind::Construct => {
+ returns_no_object(&callee_function)
+ && (!callee_executable.has_instance_elements || callee_executable.literal_instance_fields.is_some())
+ }
InlinedCallKind::DerivedConstruct => calls_super_once_before_returning(&callee_function),
};
qualifies.then_some(InlinableCallee {
@@ -2088,9 +2148,11 @@ impl<'a> GraphBuilder<'a> {
}
// NB: super() creates `this` of a derived constructor.
let receiver = match &construct {
- Some(construct) if derived_construct.is_none() => {
- self.construct_this(new_target.unwrap_or(function.function), construct)
- }
+ Some(construct) if derived_construct.is_none() => self.construct_this(
+ new_target.unwrap_or(function.function),
+ construct,
+ callee_executable.literal_instance_fields.as_deref().unwrap_or_default(),
+ ),
_ => receiver,
};
// NB: Arguments forwarded from the frame are as many as when the
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 9b381a653a8..77b34382a66 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -1658,6 +1658,9 @@ impl<'a> GraphBuilder<'a> {
}
}
Instruction::BindThisFromSuperCall { result } => {
+ if let Some(flow) = self.try_build_bind_this_initializing_instance_elements(instruction, result)? {
+ return Ok(Some(flow));
+ }
if !self.try_build_bind_this_from_super_call(result)? {
return Ok(None);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index e84757fc34f..01af9a31eb4 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -144,6 +144,15 @@ pub struct ExecutableSnapshot {
/// constructs JIT code can inline (see `ConstructTarget`): what its
/// super() constructs with.
pub super_constructor: Option<SuperConstructTarget>,
+ /// Whether the function is a class constructor with instance fields or
+ /// private methods, which InitializeInstanceElements adds to `this`.
+ pub has_instance_elements: bool,
+ /// For a base constructor with instance elements among the inlining
+ /// candidates whose constructs JIT code can inline: the values its
+ /// fields give `this`, by property offset, in the order
+ /// InitializeInstanceElements defines them. `this` is created with the
+ /// shape it has after that (see `ConstructTarget::this_shape`).
+ pub literal_instance_fields: Option<Vec<(u32, u64)>>,
}
/// The global object and the global declarative environment of a realm, and
@@ -462,13 +471,15 @@ pub struct CallFeedbackSnapshot {
}
/// A constructor whose construct JIT code can inline: a base constructor
-/// without fields, whose function object (of `function_shape`) holds
-/// `prototype` as the data property at `prototype_offset`. Its construct
-/// creates `this` as an empty plain object of `this_shape`, whose prototype
-/// that is, and runs the body of the snapshot executable `executable`
-/// (with no function environment).
+/// without private methods whose fields have string or symbol names and
+/// literal initial values (see `ExecutableSnapshot::literal_instance_fields`)
+/// if any, whose function object (of `function_shape`) holds `prototype` as
+/// the data property at `prototype_offset`. Its construct creates `this` as
+/// a plain object of `this_shape`, an empty object shape with that prototype
+/// plus the fields, and runs the body of the snapshot executable
+/// `executable` (with no function environment).
///
-/// Or a derived constructor without fields whose super() constructs with
+/// Or a derived constructor whose super() constructs with
/// `super_constructor`. Its construct runs its body, and super() constructs
/// with its parent and the same new target, down to a base constructor,
/// which creates `this` as above.
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index f6b53738daa..568f54b67c4 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -49,6 +49,7 @@ use crate::runtime::array_constructor::ArrayConstructor;
use crate::runtime::array_prototype;
use crate::runtime::boolean_constructor::BooleanConstructor;
use crate::runtime::bound_function::BoundFunction;
+use crate::runtime::class_field_definition::{ClassElementName, ClassFieldInitializer};
use crate::runtime::ecmascript_function_object::as_ecmascript_function_object;
use crate::runtime::function_prototype::{self, FunctionPrototype};
use crate::runtime::map_prototype;
@@ -56,6 +57,7 @@ use crate::runtime::math_object;
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
use crate::runtime::object_constructor::ObjectConstructor;
use crate::runtime::object_prototype;
+use crate::runtime::property_attributes::DEFAULT_ATTRIBUTES;
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
use crate::runtime::realm_watchpoints;
@@ -119,8 +121,14 @@ struct SnapshotBuilder<'vm> {
/// For the derived constructors among the inlining candidates, by index: what their super() constructs with in
/// inlined constructs of them (see `ExecutableSnapshot::super_constructor`).
super_constructors: HashMap<u32, SuperConstructTarget>,
+ /// For the base constructors with fields among the inlining candidates, by index: the values of their fields (see
+ /// `ExecutableSnapshot::literal_instance_fields`).
+ literal_instance_fields: HashMap<u32, Vec<(u32, u64)>>,
}
+/// The values of literal fields, by property offset (see `ExecutableSnapshot::literal_instance_fields`).
+type LiteralFieldValues = Vec<(u32, u64)>;
+
/// The number of bytecode instructions of an executable, counted up to one past `limit`.
fn instruction_count(executable: &Executable, limit: u32) -> u32 {
let bytecode = executable.bytecode();
@@ -816,14 +824,18 @@ impl SnapshotBuilder<'_> {
}
/// Describes the single constructor of a construct site if JIT code can inline its construct: a base constructor
- /// without fields (whose construct only creates `this` before running its body), or a derived constructor without
- /// fields whose chain of [[Prototype]]s up to a base constructor are such constructors, with a function object of a
+ /// without fields (whose construct only creates `this` before running its body), or a derived constructor whose
+ /// chain of [[Prototype]]s up to such a base constructor are derived constructors, with a function object of a
/// shape that has its "prototype" as a data property holding an object.
fn construct_target(&mut self, target: Option<Gc<CellHeader>>, caller: &Entry) -> Option<ConstructTarget> {
let function = ecmascript_function(target)?;
+ // NB: The super() of an inlined derived constructor initializes its instance elements through the slow path of
+ // BindThisFromSuperCall.
let inlinable = |constructor: Gc<EcmascriptFunctionObject>| {
constructor.has_constructor()
- && !constructor.has_class_data()
+ && (constructor.constructor_kind() == ConstructorKind::Derived
+ || !constructor.has_class_data()
+ || constructor.private_methods_count() == 0)
&& !constructor.allocates_function_environment()
&& !constructor.contains_direct_call_to_eval()
&& constructor.realm() == Some(caller.realm)
@@ -887,6 +899,15 @@ impl SnapshotBuilder<'_> {
} else {
empty_shape.create_prototype_transition(self.vm, Some(prototype))
};
+ let base = chain
+ .get(chain.len() - 1)
+ .expect("the chain ends with a base constructor");
+ let (this_shape, literal_fields) = if base.has_class_data() {
+ let (shape, fields) = self.literal_instance_fields(base, this_shape)?;
+ (shape, Some(fields))
+ } else {
+ (this_shape, None)
+ };
let index = self.inlined_function_index(function, caller)?;
let mut indices = vec![index];
for level in 1..chain.len() {
@@ -894,9 +915,10 @@ impl SnapshotBuilder<'_> {
let parent = chain.get(level).expect("the level is in the chain");
indices.push(self.inlined_function_index(parent, &entry)?);
}
- let base = chain
- .get(chain.len() - 1)
- .expect("the chain ends with a base constructor");
+ if let Some(fields) = literal_fields {
+ self.literal_instance_fields
+ .insert(*indices.last().expect("the chain ends with a base constructor"), fields);
+ }
if chain.len() == 1 {
self.construct_this_shapes.insert(index, this_shape);
}
@@ -922,6 +944,49 @@ impl SnapshotBuilder<'_> {
})
}
+ /// The values InitializeInstanceElements gives `this` of the base constructor `constructor`, whose construct
+ /// creates it with `shape`, by property offset, if its instance elements are only fields with string or symbol
+ /// names whose initial values are no cells (from literals) or absent, and the shape `this` has after that.
+ fn literal_instance_fields(
+ &self,
+ constructor: Gc<EcmascriptFunctionObject>,
+ shape: Gc<Shape>,
+ ) -> Option<(Gc<Shape>, LiteralFieldValues)> {
+ if constructor.private_methods_count() != 0 {
+ return None;
+ }
+ let mut shape = shape;
+ let mut values = Vec::new();
+ for index in 0..constructor.fields_count() {
+ let field = constructor.field(index);
+ let ClassElementName::PropertyKey(key) = &field.name else {
+ return None;
+ };
+ // NB: Fields with index names go to the indexed elements.
+ if key.is_number() {
+ return None;
+ }
+ let value = match field.initializer {
+ ClassFieldInitializer::Value(value) if !value.is_cell() => value,
+ ClassFieldInitializer::Empty => Value::UNDEFINED,
+ _ => return None,
+ };
+ // 7.3.33 DefineField ( receiver, fieldRecord ), https://tc39.es/ecma262/#sec-definefield
+ // 6.b. Perform ? CreateDataPropertyOrThrow(receiver, fieldName, initValue).
+ // NB: `this` is a new ordinary object, whose only properties are the fields defined before, so this adds the
+ // property or sets the value of an earlier field of the same name, like the interpreter does.
+ let offset = match shape.lookup(key) {
+ Some(metadata) => metadata.offset,
+ None => {
+ shape = shape.create_put_transition(self.vm, key, DEFAULT_ATTRIBUTES);
+ shape.property_count() - 1
+ }
+ };
+ values.push((offset, value.0));
+ }
+ Some((shape, values))
+ }
+
/// The environment of direct calls of `function`: Some(None) if they need none of their own, and Some(index of
/// the template) if JIT code can allocate it. Frames of functions without one of their own have the function's
/// [[Environment]], and those of arrow functions resolve `this` through it.
@@ -1093,6 +1158,13 @@ impl SnapshotBuilder<'_> {
.and_then(|function| self.indices.get(&function))
.and_then(|index| self.super_constructors.get(index))
.copied();
+ let literal_instance_fields = entry
+ .function
+ .and_then(|function| self.indices.get(&function))
+ .and_then(|index| self.literal_instance_fields.get(index))
+ .cloned();
+ let has_instance_elements =
+ matches!(entry.function, Some(InlinedFunction::Ecmascript(function)) if function.has_class_data());
let property_caches = executable
.property_lookup_caches()
.iter()
@@ -1192,6 +1264,8 @@ impl SnapshotBuilder<'_> {
globals: (!matches!(entry.function, Some(InlinedFunction::Builtin(_))))
.then(|| self.globals(executable, realm)),
super_constructor,
+ has_instance_elements,
+ literal_instance_fields,
// NB: Only the compiled function's own code creates bindings by name.
identifiers: if entry.function.is_none() {
executable
@@ -1382,6 +1456,7 @@ pub fn capture_snapshot<'d>(
lexical_environment_templates: Vec::new(),
construct_this_shapes: HashMap::new(),
super_constructors: HashMap::new(),
+ literal_instance_fields: HashMap::new(),
};
builder.closure_templates =
closure_template_snapshots(closure_templates.into_inner(), |sample| builder.cell(sample), defer_gc);
diff --git a/Tests/LibJS/JIT/ir/inlining-constructs-with-fields.js b/Tests/LibJS/JIT/ir/inlining-constructs-with-fields.js
new file mode 100644
index 00000000000..e586295b033
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/inlining-constructs-with-fields.js
@@ -0,0 +1,49 @@
+// REQUIRES: inline-allocation
+// A construct of a base constructor whose fields have literal values creates `this` with the shape it has after the
+// fields and stores their values. A derived constructor with fields initializes them through the slow path of
+// BindThisFromSuperCall, in the published frames of the inlined construct.
+
+class A {
+ a = 1;
+ b = 2;
+ constructor(x) {
+ this.x = x;
+ }
+}
+class B extends A {
+ c = 3;
+ constructor(x) {
+ super(x);
+ }
+}
+function makeBase(i) {
+ return new A(i).x;
+}
+function makeDerived(i) {
+ return new B(i).x;
+}
+jit.prepare(makeBase);
+jit.prepare(makeDerived);
+for (let i = 0; i < 10; ++i) {
+ makeBase(i);
+ makeDerived(i);
+}
+jit.compile(makeBase);
+jit.compile(makeDerived);
+
+// CHECK-FUNCTION: makeBase
+// CHECK-PASS: graph building
+// CHECK-NOT: CallConstruct
+// CHECK: AllocateObject
+// CHECK: InitializeNamed
+// CHECK: InitializeNamed
+// CHECK-NOT: CallConstruct
+
+// CHECK-FUNCTION: makeDerived
+// CHECK-PASS: graph building
+// CHECK-NOT: CallConstruct
+// CHECK-NOT: SuperCall
+// CHECK: AllocateObject
+// CHECK: InitializeNamed
+// CHECK: CallSlowPath BindThisFromSuperCall
+// CHECK-NOT: CallConstruct
diff --git a/Tests/LibJS/Runtime/classes/class-super-call-paths.js b/Tests/LibJS/Runtime/classes/class-super-call-paths.js
index 1f117526bb6..873c2d87445 100644
--- a/Tests/LibJS/Runtime/classes/class-super-call-paths.js
+++ b/Tests/LibJS/Runtime/classes/class-super-call-paths.js
@@ -1111,3 +1111,287 @@ describe("inheritance chains in hot callers", () => {
});
});
});
+
+describe("instance elements of derived constructs in hot callers", () => {
+ test("fields of each level in order, right after each super() returns", () => {
+ const log = [];
+ class A {
+ a = (log.push("a"), 1);
+ constructor() {
+ log.push("A body");
+ }
+ }
+ class B extends A {
+ b = (log.push("b"), this.a + 1);
+ constructor() {
+ log.push("B before");
+ super();
+ log.push("B after");
+ }
+ }
+ class C extends B {
+ c = (log.push("c"), this.b + 1);
+ constructor() {
+ super();
+ log.push("C after");
+ }
+ }
+ function make() {
+ return new C();
+ }
+ repeat(() => {
+ log.length = 0;
+ const c = make();
+ expect(log).toEqual(["B before", "a", "A body", "b", "B after", "c", "C after"]);
+ expect(Object.keys(c)).toEqual(["a", "b", "c"]);
+ expect(c.c).toBe(3);
+ });
+ });
+
+ test("initializers see this, earlier fields, private names and no new.target", () => {
+ class A {
+ constructor(x) {
+ this.x = x;
+ }
+ }
+ class B extends A {
+ #secret = this.x * 2;
+ first = this.#secret + 1;
+ second = this.first + 1;
+ target = new.target;
+ arrow = () => this.x;
+ constructor(x) {
+ super(x);
+ }
+ secret() {
+ return this.#secret;
+ }
+ }
+ function make(i) {
+ return new B(i);
+ }
+ repeat(i => {
+ const b = make(i);
+ expect(b.secret()).toBe(i * 2);
+ expect(b.first).toBe(i * 2 + 1);
+ expect(b.second).toBe(i * 2 + 2);
+ expect(b.target).toBeUndefined();
+ expect(b.arrow()).toBe(i);
+ });
+ });
+
+ test("private methods and accessors are installed before fields", () => {
+ class A {}
+ class B extends A {
+ seen = this.#method() + this.#accessor;
+ #method() {
+ return 1;
+ }
+ get #accessor() {
+ return 2;
+ }
+ constructor() {
+ super();
+ }
+ }
+ function make() {
+ return new B();
+ }
+ repeat(() => expect(make().seen).toBe(3));
+ });
+
+ test("fields are defined, not set, and initializers may throw", () => {
+ let setterCalls = 0;
+ class A {
+ set field(value) {
+ setterCalls++;
+ }
+ }
+ class B extends A {
+ field = 1;
+ other = B.fail
+ ? (() => {
+ throw new Error("initializer");
+ })()
+ : 2;
+ constructor() {
+ super();
+ }
+ }
+ function make() {
+ return new B();
+ }
+ repeat(i => {
+ B.fail = i % 100 === 99;
+ if (B.fail) {
+ expect(make).toThrowWithMessage(Error, "initializer");
+ return;
+ }
+ const b = make();
+ expect(Object.getOwnPropertyDescriptor(b, "field").value).toBe(1);
+ expect(b.other).toBe(2);
+ });
+ expect(setterCalls).toBe(0);
+ });
+
+ test("fields on objects returned by a parent", () => {
+ let returned = null;
+ class A {
+ constructor() {
+ if (returned) return returned;
+ }
+ }
+ class B extends A {
+ field = 1;
+ #private = 2;
+ constructor() {
+ super();
+ }
+ static hasPrivate(object) {
+ return #private in object;
+ }
+ }
+ function make() {
+ return new B();
+ }
+ repeat(i => {
+ returned = null;
+ if (i % 100 === 50) {
+ returned = Object.freeze({});
+ expect(make).toThrow(TypeError);
+ returned = {};
+ const object = make();
+ expect(object).toBe(returned);
+ expect(B.hasPrivate(object)).toBeTrue();
+ expect(make).toThrow(TypeError);
+ return;
+ }
+ expect(make().field).toBe(1);
+ });
+ });
+
+ test("computed field names are evaluated once", () => {
+ let evaluations = 0;
+ class A {}
+ class B extends A {
+ [(evaluations++, "computed")] = 1;
+ constructor() {
+ super();
+ }
+ }
+ function make() {
+ return new B();
+ }
+ repeat(() => expect(make().computed).toBe(1));
+ expect(evaluations).toBe(1);
+ });
+});
+
+describe("fields of base constructs in hot callers", () => {
+ test("literal fields, duplicate and symbol names, and the body after them", () => {
+ const symbol = Symbol("field");
+ class A {
+ a = 1;
+ b;
+ a = 3;
+ [symbol] = true;
+ "quoted name" = null;
+ constructor(x) {
+ this.seenA = this.a;
+ this.x = x;
+ }
+ }
+ function make(i) {
+ return new A(i);
+ }
+ repeat(i => {
+ const a = make(i);
+ expect(Object.keys(a)).toEqual(["a", "b", "quoted name", "seenA", "x"]);
+ expect(a.a).toBe(3);
+ expect(a.b).toBeUndefined();
+ expect(a[symbol]).toBeTrue();
+ expect(a.seenA).toBe(3);
+ expect(a.x).toBe(i);
+ expect(Object.getOwnPropertyDescriptor(a, "a")).toEqual({
+ value: 3,
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ });
+ });
+ });
+
+ test("fields are defined, not set, on objects with setters in the prototype chain", () => {
+ let setterCalls = 0;
+ class A {
+ field = 1;
+ set field(value) {
+ setterCalls++;
+ }
+ }
+ function make() {
+ return new A();
+ }
+ repeat(() => expect(Object.getOwnPropertyDescriptor(make(), "field").value).toBe(1));
+ expect(setterCalls).toBe(0);
+ });
+
+ test("parents with fields under derived constructors, new targets and prototypes changing while hot", () => {
+ class A {
+ fromA = 1;
+ constructor() {
+ this.target = new.target;
+ }
+ }
+ class B extends A {
+ constructor() {
+ super();
+ this.fromB = this.fromA + 1;
+ }
+ }
+ class C extends B {
+ fromC = 3;
+ }
+ class Other {
+ fromOther = 4;
+ }
+ function make(i) {
+ return i % 7 === 0 ? Reflect.construct(B, [], Array) : new C();
+ }
+ repeat(i => {
+ if (i === ITERATIONS / 2) Object.setPrototypeOf(B, Other);
+ const result = make(i);
+ if (i % 7 === 0) {
+ expect(result.target).toBe(i < ITERATIONS / 2 ? Array : undefined);
+ expect(Object.getPrototypeOf(result)).toBe(Array.prototype);
+ return;
+ }
+ expect(Object.getPrototypeOf(result)).toBe(C.prototype);
+ expect(result.fromC).toBe(3);
+ if (i < ITERATIONS / 2) {
+ expect(Object.keys(result)).toEqual(["fromA", "target", "fromB", "fromC"]);
+ } else {
+ expect(Object.keys(result)).toEqual(["fromOther", "fromB", "fromC"]);
+ expect(result.fromB).toBeNaN();
+ }
+ });
+ });
+
+ test("the prototype of the prototype of the new target changing while hot", () => {
+ class A {
+ field = 1;
+ }
+ class B extends A {}
+ const proto = { custom: true };
+ function make() {
+ return new B();
+ }
+ repeat(i => {
+ if (i === ITERATIONS / 2) Object.setPrototypeOf(B.prototype, proto);
+ const b = make();
+ expect(b.field).toBe(1);
+ expect(Object.getPrototypeOf(b)).toBe(B.prototype);
+ expect(b.custom).toBe(i < ITERATIONS / 2 ? undefined : true);
+ });
+ });
+});