Truly independent web browser
LibJS: Give lazy function prototypes their place after length and name
Andreas Kling767c63487958
diff --git a/Libraries/LibJS/Rust/src/layout/function_object.rs b/Libraries/LibJS/Rust/src/layout/function_object.rsindex b56cf135429..d614089dcb6 100644--- a/Libraries/LibJS/Rust/src/layout/function_object.rs+++ b/Libraries/LibJS/Rust/src/layout/function_object.rs@@ -128,6 +128,9 @@ pub struct EcmascriptFunctionObjectWithRareData {pub mod ecmascript_function_flags {/// Set on all ECMAScript function objects, which keeps their flags from reading as a builtin.pub const IS_ECMASCRIPT_FUNCTION: u8 = 1 << 7;+ /// The normal function may not have its "prototype" property yet, and acts as if it had it right after "length"+ /// and "name". Until it gets it, its shape is a chain of transitions from the premade shape it started from, and+ /// the function's own "length" and "name" are the first two properties of its shape, unless those are lazy too.pub const MAY_NEED_LAZY_PROTOTYPE_INSTANTIATION: u8 = 1 << 0;pub const IS_METHOD: u8 = 1 << 1;/// The function does not have its "length" and "name" properties yet, and acts as if it had them, in front of thediff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex cd79c0c8812..b3f5f4ae729 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -407,6 +407,88 @@ impl EcmascriptFunctionObject {fn reify_lazy_length_and_name_with_name(&self, vm: &Vm, name_string: Gc<PrimitiveString>) {self.set_flag(ecmascript_function_flags::HAS_LAZY_LENGTH_AND_NAME, false);+ let attributes = PropertyAttributes::new(Attribute::CONFIGURABLE);+ self.insert_properties(+ vm,+ 0,+ &[(&vm.names.length, attributes), (&vm.names.name, attributes)],+ &[Value::from_i32(self.function_length()), Value::from_string(name_string)],+ );+ }++ /// OPTIMIZATION: Few normal functions are ever used as constructors, so they make their "prototype" property when+ /// something looks for it.+ ///+ /// Gives the function its "prototype" property if it may not have it yet, right after "length" and "name", where+ /// the spec creates it.+ #[inline(always)]+ fn instantiate_lazy_prototype_if_needed(&self, vm: &Vm) {+ if self.has_flag(ecmascript_function_flags::MAY_NEED_LAZY_PROTOTYPE_INSTANTIATION) {+ self.instantiate_lazy_prototype(vm);+ }+ }++ fn instantiate_lazy_prototype(&self, vm: &Vm) {+ self.set_flag(ecmascript_function_flags::MAY_NEED_LAZY_PROTOTYPE_INSTANTIATION, false);++ // NB: Class constructors and functions from the Function constructor are given theirs directly.+ if self.shape().lookup(&vm.names.prototype).is_some() {+ return;+ }++ let realm = self.realm().expect("an ECMAScript function has a realm");+ let prototype = Object::create_with_premade_shape(vm, realm.normal_function_prototype_shape());+ prototype.initialize_direct(+ realm.normal_function_prototype_constructor_offset(),+ Value::from_object(self.as_function_object_gc()),+ );++ let attributes = PropertyAttributes::new(Attribute::WRITABLE);+ // NB: Lazy "length" and "name" are put in front of all other properties when they are made.+ let index = if self.has_flag(ecmascript_function_flags::HAS_LAZY_LENGTH_AND_NAME) {+ 0+ } else {+ let shape = self.shape();+ debug_assert!(+ shape+ .lookup(&vm.names.length)+ .is_some_and(|metadata| metadata.offset == 0)+ && shape+ .lookup(&vm.names.name)+ .is_some_and(|metadata| metadata.offset == 1),+ "a function with a lazy prototype has its length and name first"+ );+ 2+ };+ if self.shape().property_count() == index {+ self.define_direct_property(vm, &vm.names.prototype, Value::from_object(prototype), attributes);+ return;+ }+ self.insert_properties(+ vm,+ index,+ &[(&vm.names.prototype, attributes)],+ &[Value::from_object(prototype)],+ );+ }++ /// Gives the function all of the properties it makes lazily. This must happen before its shape changes in a way that+ /// insert_properties() cannot rebuild.+ pub(crate) fn reify_lazy_properties(&self, vm: &Vm) {+ self.reify_length_and_name(vm);+ self.instantiate_lazy_prototype_if_needed(vm);+ }++ /// Rebuilds the shape from the premade shape of the function's kind with the given properties in front of the one+ /// at `index` in insertion order, and gives them the given values.+ fn insert_properties(+ &self,+ vm: &Vm,+ index: u32,+ properties: &[(&PropertyKey, PropertyAttributes)],+ values: &[Value],+ ) {+ debug_assert_eq!(properties.len(), values.len());let old_shape = self.shape();// NB: Rebuilding the shape bypasses transitions away from the old one and moves existing property offsets.old_shape.mark_unstable(vm);@@ -415,15 +497,12 @@ impl EcmascriptFunctionObject {FunctionKind::Normal => realm.normal_function_shape(),FunctionKind::Async => realm.async_function_shape(),FunctionKind::Generator | FunctionKind::AsyncGenerator => {- unreachable!("generator functions have their length and name from the start")+ unreachable!("generator functions have all of their properties from the start")}};if shape.prototype() != old_shape.prototype() {shape = shape.create_prototype_transition(vm, old_shape.prototype());}- let attributes = PropertyAttributes::new(Attribute::CONFIGURABLE);- shape = shape.create_put_transition(vm, &vm.names.length, attributes);- shape = shape.create_put_transition(vm, &vm.names.name, attributes);// NB: Adding the transitions can allocate, which must not happen while the shape is borrowed, so the properties// are read out first.let property_count = old_shape.property_count() as usize;@@ -434,15 +513,22 @@ impl EcmascriptFunctionObject {property_attributes.push(metadata.attributes);ControlFlow::Continue(())});- for (index, attributes) in property_attributes.into_iter().enumerate() {- let property_key = property_keys.get(index).expect("the index is in bounds");+ for (position, attributes) in property_attributes.into_iter().enumerate() {+ if position == index as usize {+ for (inserted_key, inserted_attributes) in properties {+ shape = shape.create_put_transition(vm, inserted_key, *inserted_attributes);+ }+ }+ let property_key = property_keys.get(position).expect("the position is in bounds");shape = shape.create_put_transition(vm, &property_key, attributes);}+ if index as usize == property_count {+ for (inserted_key, inserted_attributes) in properties {+ shape = shape.create_put_transition(vm, inserted_key, *inserted_attributes);+ }+ }- self.prepend_named_properties(- shape,- &[Value::from_i32(self.function_length()), Value::from_string(name_string)],- );+ self.insert_named_properties(shape, index, values);}pub fn as_ecmascript_function_gc(&self) -> Gc<EcmascriptFunctionObject> {@@ -1240,22 +1326,7 @@ impl EcmascriptFunctionObject {if function.has_flag(ecmascript_function_flags::MAY_NEED_LAZY_PROTOTYPE_INSTANTIATION)&& *property_key == vm.names.prototype{- let realm = function.realm().expect("an ECMAScript function has a realm");- let metadata = object.shape().lookup(property_key);- if metadata.is_none() {- let prototype = Object::create_with_premade_shape(vm, realm.normal_function_prototype_shape());- prototype.initialize_direct(- realm.normal_function_prototype_constructor_offset(),- Value::from_object(function.as_function_object_gc()),- );- object.define_direct_property(- vm,- &vm.names.prototype,- Value::from_object(prototype),- PropertyAttributes::new(Attribute::WRITABLE),- );- }- function.set_flag(ecmascript_function_flags::MAY_NEED_LAZY_PROTOTYPE_INSTANTIATION, false);+ function.instantiate_lazy_prototype(vm);}object.ordinary_get_own_property(vm, property_key)@@ -1264,10 +1335,7 @@ impl EcmascriptFunctionObject {fn internal_own_property_keys<'vm>(object: &Object, vm: &'vm Vm) -> ThrowCompletionOr<MarkedVec<'vm, Value>> {let function = as_ecmascript_function(object);- function.reify_length_and_name(vm);- if function.has_flag(ecmascript_function_flags::MAY_NEED_LAZY_PROTOTYPE_INSTANTIATION) {- Self::internal_get_own_property(object, vm, &vm.names.prototype)?;- }+ function.reify_lazy_properties(vm);object.ordinary_own_property_keys(vm)}diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex 35b400ebe1c..61fd1e1a162 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -2853,7 +2853,7 @@ impl Object {// NB: Setting a lazy property of a function must find it.if self.is_ecmascript_function_object() && (*property_key == vm.names.length || *property_key == vm.names.name){- self.reify_lazy_function_properties(vm);+ cast_ref::<Object, EcmascriptFunctionObject>(self).reify_length_and_name(vm);}let Some(metadata) = self.shape().lookup(property_key) else {@@ -3704,19 +3704,21 @@ impl Object {.cast_mut()}- /// Puts the property values in front of the existing ones, as `shape` has them.- pub(crate) fn prepend_named_properties(&self, shape: Gc<Shape>, values: &[Value]) {+ /// Puts the property values in front of the existing one in slot `index`, as `shape` has them.+ pub(crate) fn insert_named_properties(&self, shape: Gc<Shape>, index: u32, values: &[Value]) {let existing_count = self.shape().property_count();+ assert!(index <= existing_count);self.ensure_named_storage_capacity(existing_count + values.len() as u32);- let named_properties = self.named_properties.get();- // SAFETY: The named storage has room for the existing and the new values.+ // SAFETY: The named storage has room for the existing and the new values, and `index` is at most the number of+ // existing values.unsafe {+ let insertion_point = self.named_properties.get().add(index as usize);core::ptr::copy(- named_properties,- named_properties.add(values.len()),- existing_count as usize,+ insertion_point,+ insertion_point.add(values.len()),+ (existing_count - index) as usize,);- core::ptr::copy_nonoverlapping(values.as_ptr(), named_properties, values.len());+ core::ptr::copy_nonoverlapping(values.as_ptr(), insertion_point, values.len());}self.shape.set(shape);}@@ -3724,7 +3726,7 @@ impl Object {#[inline(always)]fn reify_lazy_function_properties(&self, vm: &Vm) {if self.is_ecmascript_function_object() {- cast_ref::<Object, EcmascriptFunctionObject>(self).reify_length_and_name(vm);+ cast_ref::<Object, EcmascriptFunctionObject>(self).reify_lazy_properties(vm);}}diff --git a/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.js b/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.jsindex 9af1f98eb7b..50434d9b0a0 100644--- a/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.js+++ b/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.js@@ -185,13 +185,7 @@ describe("own properties of functions that never had them looked at", () => {expect(f.b).toBe(2);expect(f.c).toBe(3);expect(f.length).toBe(1);- expect(Object.getOwnPropertyNames(f).filter(name => name !== "prototype")).toEqual([- "length",- "name",- "a",- "b",- "c",- ]);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "a", "b", "c"]);expect(Object.getOwnPropertyDescriptor(f, "c").enumerable).toBeFalse();expect(Object.keys(f)).toEqual(["a", "b"]);});@@ -236,7 +230,7 @@ describe("own properties of functions that never had them looked at", () => {const o = Object.create(f);expect(o.a).toBe(1);expect(o.name).toBe("named");- expect(Object.getOwnPropertyNames(f).slice(0, 3)).toEqual(["length", "name", "a"]);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "a"]);});test("the prototype property does not get ahead of them", () => {diff --git a/Tests/LibJS/Runtime/functions/function-lazy-prototype.js b/Tests/LibJS/Runtime/functions/function-lazy-prototype.jsnew file mode 100644index 00000000000..6a82c8b547c--- /dev/null+++ b/Tests/LibJS/Runtime/functions/function-lazy-prototype.js@@ -0,0 +1,139 @@+describe("the prototype property of normal functions that never had it looked at", () => {+ test("it comes right after length and name, whatever is added first", () => {+ function f() {}+ f.g = 1;+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "g"]);++ function h() {}+ h.prototype;+ h.g = 1;+ expect(Object.getOwnPropertyNames(h)).toEqual(["length", "name", "prototype", "g"]);+ });++ test("length and name were looked at first", () => {+ function f(a) {}+ expect(f.length).toBe(1);+ f.g = 1;+ f.h = 2;+ expect(f.prototype.constructor).toBe(f);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "g", "h"]);+ expect(f.g + f.h).toBe(3);+ });++ test("length and name are looked at last", () => {+ function f(a, b) {}+ f.g = 1;+ f.prototype.x = 1;+ f.h = 2;+ expect(f.name).toBe("f");+ expect(f.length).toBe(2);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "g", "h"]);+ expect(new f().x).toBe(1);+ expect(f.g + f.h).toBe(3);+ });++ test("it is assigned to first", () => {+ function f() {}+ f.g = 1;+ const prototype = {};+ f.prototype = prototype;+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "g"]);+ expect(Object.getPrototypeOf(new f())).toBe(prototype);+ });++ test("deleting length or name", () => {+ function f() {}+ expect(f.length).toBe(0);+ expect(delete f.name).toBeTrue();+ f.g = 1;+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "prototype", "g"]);++ function h() {}+ h.g = 1;+ expect(delete h.length).toBeTrue();+ expect(Object.getOwnPropertyNames(h)).toEqual(["name", "prototype", "g"]);++ function k() {}+ expect(delete k.name).toBeTrue();+ Object.defineProperty(k, "name", { value: "other" });+ expect(Object.getOwnPropertyNames(k)).toEqual(["length", "prototype", "name"]);+ expect(k.name).toBe("other");+ });++ test("deleting an added property", () => {+ function f() {}+ f.g = 1;+ f.h = 2;+ expect(delete f.g).toBeTrue();+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "h"]);+ expect(f.h).toBe(2);+ });++ test("preventing extensions", () => {+ function f() {}+ f.g = 1;+ Object.preventExtensions(f);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "g"]);+ expect(f.prototype.constructor).toBe(f);+ expect(Object.isExtensible(f)).toBeFalse();+ });++ test("changing the prototype of the function", () => {+ function f() {}+ f.g = 1;+ Object.setPrototypeOf(f, null);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "g"]);+ expect(Object.getPrototypeOf(f)).toBeNull();+ });++ test("many added properties", () => {+ function f() {}+ for (let i = 0; i < 100; ++i) f["p" + i] = i;+ const names = Object.getOwnPropertyNames(f);+ expect(names.length).toBe(103);+ expect(names.slice(0, 4)).toEqual(["length", "name", "prototype", "p0"]);+ for (let i = 0; i < 100; ++i) expect(f["p" + i]).toBe(i);+ expect(f.prototype.constructor).toBe(f);++ function g() {}+ expect(g.name).toBe("g");+ for (let i = 0; i < 100; ++i) g["p" + i] = i;+ expect(g.prototype.constructor).toBe(g);+ expect(Object.getOwnPropertyNames(g).slice(0, 4)).toEqual(["length", "name", "prototype", "p0"]);+ for (let i = 0; i < 100; ++i) expect(g["p" + i]).toBe(i);+ });++ test("a function that is a prototype", () => {+ function f() {}+ f.g = 1;+ const o = Object.create(f);+ expect(o.g).toBe(1);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "prototype", "g"]);+ expect(o.prototype).toBe(f.prototype);++ function A() {}+ A.s = 1;+ class B extends A {}+ expect(B.s).toBe(1);+ expect(Object.getOwnPropertyNames(A)).toEqual(["length", "name", "prototype", "s"]);+ expect(new B()).toBeInstanceOf(A);+ });++ test("functions made in a loop", () => {+ const make = () => {+ function F(x) {}+ F.a = 1;+ F.prototype.b = 2;+ F.c = 3;+ return F;+ };+ for (let i = 0; i < 3000; ++i) {+ const F = make();+ expect(F.a + F.c + new F().b).toBe(6);+ if (i % 100 === 0) {+ expect(F.length).toBe(1);+ expect(Object.getOwnPropertyNames(F)).toEqual(["length", "name", "prototype", "a", "c"]);+ }+ }+ });+});