Truly independent web browser
LibJS: Move legacy caller and arguments to Function.prototype
Andreas Kling56fdf3f7152f
diff --git a/Libraries/LibJS/Rust/src/jit/intrinsics.rs b/Libraries/LibJS/Rust/src/jit/intrinsics.rsindex 7fa819b46aa..f1aee59dd63 100644--- a/Libraries/LibJS/Rust/src/jit/intrinsics.rs+++ b/Libraries/LibJS/Rust/src/jit/intrinsics.rs@@ -106,9 +106,7 @@ fn has_ordinary_lookups(object: Gc<Object>) -> bool {/// Whether looking up the property `key` of the object creates nothing.fn lookup_creates_nothing(vm: &Vm, object: Gc<Object>, key: &PropertyKey) -> bool {- if object.is_ecmascript_function_object()- && (*key == vm.names.prototype || *key == vm.names.caller || *key == vm.names.arguments)- {+ if object.is_ecmascript_function_object() && *key == vm.names.prototype {return false;}if key.is_number() {diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex fc4d1c4b7ba..608d4956038 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -81,15 +81,10 @@ unsafe impl Trace for EcmascriptFunctionObjectStorage {pub static ECMASCRIPT_FUNCTION_OBJECT_METHODS: ObjectMethods = ObjectMethods {internal_get_own_property: EcmascriptFunctionObject::internal_get_own_property,- // NB: Functions answer for "length", "name" and "prototype" before creating them lazily, and for "caller" and- // "arguments" if they support the legacy properties, whatever their shape holds. They answer for other names- // like ordinary objects.+ // NB: Functions answer for "length", "name" and "prototype" before creating them lazily, whatever their shape+ // holds. They answer for other names like ordinary objects.is_cacheable_for_absence_of: |_, vm, property_key| {- *property_key != vm.names.prototype- && *property_key != vm.names.caller- && *property_key != vm.names.arguments- && *property_key != vm.names.length- && *property_key != vm.names.name+ *property_key != vm.names.prototype && *property_key != vm.names.length && *property_key != vm.names.name},// NB: The non-enumerable lazy properties shadow enumerable ones of the prototype chain.eligible_for_own_property_enumeration_fast_path: |object| {@@ -1097,17 +1092,8 @@ impl EcmascriptFunctionObject {}pub fn supports_legacy_caller_or_arguments(&self) -> bool {- // https://tc39.es/ecma262/#sec-forbidden-extensions- //- // ECMAScript function objects defined using syntactic constructors in strict mode code must not be created with own- // properties named *"caller"* or *"arguments"*. Such own properties also must not be created for function objects- // defined using an |ArrowFunction|, |MethodDefinition|, |GeneratorDeclaration|, |GeneratorExpression|,- // |AsyncGeneratorDeclaration|, |AsyncGeneratorExpression|, |ClassDeclaration|, |ClassExpression|,- // |AsyncFunctionDeclaration|, |AsyncFunctionExpression|, or |AsyncArrowFunction| regardless of whether the definition- // is contained in strict mode code.- // Built-in functions, strict functions created using the Function constructor, generator functions created using- // the Generator constructor, async functions created using the AsyncFunction constructor, and functions created- // using the `bind` method also must not be created with such own properties.+ // NB: These are the functions that the "caller" and "arguments" accessors of %Function.prototype% accept. The+ // others are the functions that https://tc39.es/ecma262/#sec-forbidden-extensions keeps from exposing them.self.kind() == FunctionKind::Normal&& !self.is_arrow_function()&& !self.is_class_constructor()@@ -1115,7 +1101,7 @@ impl EcmascriptFunctionObject {&& !self.is_strict_mode()}- fn legacy_caller(&self, vm: &Vm) -> Value {+ pub fn legacy_caller(&self, vm: &Vm) -> Value {let this_function = self.as_function_object_gc();let mut caller: Option<Gc<EcmascriptFunctionObject>> = None;let mut found_this_function = false;@@ -1136,19 +1122,15 @@ impl EcmascriptFunctionObject {ControlFlow::Break(())});- // https://tc39.es/ecma262/#sec-forbidden-extensions- //- // If an implementation extends any function object with an own property named *"caller"* the value of that property,- // as observed using [[Get]] or [[GetOwnProperty]], must not be a strict function object. If it is an accessor- // property, the function that is the value of the property's [[Get]] attribute must never return a strict function- // when called.+ // NB: https://tc39.es/ecma262/#sec-forbidden-extensions keeps own "caller" properties from exposing strict+ // functions. The accessor on %Function.prototype% holds to the same rule.match caller {Some(caller) if caller.supports_legacy_caller_or_arguments() => Value::from_object(caller),_ => Value::NULL,}}- fn legacy_arguments(&self, vm: &Vm) -> Value {+ pub fn legacy_arguments(&self, vm: &Vm) -> Value {let this_function = self.as_function_object_gc();// NB: The arguments of a frame of an inlined call may be objects JIT code never created, which only the// arguments object holds once it exists.@@ -1219,32 +1201,6 @@ impl EcmascriptFunctionObject {function.reify_length_and_name(vm);}- if function.supports_legacy_caller_or_arguments() {- let descriptor = object.ordinary_get_own_property(vm, property_key)?;- if descriptor.is_some() {- return Ok(descriptor);- }-- if *property_key == vm.names.caller {- return Ok(Some(PropertyDescriptor {- value: Some(function.legacy_caller(vm)),- writable: Some(false),- enumerable: Some(false),- configurable: Some(false),- ..Default::default()- }));- }- if *property_key == vm.names.arguments {- return Ok(Some(PropertyDescriptor {- value: Some(function.legacy_arguments(vm)),- writable: Some(false),- enumerable: Some(false),- configurable: Some(false),- ..Default::default()- }));- }- }-if function.has_flag(ecmascript_function_flags::MAY_NEED_LAZY_PROTOTYPE_INSTANTIATION)&& *property_key == vm.names.prototype{@@ -1277,38 +1233,6 @@ impl EcmascriptFunctionObject {Self::internal_get_own_property(object, vm, &vm.names.prototype)?;}- let keys = object.ordinary_own_property_keys(vm)?;- if !function.supports_legacy_caller_or_arguments() {- return Ok(keys);- }-- let mut insertion_index = keys.len();- let name = Utf16String::from(vm.names.name.as_string());- for index in 0..keys.len() {- let key = keys.get(index).expect("the index is in bounds");- if key.is_string() && key.as_string().utf16_string() == name {- insertion_index = index + 1;- break;- }- }-- if object.ordinary_get_own_property(vm, &vm.names.arguments)?.is_none() {- keys.insert(- insertion_index,- Value::from_string(PrimitiveString::create_from_fly_string(- vm,- vm.names.arguments.as_string(),- )),- );- insertion_index += 1;- }- if object.ordinary_get_own_property(vm, &vm.names.caller)?.is_none() {- keys.insert(- insertion_index,- Value::from_string(PrimitiveString::create_from_fly_string(vm, vm.names.caller.as_string())),- );- }-- Ok(keys)+ object.ordinary_own_property_keys(vm)}}diff --git a/Libraries/LibJS/Rust/src/runtime/error_types.rs b/Libraries/LibJS/Rust/src/runtime/error_types.rsindex abfbefde17a..9654ea51736 100644--- a/Libraries/LibJS/Rust/src/runtime/error_types.rs+++ b/Libraries/LibJS/Rust/src/runtime/error_types.rs@@ -121,6 +121,7 @@ define_error_types! {JsonCircular => "Cannot stringify circular object",JsonMalformed => "Malformed JSON string",JsonRawJSONNonPrimitive => "JSON.rawJSON cannot accept object or array as outermost value",+ LegacyCallerOrArgumentsReceiver => "'caller' and 'arguments' may only be accessed on ordinary non-strict functions",MathSumPreciseOverflow => "Overflow in Math.sumPrecise",MissingRequiredProperty => "Required property {} is missing or undefined",ModuleNoEnvironment => "Cannot find module environment for imported binding",diff --git a/Libraries/LibJS/Rust/src/runtime/function_prototype.rs b/Libraries/LibJS/Rust/src/runtime/function_prototype.rsindex f97d8317d2e..a365c383efd 100644--- a/Libraries/LibJS/Rust/src/runtime/function_prototype.rs+++ b/Libraries/LibJS/Rust/src/runtime/function_prototype.rs@@ -51,7 +51,9 @@ use crate::runtime::bound_function::{};use crate::runtime::class_field_definition::ClassElementName;use crate::runtime::completion::{Must, ThrowCompletionOr};-use crate::runtime::ecmascript_function_object::as_ecmascript_function_object;+use crate::runtime::ecmascript_function_object::{+ EcmascriptFunctionObject, as_ecmascript_function_object, value_as_ecmascript_function_object,+};use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;use crate::runtime::function_object::{FUNCTION_OBJECT_METHODS, FunctionObject};@@ -64,6 +66,13 @@ use crate::runtime::realm::Realm;use crate::runtime::value::ordinary_has_instance;use crate::utf16::{Utf16StringBuilder, Utf16View, concatenate};+fn this_function_with_legacy_caller_and_arguments(vm: &Vm) -> ThrowCompletionOr<Gc<EcmascriptFunctionObject>> {+ match value_as_ecmascript_function_object(vm.this_value()) {+ Some(function) if function.supports_legacy_caller_or_arguments() => Ok(function),+ _ => vm.throw_completion(ErrorKind::TypeError, ErrorType::LegacyCallerOrArgumentsReceiver, &[]),+ }+}+/// %Function.prototype%, a function object that accepts any arguments and returns undefined.#[repr(C)]#[derive(Trace)]@@ -158,6 +167,39 @@ impl FunctionPrototype {Value::from_string(PrimitiveString::create(vm, Utf16String::default())),PropertyAttributes::new(Attribute::CONFIGURABLE),);++ // INTEROP: The specification makes these accessors %ThrowTypeError%, and all major engines have them work for+ // sloppy functions. Being accessors here keeps them out of what functions report as their own+ // properties, which scripts that walk object graphs would otherwise follow out of the function.+ object.define_native_accessor(+ vm,+ realm,+ &names.caller,+ raw_native!(FunctionPrototype::legacy_caller_getter),+ raw_native!(FunctionPrototype::legacy_caller_or_arguments_setter),+ PropertyAttributes::new(Attribute::CONFIGURABLE),+ );+ object.define_native_accessor(+ vm,+ realm,+ &names.arguments,+ raw_native!(FunctionPrototype::legacy_arguments_getter),+ raw_native!(FunctionPrototype::legacy_caller_or_arguments_setter),+ PropertyAttributes::new(Attribute::CONFIGURABLE),+ );+ }++ fn legacy_caller_getter(vm: &Vm) -> ThrowCompletionOr<Value> {+ Ok(this_function_with_legacy_caller_and_arguments(vm)?.legacy_caller(vm))+ }++ fn legacy_arguments_getter(vm: &Vm) -> ThrowCompletionOr<Value> {+ Ok(this_function_with_legacy_caller_and_arguments(vm)?.legacy_arguments(vm))+ }++ fn legacy_caller_or_arguments_setter(vm: &Vm) -> ThrowCompletionOr<Value> {+ this_function_with_legacy_caller_and_arguments(vm)?;+ Ok(Value::UNDEFINED)}#[allow(clippy::unnecessary_wraps, reason = "[[Call]] can throw for other functions")]diff --git a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs b/Libraries/LibJS/Rust/src/runtime/intrinsics.rsindex 8dea1b7ed38..8ec6f7f48e1 100644--- a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs+++ b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs@@ -268,7 +268,6 @@ define_intrinsics! {json_parse_function: Cell<Option<Gc<FunctionObject>>>,json_stringify_function: Cell<Option<Gc<FunctionObject>>>,object_prototype_to_string_function: Cell<Option<Gc<FunctionObject>>>,- throw_type_error_function: Cell<Option<Gc<FunctionObject>>>,// JS_ENUMERATE_BUILTIN_TYPESaggregate_error_constructor: Cell<Option<Gc<AggregateErrorConstructor>>>,@@ -522,7 +521,6 @@ created_intrinsics! {json_parse_function: FunctionObject => "%JSON.parse%",json_stringify_function: FunctionObject => "%JSON.stringify%",object_prototype_to_string_function: FunctionObject => "%Object.prototype.toString%",- throw_type_error_function: FunctionObject => "%ThrowTypeError%",array_iterator_prototype: Object => "%ArrayIteratorPrototype%",async_iterator_prototype: Object => "%AsyncIteratorPrototype%",intl_segment_iterator_prototype: Object => "%IntlSegmentIteratorPrototype%",@@ -1106,7 +1104,8 @@ impl Intrinsics {intrinsics.initialize_intrinsics(vm, realm);// 3. Perform AddRestrictedFunctionProperties(realmRec.[[Intrinsics]].[[%Function.prototype%]], realmRec).- add_restricted_function_properties(vm, &realm.intrinsics().function_prototype(vm), realm);+ // INTEROP: All major engines give %Function.prototype% accessors that work for sloppy functions instead, see+ // FunctionPrototype::initialize().realm_watchpoints::arm(vm, realm);@@ -1364,8 +1363,6 @@ impl Intrinsics {None,None,);- self.throw_type_error_function- .set(Some(throw_type_error_function.upcast()));throw_type_error_function.define_direct_property(vm, &names.length, Value::from_i32(0), attributes(0));throw_type_error_function.define_direct_property(vm,@@ -1581,32 +1578,3 @@ impl Intrinsics {self.realm}}--// 10.2.4 AddRestrictedFunctionProperties ( F, realm ), https://tc39.es/ecma262/#sec-addrestrictedfunctionproperties-pub fn add_restricted_function_properties(vm: &Vm, function: &Object, realm: Gc<Realm>) {- // 1. Assert: realm.[[Intrinsics]].[[%ThrowTypeError%]] exists and has been initialized.- // NOTE: This is ensured by dereferencing the GCPtr in the getter.-- // 2. Let thrower be realm.[[Intrinsics]].[[%ThrowTypeError%]].- let thrower = realm.intrinsics().throw_type_error_function();-- // 3. Perform ! DefinePropertyOrThrow(F, "caller", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true }).- function.define_direct_accessor(- vm,- &vm.names.caller,- Some(thrower),- Some(thrower),- PropertyAttributes::new(Attribute::CONFIGURABLE),- );-- // 4. Perform ! DefinePropertyOrThrow(F, "arguments", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true }).- function.define_direct_accessor(- vm,- &vm.names.arguments,- Some(thrower),- Some(thrower),- PropertyAttributes::new(Attribute::CONFIGURABLE),- );-- // 5. Return unused.-}diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex f0df84048e3..74b8b6ccc39 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -1021,8 +1021,8 @@ impl Object {return false;}let methods = self.methods();- // NB: ECMAScript function objects only answer "caller", "arguments" and lazily created "length", "name" and- // "prototype" properties themselves, and arrays only "length" and array indices.+ // NB: ECMAScript function objects only answer lazily created "length", "name" and "prototype" properties+ // themselves, and arrays only "length" and array indices.(core::ptr::fn_addr_eq(methods.internal_get_own_property,ORDINARY_OBJECT_METHODS.internal_get_own_property,@@ -1069,14 +1069,12 @@ impl Object {if core::ptr::fn_addr_eq(internal_get_own_property, ordinary_get_own_property) {return true;}- // NB: ECMAScript function objects only answer "caller", "arguments" and lazily created "length", "name" and- // "prototype" properties themselves.+ // NB: ECMAScript function objects only answer lazily created "length", "name" and "prototype" properties+ // themselves.core::ptr::fn_addr_eq(internal_get_own_property,ECMASCRIPT_FUNCTION_OBJECT_METHODS.internal_get_own_property,- ) && *property_key != vm.names.caller- && *property_key != vm.names.arguments- && *property_key != vm.names.prototype+ ) && *property_key != vm.names.prototype&& *property_key != vm.names.length&& *property_key != vm.names.name}diff --git a/Libraries/LibJS/Rust/src/runtime/realm.rs b/Libraries/LibJS/Rust/src/runtime/realm.rsindex d7e94a320e9..a312a2749a0 100644--- a/Libraries/LibJS/Rust/src/runtime/realm.rs+++ b/Libraries/LibJS/Rust/src/runtime/realm.rs@@ -106,7 +106,6 @@ realm_intrinsic_accessors! {mapped_arguments_object_shape: Shape,regexp_builtin_exec_array_shape: Shape,throw_type_error_accessor: Accessor,- throw_type_error_function: FunctionObject,array_prototype_values_function: FunctionObject,generator_prototype_next_function: FunctionObject,eval_function: FunctionObject,diff --git a/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.js b/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.jsindex d91100d43bc..9af1f98eb7b 100644--- a/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.js+++ b/Tests/LibJS/Runtime/functions/function-lazy-length-and-name.js@@ -1,22 +1,20 @@-const namesOf = f => Object.getOwnPropertyNames(f).filter(name => name !== "arguments" && name !== "caller");-describe("own properties of functions that never had them looked at", () => {test("length and name come first, whatever is added first", () => {function a(x, y) {}a.foo = 1;- expect(namesOf(a).slice(0, 2)).toEqual(["length", "name"]);+ expect(Object.getOwnPropertyNames(a).slice(0, 2)).toEqual(["length", "name"]);expect(a.length).toBe(2);expect(a.name).toBe("a");- expect(namesOf(a)).toContain("foo");+ expect(Object.getOwnPropertyNames(a)).toContain("foo");const b = () => {};Object.defineProperty(b, "bar", { value: 1 });- expect(namesOf(b)).toEqual(["length", "name", "bar"]);+ expect(Object.getOwnPropertyNames(b)).toEqual(["length", "name", "bar"]);const c = async x => {};c[Symbol.iterator] = 1;c.baz = 1;- expect(namesOf(c)).toEqual(["length", "name", "baz"]);+ expect(Object.getOwnPropertyNames(c)).toEqual(["length", "name", "baz"]);expect(c.length).toBe(1);});@@ -73,7 +71,7 @@ describe("own properties of functions that never had them looked at", () => {const f = function named() {};Object.defineProperty(f, "name", { value: "other" });expect(f.name).toBe("other");- expect(namesOf(f).slice(0, 2)).toEqual(["length", "name"]);+ expect(Object.getOwnPropertyNames(f).slice(0, 2)).toEqual(["length", "name"]);});test("objects inheriting from a function see them", () => {@@ -134,7 +132,7 @@ describe("own properties of functions that never had them looked at", () => {f.foo = 1;expect(o.foo).toBe(1);expect(o.length).toBe(1);- expect(namesOf(f).slice(0, 2)).toEqual(["length", "name"]);+ expect(Object.getOwnPropertyNames(f).slice(0, 2)).toEqual(["length", "name"]);});test("bind", () => {@@ -151,9 +149,9 @@ describe("own properties of functions that never had them looked at", () => {}expect(A.name).toBe("A");expect(A.length).toBe(0);- expect(namesOf(A).slice(0, 3)).toEqual(["length", "name", "prototype"]);+ expect(Object.getOwnPropertyNames(A).slice(0, 3)).toEqual(["length", "name", "prototype"]);expect(A.m.name).toBe("m");- expect(namesOf(A.m)).toEqual(["length", "name"]);+ expect(Object.getOwnPropertyNames(A.m)).toEqual(["length", "name"]);class B extends A {constructor(a, b) {@@ -187,7 +185,13 @@ 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(namesOf(f).filter(name => name !== "prototype")).toEqual(["length", "name", "a", "b", "c"]);+ expect(Object.getOwnPropertyNames(f).filter(name => name !== "prototype")).toEqual([+ "length",+ "name",+ "a",+ "b",+ "c",+ ]);expect(Object.getOwnPropertyDescriptor(f, "c").enumerable).toBeFalse();expect(Object.keys(f)).toEqual(["a", "b"]);});@@ -197,14 +201,14 @@ describe("own properties of functions that never had them looked at", () => {f.a = 1;f.b = 2;expect(delete f.a).toBeTrue();- expect(namesOf(f)).toEqual(["length", "name", "b"]);+ expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "b"]);expect(f.b).toBe(2);});test("many added properties", () => {const f = () => {};for (let i = 0; i < 100; ++i) f["p" + i] = i;- const names = namesOf(f);+ const names = Object.getOwnPropertyNames(f);expect(names.length).toBe(102);expect(names.slice(0, 3)).toEqual(["length", "name", "p0"]);for (let i = 0; i < 100; ++i) expect(f["p" + i]).toBe(i);@@ -232,7 +236,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(namesOf(f).slice(0, 3)).toEqual(["length", "name", "a"]);+ expect(Object.getOwnPropertyNames(f).slice(0, 3)).toEqual(["length", "name", "a"]);});test("the prototype property does not get ahead of them", () => {@@ -240,7 +244,7 @@ describe("own properties of functions that never had them looked at", () => {F.prototype.x = 1;expect(new F().x).toBe(1);expect(F.length).toBe(2);- expect(namesOf(F)).toEqual(["length", "name", "prototype"]);+ expect(Object.getOwnPropertyNames(F)).toEqual(["length", "name", "prototype"]);});test("cached additions keep functions apart", () => {@@ -252,7 +256,7 @@ describe("own properties of functions that never had them looked at", () => {for (let i = 0; i < 3000; ++i) {const f = addTo(x => x);if (i % 3 === 0) expect(f.length).toBe(1);- if (i % 3 === 1) expect(namesOf(f)).toEqual(["length", "name", "a", "b"]);+ if (i % 3 === 1) expect(Object.getOwnPropertyNames(f)).toEqual(["length", "name", "a", "b"]);expect(f.a + f.b).toBe(3);if (i % 7 === 0) {expect(f.name).toBe("");@@ -273,7 +277,7 @@ describe("own properties of functions that never had them looked at", () => {expect(lengthOf(f)).toBe(2);expect(nameOf(f)).toBe("named");const g = addTo(() => {});- expect(namesOf(g)).toEqual(["length", "name", "foo"]);+ expect(Object.getOwnPropertyNames(g)).toEqual(["length", "name", "foo"]);expect(g.foo).toBe(1);expect(lengthOf(addTo(x => x))).toBe(1);}@@ -286,7 +290,7 @@ describe("own properties of functions that never had them looked at", () => {last = make();if (i % 1000 === 0) {expect(last.length).toBe(1);- expect(namesOf(last)).toEqual(["length", "name"]);+ expect(Object.getOwnPropertyNames(last)).toEqual(["length", "name"]);}}expect(last.length).toBe(1);diff --git a/Tests/LibJS/Runtime/functions/function-legacy-caller-arguments.js b/Tests/LibJS/Runtime/functions/function-legacy-caller-arguments.jsindex 0b11557dca9..ec65f6e64f4 100644--- a/Tests/LibJS/Runtime/functions/function-legacy-caller-arguments.js+++ b/Tests/LibJS/Runtime/functions/function-legacy-caller-arguments.js@@ -74,50 +74,124 @@ test("restricted functions keep the throwing caller and arguments accessors", ()expect(() => arrow.arguments).toThrow(TypeError);});-test("legacy caller and arguments properties appear in own property keys", () => {- function ordinary() {}+test("legacy caller and arguments are not own properties of functions", () => {+ function ordinary() {+ expect(Object.getOwnPropertyDescriptor(ordinary, "caller")).toBeUndefined();+ expect(Object.getOwnPropertyDescriptor(ordinary, "arguments")).toBeUndefined();+ }+ ordinary();++ expect(Object.getOwnPropertyNames(ordinary)).not.toContain("caller");+ expect(Object.getOwnPropertyNames(ordinary)).not.toContain("arguments");+ expect(Reflect.ownKeys(ordinary)).not.toContain("caller");+ expect(Reflect.ownKeys(ordinary)).not.toContain("arguments");+ expect(Object.hasOwn(ordinary, "caller")).toBeFalse();+ expect(Object.hasOwn(ordinary, "arguments")).toBeFalse();+ expect("caller" in ordinary).toBeTrue();+ expect("arguments" in ordinary).toBeTrue();+});- let ownPropertyNames = Object.getOwnPropertyNames(ordinary);- expect(ownPropertyNames).toContain("arguments");- expect(ownPropertyNames).toContain("caller");+test("walking own properties from inside a function does not reach its caller's arguments", () => {+ const secret = {};++ function walk(root) {+ const seen = [];+ (function visit(object) {+ if (!object || (typeof object !== "object" && typeof object !== "function") || seen.includes(object))+ return;+ seen.push(object);+ for (const name of Object.getOwnPropertyNames(object)) {+ const descriptor = Object.getOwnPropertyDescriptor(object, name);+ if ("value" in descriptor) visit(descriptor.value);+ }+ })(root);+ return seen;+ }++ function outer(argument) {+ const holder = {+ method: function () {+ return walk(holder);+ },+ };+ return holder.method();+ }- let ownKeys = Reflect.ownKeys(ordinary);- expect(ownKeys).toContain("arguments");- expect(ownKeys).toContain("caller");+ expect(outer(secret)).not.toContain(secret);});-test("legacy caller and arguments properties materialized by defineProperty are stable", () => {- function getCallerDescriptor() {- return Reflect.getOwnPropertyDescriptor(getCallerDescriptor, "caller");+test("%Function.prototype% has caller and arguments accessors", () => {+ function strict() {+ "use strict";}- function callGetCallerDescriptor() {- return getCallerDescriptor();+ for (const name of ["caller", "arguments"]) {+ const descriptor = Object.getOwnPropertyDescriptor(Function.prototype, name);+ expect(descriptor.get).toBeInstanceOf(Function);+ expect(descriptor.set).toBeInstanceOf(Function);+ expect(descriptor.enumerable).toBeFalse();+ expect(descriptor.configurable).toBeTrue();++ expect(descriptor.get.call(function () {})).toBeNull();+ expect(descriptor.set.call(function () {}, 1)).toBeUndefined();++ const restricted = [strict, () => {}, class {}, function* () {}, async function () {}, Math.abs, {}, 1];+ restricted.push(function () {}.bind(), { method() {} }.method, Function.prototype, undefined);+ for (const receiver of restricted) {+ expect(() => descriptor.get.call(receiver)).toThrow(TypeError);+ expect(() => descriptor.set.call(receiver, 1)).toThrow(TypeError);+ }+ }+});++test("objects that inherit from sloppy functions cannot use legacy caller and arguments", () => {+ function base() {}+ class Derived extends base {}++ for (const object of [Object.create(base), new Proxy(base, {}), Derived]) {+ expect(() => object.caller).toThrowWithMessage(TypeError, "ordinary non-strict functions");+ expect(() => object.arguments).toThrowWithMessage(TypeError, "ordinary non-strict functions");}- expect(- Reflect.defineProperty(getCallerDescriptor, "caller", {- writable: false,- configurable: false,- })- ).toBeTrue();+ const inheriting = Object.create(base);+ expect(() => {+ inheriting.caller = 1;+ }).toThrow(TypeError);+ expect(() => {+ inheriting.arguments = 1;+ }).toThrow(TypeError);+});++test("assigning to legacy caller and arguments does nothing", () => {+ function ordinary() {+ ordinary.caller = 1;+ ordinary.arguments = 2;+ return [ordinary.caller, ordinary.arguments];+ }- let callerDescriptor = Reflect.getOwnPropertyDescriptor(getCallerDescriptor, "caller");- expect(callerDescriptor.value).toBeNull();- expect(callGetCallerDescriptor().value).toBe(callerDescriptor.value);+ const [caller, argumentsObject] = ordinary(3);+ expect(caller).toBeNull();+ expect(argumentsObject[0]).toBe(3);+ expect(Object.hasOwn(ordinary, "caller")).toBeFalse();+ expect(Object.hasOwn(ordinary, "arguments")).toBeFalse();+});- function getArgumentsDescriptor() {- return Reflect.getOwnPropertyDescriptor(getArgumentsDescriptor, "arguments");+test("own caller and arguments properties shadow the legacy accessors", () => {+ function ordinary() {+ return [ordinary.caller, ordinary.arguments];}- expect(- Reflect.defineProperty(getArgumentsDescriptor, "arguments", {- writable: false,- configurable: false,- })- ).toBeTrue();+ expect(Reflect.defineProperty(ordinary, "caller", { value: "own caller" })).toBeTrue();+ expect(Reflect.defineProperty(ordinary, "arguments", { value: "own arguments" })).toBeTrue();+ expect(ordinary()).toEqual(["own caller", "own arguments"]);+});++test("freezing a function keeps its legacy caller and arguments working", () => {+ function ordinary() {+ return ordinary.arguments;+ }- let argumentsDescriptor = Reflect.getOwnPropertyDescriptor(getArgumentsDescriptor, "arguments");- expect(argumentsDescriptor.value).toBeNull();- expect(getArgumentsDescriptor(1, 2, 3).value).toBe(argumentsDescriptor.value);+ Object.freeze(ordinary);+ expect(ordinary(1)[0]).toBe(1);+ expect(ordinary.arguments).toBeNull();});