Object.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/DeprecatedString.h>
  8. #include <AK/TypeCasts.h>
  9. #include <LibJS/Runtime/AbstractOperations.h>
  10. #include <LibJS/Runtime/Accessor.h>
  11. #include <LibJS/Runtime/Array.h>
  12. #include <LibJS/Runtime/ClassFieldDefinition.h>
  13. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  14. #include <LibJS/Runtime/Error.h>
  15. #include <LibJS/Runtime/GlobalObject.h>
  16. #include <LibJS/Runtime/NativeFunction.h>
  17. #include <LibJS/Runtime/Object.h>
  18. #include <LibJS/Runtime/PropertyDescriptor.h>
  19. #include <LibJS/Runtime/ProxyObject.h>
  20. #include <LibJS/Runtime/Shape.h>
  21. #include <LibJS/Runtime/Value.h>
  22. namespace JS {
  23. JS_DEFINE_ALLOCATOR(Object);
  24. static HashMap<GCPtr<Object const>, HashMap<DeprecatedFlyString, Object::IntrinsicAccessor>> s_intrinsics;
  25. // 10.1.12 OrdinaryObjectCreate ( proto [ , additionalInternalSlotsList ] ), https://tc39.es/ecma262/#sec-ordinaryobjectcreate
  26. NonnullGCPtr<Object> Object::create(Realm& realm, Object* prototype)
  27. {
  28. if (!prototype)
  29. return realm.heap().allocate<Object>(realm, realm.intrinsics().empty_object_shape());
  30. if (prototype == realm.intrinsics().object_prototype())
  31. return realm.heap().allocate<Object>(realm, realm.intrinsics().new_object_shape());
  32. return realm.heap().allocate<Object>(realm, ConstructWithPrototypeTag::Tag, *prototype);
  33. }
  34. Object::Object(GlobalObjectTag, Realm& realm, MayInterfereWithIndexedPropertyAccess may_interfere_with_indexed_property_access)
  35. : m_may_interfere_with_indexed_property_access(may_interfere_with_indexed_property_access == MayInterfereWithIndexedPropertyAccess::Yes)
  36. {
  37. // This is the global object
  38. m_shape = heap().allocate_without_realm<Shape>(realm);
  39. }
  40. Object::Object(ConstructWithoutPrototypeTag, Realm& realm, MayInterfereWithIndexedPropertyAccess may_interfere_with_indexed_property_access)
  41. : m_may_interfere_with_indexed_property_access(may_interfere_with_indexed_property_access == MayInterfereWithIndexedPropertyAccess::Yes)
  42. {
  43. m_shape = heap().allocate_without_realm<Shape>(realm);
  44. }
  45. Object::Object(Realm& realm, Object* prototype, MayInterfereWithIndexedPropertyAccess may_interfere_with_indexed_property_access)
  46. : m_may_interfere_with_indexed_property_access(may_interfere_with_indexed_property_access == MayInterfereWithIndexedPropertyAccess::Yes)
  47. {
  48. m_shape = realm.intrinsics().empty_object_shape();
  49. VERIFY(m_shape);
  50. if (prototype != nullptr)
  51. set_prototype(prototype);
  52. }
  53. Object::Object(ConstructWithPrototypeTag, Object& prototype, MayInterfereWithIndexedPropertyAccess may_interfere_with_indexed_property_access)
  54. : m_may_interfere_with_indexed_property_access(may_interfere_with_indexed_property_access == MayInterfereWithIndexedPropertyAccess::Yes)
  55. {
  56. m_shape = prototype.shape().realm().intrinsics().empty_object_shape();
  57. VERIFY(m_shape);
  58. set_prototype(&prototype);
  59. }
  60. Object::Object(Shape& shape, MayInterfereWithIndexedPropertyAccess may_interfere_with_indexed_property_access)
  61. : m_may_interfere_with_indexed_property_access(may_interfere_with_indexed_property_access == MayInterfereWithIndexedPropertyAccess::Yes)
  62. , m_shape(&shape)
  63. {
  64. m_storage.resize(shape.property_count());
  65. }
  66. Object::~Object()
  67. {
  68. if (m_has_intrinsic_accessors)
  69. s_intrinsics.remove(this);
  70. }
  71. void Object::initialize(Realm&)
  72. {
  73. }
  74. // 7.2 Testing and Comparison Operations, https://tc39.es/ecma262/#sec-testing-and-comparison-operations
  75. // 7.2.5 IsExtensible ( O ), https://tc39.es/ecma262/#sec-isextensible-o
  76. ThrowCompletionOr<bool> Object::is_extensible() const
  77. {
  78. // 1. Return ? O.[[IsExtensible]]().
  79. return internal_is_extensible();
  80. }
  81. // 7.3 Operations on Objects, https://tc39.es/ecma262/#sec-operations-on-objects
  82. // 7.3.2 Get ( O, P ), https://tc39.es/ecma262/#sec-get-o-p
  83. ThrowCompletionOr<Value> Object::get(PropertyKey const& property_key) const
  84. {
  85. VERIFY(property_key.is_valid());
  86. // 1. Return ? O.[[Get]](P, O).
  87. return TRY(internal_get(property_key, this));
  88. }
  89. // NOTE: 7.3.3 GetV ( V, P ) is implemented as Value::get().
  90. // 7.3.4 Set ( O, P, V, Throw ), https://tc39.es/ecma262/#sec-set-o-p-v-throw
  91. ThrowCompletionOr<void> Object::set(PropertyKey const& property_key, Value value, ShouldThrowExceptions throw_exceptions)
  92. {
  93. auto& vm = this->vm();
  94. VERIFY(property_key.is_valid());
  95. VERIFY(!value.is_empty());
  96. // 1. Let success be ? O.[[Set]](P, V, O).
  97. auto success = TRY(internal_set(property_key, value, this));
  98. // 2. If success is false and Throw is true, throw a TypeError exception.
  99. if (!success && throw_exceptions == ShouldThrowExceptions::Yes) {
  100. // FIXME: Improve/contextualize error message
  101. return vm.throw_completion<TypeError>(ErrorType::ObjectSetReturnedFalse);
  102. }
  103. // 3. Return unused.
  104. return {};
  105. }
  106. // 7.3.5 CreateDataProperty ( O, P, V ), https://tc39.es/ecma262/#sec-createdataproperty
  107. ThrowCompletionOr<bool> Object::create_data_property(PropertyKey const& property_key, Value value)
  108. {
  109. VERIFY(property_key.is_valid());
  110. // 1. Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
  111. auto new_descriptor = PropertyDescriptor {
  112. .value = value,
  113. .writable = true,
  114. .enumerable = true,
  115. .configurable = true,
  116. };
  117. // 2. Return ? O.[[DefineOwnProperty]](P, newDesc).
  118. return internal_define_own_property(property_key, new_descriptor);
  119. }
  120. // 7.3.6 CreateMethodProperty ( O, P, V ), https://tc39.es/ecma262/#sec-createmethodproperty
  121. void Object::create_method_property(PropertyKey const& property_key, Value value)
  122. {
  123. VERIFY(property_key.is_valid());
  124. VERIFY(!value.is_empty());
  125. // 1. Assert: O is an ordinary, extensible object with no non-configurable properties.
  126. // 2. Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }.
  127. auto new_descriptor = PropertyDescriptor {
  128. .value = value,
  129. .writable = true,
  130. .enumerable = false,
  131. .configurable = true,
  132. };
  133. // 3. Perform ! O.[[DefineOwnProperty]](P, newDesc).
  134. MUST(internal_define_own_property(property_key, new_descriptor));
  135. // 4. Return unused.
  136. }
  137. // 7.3.7 CreateDataPropertyOrThrow ( O, P, V ), https://tc39.es/ecma262/#sec-createdatapropertyorthrow
  138. ThrowCompletionOr<bool> Object::create_data_property_or_throw(PropertyKey const& property_key, Value value)
  139. {
  140. auto& vm = this->vm();
  141. VERIFY(property_key.is_valid());
  142. VERIFY(!value.is_empty());
  143. // 1. Let success be ? CreateDataProperty(O, P, V).
  144. auto success = TRY(create_data_property(property_key, value));
  145. // 2. If success is false, throw a TypeError exception.
  146. if (!success) {
  147. // FIXME: Improve/contextualize error message
  148. return vm.throw_completion<TypeError>(ErrorType::ObjectDefineOwnPropertyReturnedFalse);
  149. }
  150. // 3. Return success.
  151. return success;
  152. }
  153. // 7.3.8 CreateNonEnumerableDataPropertyOrThrow ( O, P, V ), https://tc39.es/ecma262/#sec-createnonenumerabledatapropertyorthrow
  154. void Object::create_non_enumerable_data_property_or_throw(PropertyKey const& property_key, Value value)
  155. {
  156. VERIFY(property_key.is_valid());
  157. VERIFY(!value.is_empty());
  158. // 1. Assert: O is an ordinary, extensible object with no non-configurable properties.
  159. // 2. Let newDesc be the PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }.
  160. auto new_description = PropertyDescriptor { .value = value, .writable = true, .enumerable = false, .configurable = true };
  161. // 3. Perform ! DefinePropertyOrThrow(O, P, newDesc).
  162. MUST(define_property_or_throw(property_key, new_description));
  163. // 4. Return unused.
  164. }
  165. // 7.3.9 DefinePropertyOrThrow ( O, P, desc ), https://tc39.es/ecma262/#sec-definepropertyorthrow
  166. ThrowCompletionOr<void> Object::define_property_or_throw(PropertyKey const& property_key, PropertyDescriptor const& property_descriptor)
  167. {
  168. auto& vm = this->vm();
  169. VERIFY(property_key.is_valid());
  170. // 1. Let success be ? O.[[DefineOwnProperty]](P, desc).
  171. auto success = TRY(internal_define_own_property(property_key, property_descriptor));
  172. // 2. If success is false, throw a TypeError exception.
  173. if (!success) {
  174. // FIXME: Improve/contextualize error message
  175. return vm.throw_completion<TypeError>(ErrorType::ObjectDefineOwnPropertyReturnedFalse);
  176. }
  177. // 3. Return unused.
  178. return {};
  179. }
  180. // 7.3.10 DeletePropertyOrThrow ( O, P ), https://tc39.es/ecma262/#sec-deletepropertyorthrow
  181. ThrowCompletionOr<void> Object::delete_property_or_throw(PropertyKey const& property_key)
  182. {
  183. auto& vm = this->vm();
  184. VERIFY(property_key.is_valid());
  185. // 1. Let success be ? O.[[Delete]](P).
  186. auto success = TRY(internal_delete(property_key));
  187. // 2. If success is false, throw a TypeError exception.
  188. if (!success) {
  189. // FIXME: Improve/contextualize error message
  190. return vm.throw_completion<TypeError>(ErrorType::ObjectDeleteReturnedFalse);
  191. }
  192. // 3. Return unused.
  193. return {};
  194. }
  195. // 7.3.12 HasProperty ( O, P ), https://tc39.es/ecma262/#sec-hasproperty
  196. ThrowCompletionOr<bool> Object::has_property(PropertyKey const& property_key) const
  197. {
  198. VERIFY(property_key.is_valid());
  199. // 1. Return ? O.[[HasProperty]](P).
  200. return internal_has_property(property_key);
  201. }
  202. // 7.3.13 HasOwnProperty ( O, P ), https://tc39.es/ecma262/#sec-hasownproperty
  203. ThrowCompletionOr<bool> Object::has_own_property(PropertyKey const& property_key) const
  204. {
  205. VERIFY(property_key.is_valid());
  206. // 1. Let desc be ? O.[[GetOwnProperty]](P).
  207. auto descriptor = TRY(internal_get_own_property(property_key));
  208. // 2. If desc is undefined, return false.
  209. if (!descriptor.has_value())
  210. return false;
  211. // 3. Return true.
  212. return true;
  213. }
  214. // 7.3.16 SetIntegrityLevel ( O, level ), https://tc39.es/ecma262/#sec-setintegritylevel
  215. ThrowCompletionOr<bool> Object::set_integrity_level(IntegrityLevel level)
  216. {
  217. auto& vm = this->vm();
  218. // 1. Let status be ? O.[[PreventExtensions]]().
  219. auto status = TRY(internal_prevent_extensions());
  220. // 2. If status is false, return false.
  221. if (!status)
  222. return false;
  223. // 3. Let keys be ? O.[[OwnPropertyKeys]]().
  224. auto keys = TRY(internal_own_property_keys());
  225. // 4. If level is sealed, then
  226. if (level == IntegrityLevel::Sealed) {
  227. // a. For each element k of keys, do
  228. for (auto& key : keys) {
  229. auto property_key = MUST(PropertyKey::from_value(vm, key));
  230. // i. Perform ? DefinePropertyOrThrow(O, k, PropertyDescriptor { [[Configurable]]: false }).
  231. TRY(define_property_or_throw(property_key, { .configurable = false }));
  232. }
  233. }
  234. // 5. Else,
  235. else {
  236. // a. Assert: level is frozen.
  237. // b. For each element k of keys, do
  238. for (auto& key : keys) {
  239. auto property_key = MUST(PropertyKey::from_value(vm, key));
  240. // i. Let currentDesc be ? O.[[GetOwnProperty]](k).
  241. auto current_descriptor = TRY(internal_get_own_property(property_key));
  242. // ii. If currentDesc is not undefined, then
  243. if (!current_descriptor.has_value())
  244. continue;
  245. PropertyDescriptor descriptor;
  246. // 1. If IsAccessorDescriptor(currentDesc) is true, then
  247. if (current_descriptor->is_accessor_descriptor()) {
  248. // a. Let desc be the PropertyDescriptor { [[Configurable]]: false }.
  249. descriptor = { .configurable = false };
  250. }
  251. // 2. Else,
  252. else {
  253. // a. Let desc be the PropertyDescriptor { [[Configurable]]: false, [[Writable]]: false }.
  254. descriptor = { .writable = false, .configurable = false };
  255. }
  256. // 3. Perform ? DefinePropertyOrThrow(O, k, desc).
  257. TRY(define_property_or_throw(property_key, descriptor));
  258. }
  259. }
  260. // 6. Return true.
  261. return true;
  262. }
  263. // 7.3.17 TestIntegrityLevel ( O, level ), https://tc39.es/ecma262/#sec-testintegritylevel
  264. ThrowCompletionOr<bool> Object::test_integrity_level(IntegrityLevel level) const
  265. {
  266. auto& vm = this->vm();
  267. // 1. Let extensible be ? IsExtensible(O).
  268. auto extensible = TRY(is_extensible());
  269. // 2. If extensible is true, return false.
  270. // 3. NOTE: If the object is extensible, none of its properties are examined.
  271. if (extensible)
  272. return false;
  273. // 4. Let keys be ? O.[[OwnPropertyKeys]]().
  274. auto keys = TRY(internal_own_property_keys());
  275. // 5. For each element k of keys, do
  276. for (auto& key : keys) {
  277. auto property_key = MUST(PropertyKey::from_value(vm, key));
  278. // a. Let currentDesc be ? O.[[GetOwnProperty]](k).
  279. auto current_descriptor = TRY(internal_get_own_property(property_key));
  280. // b. If currentDesc is not undefined, then
  281. if (!current_descriptor.has_value())
  282. continue;
  283. // i. If currentDesc.[[Configurable]] is true, return false.
  284. if (*current_descriptor->configurable)
  285. return false;
  286. // ii. If level is frozen and IsDataDescriptor(currentDesc) is true, then
  287. if (level == IntegrityLevel::Frozen && current_descriptor->is_data_descriptor()) {
  288. // 1. If currentDesc.[[Writable]] is true, return false.
  289. if (*current_descriptor->writable)
  290. return false;
  291. }
  292. }
  293. // 6. Return true.
  294. return true;
  295. }
  296. // 7.3.24 EnumerableOwnPropertyNames ( O, kind ), https://tc39.es/ecma262/#sec-enumerableownpropertynames
  297. ThrowCompletionOr<MarkedVector<Value>> Object::enumerable_own_property_names(PropertyKind kind) const
  298. {
  299. // NOTE: This has been flattened for readability, so some `else` branches in the
  300. // spec text have been replaced with `continue`s in the loop below.
  301. auto& vm = this->vm();
  302. auto& realm = *vm.current_realm();
  303. // 1. Let ownKeys be ? O.[[OwnPropertyKeys]]().
  304. auto own_keys = TRY(internal_own_property_keys());
  305. // 2. Let properties be a new empty List.
  306. auto properties = MarkedVector<Value> { heap() };
  307. // 3. For each element key of ownKeys, do
  308. for (auto& key : own_keys) {
  309. // a. If Type(key) is String, then
  310. if (!key.is_string())
  311. continue;
  312. auto property_key = MUST(PropertyKey::from_value(vm, key));
  313. // i. Let desc be ? O.[[GetOwnProperty]](key).
  314. auto descriptor = TRY(internal_get_own_property(property_key));
  315. // ii. If desc is not undefined and desc.[[Enumerable]] is true, then
  316. if (descriptor.has_value() && *descriptor->enumerable) {
  317. // 1. If kind is key, append key to properties.
  318. if (kind == PropertyKind::Key) {
  319. properties.append(key);
  320. continue;
  321. }
  322. // 2. Else,
  323. // a. Let value be ? Get(O, key).
  324. auto value = TRY(get(property_key));
  325. // b. If kind is value, append value to properties.
  326. if (kind == PropertyKind::Value) {
  327. properties.append(value);
  328. continue;
  329. }
  330. // c. Else,
  331. // i. Assert: kind is key+value.
  332. VERIFY(kind == PropertyKind::KeyAndValue);
  333. // ii. Let entry be CreateArrayFromList(« key, value »).
  334. auto entry = Array::create_from(realm, { key, value });
  335. // iii. Append entry to properties.
  336. properties.append(entry);
  337. }
  338. }
  339. // 4. Return properties.
  340. return { move(properties) };
  341. }
  342. // 7.3.26 CopyDataProperties ( target, source, excludedItems ), https://tc39.es/ecma262/#sec-copydataproperties
  343. ThrowCompletionOr<void> Object::copy_data_properties(VM& vm, Value source, HashTable<PropertyKey> const& seen_names)
  344. {
  345. // 1. If source is either undefined or null, return unused.
  346. if (source.is_nullish())
  347. return {};
  348. // 2. Let from be ! ToObject(source).
  349. auto from = MUST(source.to_object(vm));
  350. // 3. Let keys be ? from.[[OwnPropertyKeys]]().
  351. auto keys = TRY(from->internal_own_property_keys());
  352. // 4. For each element nextKey of keys, do
  353. for (auto& next_key_value : keys) {
  354. auto next_key = MUST(PropertyKey::from_value(vm, next_key_value));
  355. // a. Let excluded be false.
  356. // b. For each element e of excludedItems, do
  357. // i. If SameValue(e, nextKey) is true, then
  358. // 1. Set excluded to true.
  359. if (seen_names.contains(next_key))
  360. continue;
  361. // c. If excluded is false, then
  362. // i. Let desc be ? from.[[GetOwnProperty]](nextKey).
  363. auto desc = TRY(from->internal_get_own_property(next_key));
  364. // ii. If desc is not undefined and desc.[[Enumerable]] is true, then
  365. if (desc.has_value() && desc->attributes().is_enumerable()) {
  366. // 1. Let propValue be ? Get(from, nextKey).
  367. auto prop_value = TRY(from->get(next_key));
  368. // 2. Perform ! CreateDataPropertyOrThrow(target, nextKey, propValue).
  369. MUST(create_data_property_or_throw(next_key, prop_value));
  370. }
  371. }
  372. // 5. Return unused.
  373. return {};
  374. }
  375. // 7.3.27 PrivateElementFind ( O, P ), https://tc39.es/ecma262/#sec-privateelementfind
  376. PrivateElement* Object::private_element_find(PrivateName const& name)
  377. {
  378. if (!m_private_elements)
  379. return nullptr;
  380. // 1. If O.[[PrivateElements]] contains a PrivateElement pe such that pe.[[Key]] is P, then
  381. auto it = m_private_elements->find_if([&](auto const& element) {
  382. return element.key == name;
  383. });
  384. if (!it.is_end()) {
  385. // a. Return pe.
  386. return &(*it);
  387. }
  388. // 2. Return empty.
  389. return nullptr;
  390. }
  391. // 7.3.28 PrivateFieldAdd ( O, P, value ), https://tc39.es/ecma262/#sec-privatefieldadd
  392. ThrowCompletionOr<void> Object::private_field_add(PrivateName const& name, Value value)
  393. {
  394. auto& vm = this->vm();
  395. // 1. If the host is a web browser, then
  396. // a. Perform ? HostEnsureCanAddPrivateElement(O).
  397. // NOTE: Since LibJS has no way of knowing whether it is in a browser we just always call the hook.
  398. TRY(vm.host_ensure_can_add_private_element(*this));
  399. // 2. Let entry be PrivateElementFind(O, P).
  400. // 3. If entry is not empty, throw a TypeError exception.
  401. if (auto* entry = private_element_find(name); entry)
  402. return vm.throw_completion<TypeError>(ErrorType::PrivateFieldAlreadyDeclared, name.description);
  403. if (!m_private_elements)
  404. m_private_elements = make<Vector<PrivateElement>>();
  405. // 4. Append PrivateElement { [[Key]]: P, [[Kind]]: field, [[Value]]: value } to O.[[PrivateElements]].
  406. m_private_elements->empend(name, PrivateElement::Kind::Field, make_handle(value));
  407. // 5. Return unused.
  408. return {};
  409. }
  410. // 7.3.29 PrivateMethodOrAccessorAdd ( O, method ), https://tc39.es/ecma262/#sec-privatemethodoraccessoradd
  411. ThrowCompletionOr<void> Object::private_method_or_accessor_add(PrivateElement element)
  412. {
  413. auto& vm = this->vm();
  414. // 1. Assert: method.[[Kind]] is either method or accessor.
  415. VERIFY(element.kind == PrivateElement::Kind::Method || element.kind == PrivateElement::Kind::Accessor);
  416. // 2. If the host is a web browser, then
  417. // a. Perform ? HostEnsureCanAddPrivateElement(O).
  418. // NOTE: Since LibJS has no way of knowing whether it is in a browser we just always call the hook.
  419. TRY(vm.host_ensure_can_add_private_element(*this));
  420. // 3. Let entry be PrivateElementFind(O, method.[[Key]]).
  421. // 4. If entry is not empty, throw a TypeError exception.
  422. if (auto* entry = private_element_find(element.key); entry)
  423. return vm.throw_completion<TypeError>(ErrorType::PrivateFieldAlreadyDeclared, element.key.description);
  424. if (!m_private_elements)
  425. m_private_elements = make<Vector<PrivateElement>>();
  426. // 5. Append method to O.[[PrivateElements]].
  427. m_private_elements->append(move(element));
  428. // 6. Return unused.
  429. return {};
  430. }
  431. // 7.3.31 PrivateGet ( O, P ), https://tc39.es/ecma262/#sec-privateget
  432. ThrowCompletionOr<Value> Object::private_get(PrivateName const& name)
  433. {
  434. auto& vm = this->vm();
  435. // 1. Let entry be PrivateElementFind(O, P).
  436. auto* entry = private_element_find(name);
  437. // 2. If entry is empty, throw a TypeError exception.
  438. if (!entry)
  439. return vm.throw_completion<TypeError>(ErrorType::PrivateFieldDoesNotExistOnObject, name.description);
  440. auto& value = entry->value;
  441. // 3. If entry.[[Kind]] is either field or method, then
  442. if (entry->kind != PrivateElement::Kind::Accessor) {
  443. // a. Return entry.[[Value]].
  444. return value.value();
  445. }
  446. // Assert: entry.[[Kind]] is accessor.
  447. VERIFY(value.value().is_accessor());
  448. // 6. Let getter be entry.[[Get]].
  449. auto* getter = value.value().as_accessor().getter();
  450. // 5. If entry.[[Get]] is undefined, throw a TypeError exception.
  451. if (!getter)
  452. return vm.throw_completion<TypeError>(ErrorType::PrivateFieldGetAccessorWithoutGetter, name.description);
  453. // 7. Return ? Call(getter, O).
  454. return TRY(call(vm, *getter, this));
  455. }
  456. // 7.3.32 PrivateSet ( O, P, value ), https://tc39.es/ecma262/#sec-privateset
  457. ThrowCompletionOr<void> Object::private_set(PrivateName const& name, Value value)
  458. {
  459. auto& vm = this->vm();
  460. // 1. Let entry be PrivateElementFind(O, P).
  461. auto* entry = private_element_find(name);
  462. // 2. If entry is empty, throw a TypeError exception.
  463. if (!entry)
  464. return vm.throw_completion<TypeError>(ErrorType::PrivateFieldDoesNotExistOnObject, name.description);
  465. // 3. If entry.[[Kind]] is field, then
  466. if (entry->kind == PrivateElement::Kind::Field) {
  467. // a. Set entry.[[Value]] to value.
  468. entry->value = make_handle(value);
  469. return {};
  470. }
  471. // 4. Else if entry.[[Kind]] is method, then
  472. else if (entry->kind == PrivateElement::Kind::Method) {
  473. // a. Throw a TypeError exception.
  474. return vm.throw_completion<TypeError>(ErrorType::PrivateFieldSetMethod, name.description);
  475. }
  476. // 5. Else,
  477. // a. Assert: entry.[[Kind]] is accessor.
  478. VERIFY(entry->kind == PrivateElement::Kind::Accessor);
  479. auto& accessor = entry->value;
  480. VERIFY(accessor.value().is_accessor());
  481. // c. Let setter be entry.[[Set]].
  482. auto* setter = accessor.value().as_accessor().setter();
  483. // b. If entry.[[Set]] is undefined, throw a TypeError exception.
  484. if (!setter)
  485. return vm.throw_completion<TypeError>(ErrorType::PrivateFieldSetAccessorWithoutSetter, name.description);
  486. // d. Perform ? Call(setter, O, « value »).
  487. TRY(call(vm, *setter, this, value));
  488. // 6. Return unused.
  489. return {};
  490. }
  491. // 7.3.33 DefineField ( receiver, fieldRecord ), https://tc39.es/ecma262/#sec-definefield
  492. ThrowCompletionOr<void> Object::define_field(ClassFieldDefinition const& field)
  493. {
  494. auto& vm = this->vm();
  495. // 1. Let fieldName be fieldRecord.[[Name]].
  496. auto const& field_name = field.name;
  497. // 2. Let initializer be fieldRecord.[[Initializer]].
  498. auto const& initializer = field.initializer;
  499. auto init_value = js_undefined();
  500. // 3. If initializer is not empty, then
  501. if (!initializer.is_null()) {
  502. // a. Let initValue be ? Call(initializer, receiver).
  503. init_value = TRY(call(vm, initializer.cell(), this));
  504. }
  505. // 4. Else, let initValue be undefined.
  506. // 5. If fieldName is a Private Name, then
  507. if (field_name.has<PrivateName>()) {
  508. // a. Perform ? PrivateFieldAdd(receiver, fieldName, initValue).
  509. TRY(private_field_add(field_name.get<PrivateName>(), init_value));
  510. }
  511. // 6. Else,
  512. else {
  513. // a. Assert: IsPropertyKey(fieldName) is true.
  514. // b. Perform ? CreateDataPropertyOrThrow(receiver, fieldName, initValue).
  515. TRY(create_data_property_or_throw(field_name.get<PropertyKey>(), init_value));
  516. }
  517. // 7. Return unused.
  518. return {};
  519. }
  520. // 7.3.34 InitializeInstanceElements ( O, constructor ), https://tc39.es/ecma262/#sec-initializeinstanceelements
  521. ThrowCompletionOr<void> Object::initialize_instance_elements(ECMAScriptFunctionObject& constructor)
  522. {
  523. // 1. Let methods be the value of constructor.[[PrivateMethods]].
  524. // 2. For each PrivateElement method of methods, do
  525. for (auto const& method : constructor.private_methods()) {
  526. // a. Perform ? PrivateMethodOrAccessorAdd(O, method).
  527. TRY(private_method_or_accessor_add(method));
  528. }
  529. // 3. Let fields be the value of constructor.[[Fields]].
  530. // 4. For each element fieldRecord of fields, do
  531. for (auto const& field : constructor.fields()) {
  532. // a. Perform ? DefineField(O, fieldRecord).
  533. TRY(define_field(field));
  534. }
  535. // 5. Return unused.
  536. return {};
  537. }
  538. // 10.1 Ordinary Object Internal Methods and Internal Slots, https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
  539. // 10.1.1 [[GetPrototypeOf]] ( ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-getprototypeof
  540. ThrowCompletionOr<Object*> Object::internal_get_prototype_of() const
  541. {
  542. // 1. Return O.[[Prototype]].
  543. return const_cast<Object*>(prototype());
  544. }
  545. // 10.1.2 [[SetPrototypeOf]] ( V ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-setprototypeof-v
  546. ThrowCompletionOr<bool> Object::internal_set_prototype_of(Object* new_prototype)
  547. {
  548. // 1. Let current be O.[[Prototype]].
  549. // 2. If SameValue(V, current) is true, return true.
  550. if (prototype() == new_prototype)
  551. return true;
  552. // 3. Let extensible be O.[[Extensible]].
  553. // 4. If extensible is false, return false.
  554. if (!m_is_extensible)
  555. return false;
  556. // 5. Let p be V.
  557. auto* prototype = new_prototype;
  558. // 6. Let done be false.
  559. // 7. Repeat, while done is false,
  560. while (prototype) {
  561. // a. If p is null, set done to true.
  562. // b. Else if SameValue(p, O) is true, return false.
  563. if (prototype == this)
  564. return false;
  565. // c. Else,
  566. // i. If p.[[GetPrototypeOf]] is not the ordinary object internal method defined in 10.1.1, set done to true.
  567. // NOTE: This is a best-effort implementation; we don't have a good way of detecting whether certain virtual
  568. // Object methods have been overridden by a given object, but as ProxyObject is the only one doing that for
  569. // [[SetPrototypeOf]], this check does the trick.
  570. if (is<ProxyObject>(prototype))
  571. break;
  572. // ii. Else, set p to p.[[Prototype]].
  573. prototype = prototype->prototype();
  574. }
  575. // 8. Set O.[[Prototype]] to V.
  576. set_prototype(new_prototype);
  577. // 9. Return true.
  578. return true;
  579. }
  580. // 10.1.3 [[IsExtensible]] ( ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-isextensible
  581. ThrowCompletionOr<bool> Object::internal_is_extensible() const
  582. {
  583. // 1. Return O.[[Extensible]].
  584. return m_is_extensible;
  585. }
  586. // 10.1.4 [[PreventExtensions]] ( ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-preventextensions
  587. ThrowCompletionOr<bool> Object::internal_prevent_extensions()
  588. {
  589. // 1. Set O.[[Extensible]] to false.
  590. m_is_extensible = false;
  591. // 2. Return true.
  592. return true;
  593. }
  594. // 10.1.5 [[GetOwnProperty]] ( P ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-getownproperty-p
  595. ThrowCompletionOr<Optional<PropertyDescriptor>> Object::internal_get_own_property(PropertyKey const& property_key) const
  596. {
  597. VERIFY(property_key.is_valid());
  598. // 1. If O does not have an own property with key P, return undefined.
  599. auto maybe_storage_entry = storage_get(property_key);
  600. if (!maybe_storage_entry.has_value())
  601. return Optional<PropertyDescriptor> {};
  602. // 2. Let D be a newly created Property Descriptor with no fields.
  603. PropertyDescriptor descriptor;
  604. // 3. Let X be O's own property whose key is P.
  605. auto [value, attributes, property_offset] = *maybe_storage_entry;
  606. // 4. If X is a data property, then
  607. if (!value.is_accessor()) {
  608. // a. Set D.[[Value]] to the value of X's [[Value]] attribute.
  609. descriptor.value = value.value_or(js_undefined());
  610. // b. Set D.[[Writable]] to the value of X's [[Writable]] attribute.
  611. descriptor.writable = attributes.is_writable();
  612. }
  613. // 5. Else,
  614. else {
  615. // a. Assert: X is an accessor property.
  616. // b. Set D.[[Get]] to the value of X's [[Get]] attribute.
  617. descriptor.get = value.as_accessor().getter();
  618. // c. Set D.[[Set]] to the value of X's [[Set]] attribute.
  619. descriptor.set = value.as_accessor().setter();
  620. }
  621. // 6. Set D.[[Enumerable]] to the value of X's [[Enumerable]] attribute.
  622. descriptor.enumerable = attributes.is_enumerable();
  623. // 7. Set D.[[Configurable]] to the value of X's [[Configurable]] attribute.
  624. descriptor.configurable = attributes.is_configurable();
  625. // Non-standard: Add the property offset to the descriptor. This is used to populate CacheablePropertyMetadata.
  626. descriptor.property_offset = property_offset;
  627. // 8. Return D.
  628. return descriptor;
  629. }
  630. // 10.1.6 [[DefineOwnProperty]] ( P, Desc ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc
  631. ThrowCompletionOr<bool> Object::internal_define_own_property(PropertyKey const& property_key, PropertyDescriptor const& property_descriptor)
  632. {
  633. VERIFY(property_key.is_valid());
  634. // 1. Let current be ? O.[[GetOwnProperty]](P).
  635. auto current = TRY(internal_get_own_property(property_key));
  636. // 2. Let extensible be ? IsExtensible(O).
  637. auto extensible = TRY(is_extensible());
  638. // 3. Return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current).
  639. return validate_and_apply_property_descriptor(this, property_key, extensible, property_descriptor, current);
  640. }
  641. // 10.1.7 [[HasProperty]] ( P ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-hasproperty-p
  642. ThrowCompletionOr<bool> Object::internal_has_property(PropertyKey const& property_key) const
  643. {
  644. VERIFY(property_key.is_valid());
  645. // 1. Let hasOwn be ? O.[[GetOwnProperty]](P).
  646. auto has_own = TRY(internal_get_own_property(property_key));
  647. // 2. If hasOwn is not undefined, return true.
  648. if (has_own.has_value())
  649. return true;
  650. // 3. Let parent be ? O.[[GetPrototypeOf]]().
  651. auto* parent = TRY(internal_get_prototype_of());
  652. // 4. If parent is not null, then
  653. if (parent) {
  654. // a. Return ? parent.[[HasProperty]](P).
  655. return parent->internal_has_property(property_key);
  656. }
  657. // 5. Return false.
  658. return false;
  659. }
  660. // 10.1.8 [[Get]] ( P, Receiver ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-get-p-receiver
  661. ThrowCompletionOr<Value> Object::internal_get(PropertyKey const& property_key, Value receiver, CacheablePropertyMetadata* cacheable_metadata) const
  662. {
  663. VERIFY(!receiver.is_empty());
  664. VERIFY(property_key.is_valid());
  665. auto& vm = this->vm();
  666. // 1. Let desc be ? O.[[GetOwnProperty]](P).
  667. auto descriptor = TRY(internal_get_own_property(property_key));
  668. // 2. If desc is undefined, then
  669. if (!descriptor.has_value()) {
  670. // a. Let parent be ? O.[[GetPrototypeOf]]().
  671. auto* parent = TRY(internal_get_prototype_of());
  672. // b. If parent is null, return undefined.
  673. if (!parent)
  674. return js_undefined();
  675. // c. Return ? parent.[[Get]](P, Receiver).
  676. return parent->internal_get(property_key, receiver);
  677. }
  678. // 3. If IsDataDescriptor(desc) is true, return desc.[[Value]].
  679. if (descriptor->is_data_descriptor()) {
  680. // Non-standard: If the caller has requested cacheable metadata and the property is an own property, fill it in.
  681. if (cacheable_metadata && descriptor->property_offset.has_value()) {
  682. *cacheable_metadata = CacheablePropertyMetadata {
  683. .type = CacheablePropertyMetadata::Type::OwnProperty,
  684. .property_offset = descriptor->property_offset.value(),
  685. };
  686. }
  687. return *descriptor->value;
  688. }
  689. // 4. Assert: IsAccessorDescriptor(desc) is true.
  690. VERIFY(descriptor->is_accessor_descriptor());
  691. // 5. Let getter be desc.[[Get]].
  692. auto getter = *descriptor->get;
  693. // 6. If getter is undefined, return undefined.
  694. if (!getter)
  695. return js_undefined();
  696. // 7. Return ? Call(getter, Receiver).
  697. return TRY(call(vm, *getter, receiver));
  698. }
  699. // 10.1.9 [[Set]] ( P, V, Receiver ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  700. ThrowCompletionOr<bool> Object::internal_set(PropertyKey const& property_key, Value value, Value receiver, CacheablePropertyMetadata* cacheable_metadata)
  701. {
  702. VERIFY(property_key.is_valid());
  703. VERIFY(!value.is_empty());
  704. VERIFY(!receiver.is_empty());
  705. // 2. Let ownDesc be ? O.[[GetOwnProperty]](P).
  706. auto own_descriptor = TRY(internal_get_own_property(property_key));
  707. // 3. Return ? OrdinarySetWithOwnDescriptor(O, P, V, Receiver, ownDesc).
  708. return ordinary_set_with_own_descriptor(property_key, value, receiver, own_descriptor, cacheable_metadata);
  709. }
  710. // 10.1.9.2 OrdinarySetWithOwnDescriptor ( O, P, V, Receiver, ownDesc ), https://tc39.es/ecma262/#sec-ordinarysetwithowndescriptor
  711. ThrowCompletionOr<bool> Object::ordinary_set_with_own_descriptor(PropertyKey const& property_key, Value value, Value receiver, Optional<PropertyDescriptor> own_descriptor, CacheablePropertyMetadata* cacheable_metadata)
  712. {
  713. VERIFY(property_key.is_valid());
  714. VERIFY(!value.is_empty());
  715. VERIFY(!receiver.is_empty());
  716. auto& vm = this->vm();
  717. // 1. If ownDesc is undefined, then
  718. if (!own_descriptor.has_value()) {
  719. // a. Let parent be ? O.[[GetPrototypeOf]]().
  720. auto* parent = TRY(internal_get_prototype_of());
  721. // b. If parent is not null, then
  722. if (parent) {
  723. // i. Return ? parent.[[Set]](P, V, Receiver).
  724. return TRY(parent->internal_set(property_key, value, receiver));
  725. }
  726. // c. Else,
  727. else {
  728. // i. Set ownDesc to the PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
  729. own_descriptor = PropertyDescriptor {
  730. .value = js_undefined(),
  731. .writable = true,
  732. .enumerable = true,
  733. .configurable = true,
  734. };
  735. }
  736. }
  737. // 2. If IsDataDescriptor(ownDesc) is true, then
  738. if (own_descriptor->is_data_descriptor()) {
  739. // a. If ownDesc.[[Writable]] is false, return false.
  740. if (!*own_descriptor->writable)
  741. return false;
  742. // b. If Type(Receiver) is not Object, return false.
  743. if (!receiver.is_object())
  744. return false;
  745. // c. Let existingDescriptor be ? Receiver.[[GetOwnProperty]](P).
  746. auto existing_descriptor = TRY(receiver.as_object().internal_get_own_property(property_key));
  747. // d. If existingDescriptor is not undefined, then
  748. if (existing_descriptor.has_value()) {
  749. // i. If IsAccessorDescriptor(existingDescriptor) is true, return false.
  750. if (existing_descriptor->is_accessor_descriptor())
  751. return false;
  752. // ii. If existingDescriptor.[[Writable]] is false, return false.
  753. if (!*existing_descriptor->writable)
  754. return false;
  755. // iii. Let valueDesc be the PropertyDescriptor { [[Value]]: V }.
  756. auto value_descriptor = PropertyDescriptor { .value = value };
  757. if (cacheable_metadata && own_descriptor.has_value() && own_descriptor->property_offset.has_value()) {
  758. *cacheable_metadata = CacheablePropertyMetadata {
  759. .type = CacheablePropertyMetadata::Type::OwnProperty,
  760. .property_offset = own_descriptor->property_offset.value(),
  761. };
  762. }
  763. // iv. Return ? Receiver.[[DefineOwnProperty]](P, valueDesc).
  764. return TRY(receiver.as_object().internal_define_own_property(property_key, value_descriptor));
  765. }
  766. // e. Else,
  767. else {
  768. // i. Assert: Receiver does not currently have a property P.
  769. VERIFY(!receiver.as_object().storage_has(property_key));
  770. // ii. Return ? CreateDataProperty(Receiver, P, V).
  771. return TRY(receiver.as_object().create_data_property(property_key, value));
  772. }
  773. }
  774. // 3. Assert: IsAccessorDescriptor(ownDesc) is true.
  775. VERIFY(own_descriptor->is_accessor_descriptor());
  776. // 4. Let setter be ownDesc.[[Set]].
  777. auto setter = *own_descriptor->set;
  778. // 5. If setter is undefined, return false.
  779. if (!setter)
  780. return false;
  781. // 6. Perform ? Call(setter, Receiver, « V »).
  782. (void)TRY(call(vm, *setter, receiver, value));
  783. // 7. Return true.
  784. return true;
  785. }
  786. // 10.1.10 [[Delete]] ( P ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-delete-p
  787. ThrowCompletionOr<bool> Object::internal_delete(PropertyKey const& property_key)
  788. {
  789. VERIFY(property_key.is_valid());
  790. // 1. Let desc be ? O.[[GetOwnProperty]](P).
  791. auto descriptor = TRY(internal_get_own_property(property_key));
  792. // 2. If desc is undefined, return true.
  793. if (!descriptor.has_value())
  794. return true;
  795. // 3. If desc.[[Configurable]] is true, then
  796. if (*descriptor->configurable) {
  797. // a. Remove the own property with name P from O.
  798. storage_delete(property_key);
  799. // b. Return true.
  800. return true;
  801. }
  802. // 4. Return false.
  803. return false;
  804. }
  805. // 10.1.11 [[OwnPropertyKeys]] ( ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys
  806. ThrowCompletionOr<MarkedVector<Value>> Object::internal_own_property_keys() const
  807. {
  808. auto& vm = this->vm();
  809. // 1. Let keys be a new empty List.
  810. MarkedVector<Value> keys { heap() };
  811. // 2. For each own property key P of O such that P is an array index, in ascending numeric index order, do
  812. for (auto& entry : m_indexed_properties) {
  813. // a. Add P as the last element of keys.
  814. keys.append(PrimitiveString::create(vm, DeprecatedString::number(entry.index())));
  815. }
  816. // 3. For each own property key P of O such that Type(P) is String and P is not an array index, in ascending chronological order of property creation, do
  817. for (auto& it : shape().property_table()) {
  818. if (it.key.is_string()) {
  819. // a. Add P as the last element of keys.
  820. keys.append(it.key.to_value(vm));
  821. }
  822. }
  823. // 4. For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property creation, do
  824. for (auto& it : shape().property_table()) {
  825. if (it.key.is_symbol()) {
  826. // a. Add P as the last element of keys.
  827. keys.append(it.key.to_value(vm));
  828. }
  829. }
  830. // 5. Return keys.
  831. return { move(keys) };
  832. }
  833. // 10.4.7.2 SetImmutablePrototype ( O, V ), https://tc39.es/ecma262/#sec-set-immutable-prototype
  834. ThrowCompletionOr<bool> Object::set_immutable_prototype(Object* prototype)
  835. {
  836. // 1. Let current be ? O.[[GetPrototypeOf]]().
  837. auto* current = TRY(internal_get_prototype_of());
  838. // 2. If SameValue(V, current) is true, return true.
  839. if (prototype == current)
  840. return true;
  841. // 3. Return false.
  842. return false;
  843. }
  844. static Optional<Object::IntrinsicAccessor> find_intrinsic_accessor(Object const* object, PropertyKey const& property_key)
  845. {
  846. if (!property_key.is_string())
  847. return {};
  848. auto intrinsics = s_intrinsics.find(object);
  849. if (intrinsics == s_intrinsics.end())
  850. return {};
  851. auto accessor_iterator = intrinsics->value.find(property_key.as_string());
  852. if (accessor_iterator == intrinsics->value.end())
  853. return {};
  854. auto accessor = accessor_iterator->value;
  855. intrinsics->value.remove(accessor_iterator);
  856. return accessor;
  857. }
  858. Optional<ValueAndAttributes> Object::storage_get(PropertyKey const& property_key) const
  859. {
  860. VERIFY(property_key.is_valid());
  861. Value value;
  862. PropertyAttributes attributes;
  863. Optional<u32> property_offset;
  864. if (property_key.is_number()) {
  865. auto value_and_attributes = m_indexed_properties.get(property_key.as_number());
  866. if (!value_and_attributes.has_value())
  867. return {};
  868. value = value_and_attributes->value;
  869. attributes = value_and_attributes->attributes;
  870. } else {
  871. auto metadata = shape().lookup(property_key.to_string_or_symbol());
  872. if (!metadata.has_value())
  873. return {};
  874. if (m_has_intrinsic_accessors) {
  875. if (auto accessor = find_intrinsic_accessor(this, property_key); accessor.has_value())
  876. const_cast<Object&>(*this).m_storage[metadata->offset] = (*accessor)(shape().realm());
  877. }
  878. value = m_storage[metadata->offset];
  879. attributes = metadata->attributes;
  880. property_offset = metadata->offset;
  881. }
  882. return ValueAndAttributes { .value = value, .attributes = attributes, .property_offset = property_offset };
  883. }
  884. bool Object::storage_has(PropertyKey const& property_key) const
  885. {
  886. VERIFY(property_key.is_valid());
  887. if (property_key.is_number())
  888. return m_indexed_properties.has_index(property_key.as_number());
  889. return shape().lookup(property_key.to_string_or_symbol()).has_value();
  890. }
  891. void Object::storage_set(PropertyKey const& property_key, ValueAndAttributes const& value_and_attributes)
  892. {
  893. VERIFY(property_key.is_valid());
  894. auto [value, attributes, _] = value_and_attributes;
  895. if (property_key.is_number()) {
  896. auto index = property_key.as_number();
  897. m_indexed_properties.put(index, value, attributes);
  898. return;
  899. }
  900. if (m_has_intrinsic_accessors && property_key.is_string()) {
  901. if (auto intrinsics = s_intrinsics.find(this); intrinsics != s_intrinsics.end())
  902. intrinsics->value.remove(property_key.as_string());
  903. }
  904. auto property_key_string_or_symbol = property_key.to_string_or_symbol();
  905. auto metadata = shape().lookup(property_key_string_or_symbol);
  906. if (!metadata.has_value()) {
  907. if (!m_shape->is_unique() && shape().property_count() > 100) {
  908. // If you add more than 100 properties to an object, let's stop doing
  909. // transitions to avoid filling up the heap with shapes.
  910. ensure_shape_is_unique();
  911. }
  912. if (m_shape->is_unique())
  913. m_shape->add_property_to_unique_shape(property_key_string_or_symbol, attributes);
  914. else
  915. set_shape(*m_shape->create_put_transition(property_key_string_or_symbol, attributes));
  916. m_storage.append(value);
  917. return;
  918. }
  919. if (attributes != metadata->attributes) {
  920. if (m_shape->is_unique())
  921. m_shape->reconfigure_property_in_unique_shape(property_key_string_or_symbol, attributes);
  922. else
  923. set_shape(*m_shape->create_configure_transition(property_key_string_or_symbol, attributes));
  924. }
  925. m_storage[metadata->offset] = value;
  926. }
  927. void Object::storage_delete(PropertyKey const& property_key)
  928. {
  929. VERIFY(property_key.is_valid());
  930. VERIFY(storage_has(property_key));
  931. if (property_key.is_number())
  932. return m_indexed_properties.remove(property_key.as_number());
  933. if (m_has_intrinsic_accessors && property_key.is_string()) {
  934. if (auto intrinsics = s_intrinsics.find(this); intrinsics != s_intrinsics.end())
  935. intrinsics->value.remove(property_key.as_string());
  936. }
  937. auto metadata = shape().lookup(property_key.to_string_or_symbol());
  938. VERIFY(metadata.has_value());
  939. ensure_shape_is_unique();
  940. shape().remove_property_from_unique_shape(property_key.to_string_or_symbol(), metadata->offset);
  941. m_storage.remove(metadata->offset);
  942. }
  943. void Object::set_prototype(Object* new_prototype)
  944. {
  945. if (prototype() == new_prototype)
  946. return;
  947. auto& shape = this->shape();
  948. if (shape.is_unique())
  949. shape.set_prototype_without_transition(new_prototype);
  950. else
  951. m_shape = shape.create_prototype_transition(new_prototype);
  952. }
  953. void Object::define_native_accessor(Realm& realm, PropertyKey const& property_key, Function<ThrowCompletionOr<Value>(VM&)> getter, Function<ThrowCompletionOr<Value>(VM&)> setter, PropertyAttributes attribute)
  954. {
  955. FunctionObject* getter_function = nullptr;
  956. if (getter)
  957. getter_function = NativeFunction::create(realm, move(getter), 0, property_key, &realm, {}, "get"sv);
  958. FunctionObject* setter_function = nullptr;
  959. if (setter)
  960. setter_function = NativeFunction::create(realm, move(setter), 1, property_key, &realm, {}, "set"sv);
  961. return define_direct_accessor(property_key, getter_function, setter_function, attribute);
  962. }
  963. void Object::define_direct_accessor(PropertyKey const& property_key, FunctionObject* getter, FunctionObject* setter, PropertyAttributes attributes)
  964. {
  965. VERIFY(property_key.is_valid());
  966. auto existing_property = storage_get(property_key).value_or({}).value;
  967. auto* accessor = existing_property.is_accessor() ? &existing_property.as_accessor() : nullptr;
  968. if (!accessor) {
  969. accessor = Accessor::create(vm(), getter, setter);
  970. define_direct_property(property_key, accessor, attributes);
  971. } else {
  972. if (getter)
  973. accessor->set_getter(getter);
  974. if (setter)
  975. accessor->set_setter(setter);
  976. }
  977. }
  978. void Object::define_intrinsic_accessor(PropertyKey const& property_key, PropertyAttributes attributes, IntrinsicAccessor accessor)
  979. {
  980. VERIFY(property_key.is_string());
  981. storage_set(property_key, { {}, attributes });
  982. m_has_intrinsic_accessors = true;
  983. auto& intrinsics = s_intrinsics.ensure(this);
  984. intrinsics.set(property_key.as_string(), move(accessor));
  985. }
  986. void Object::ensure_shape_is_unique()
  987. {
  988. if (shape().is_unique())
  989. return;
  990. m_shape = m_shape->create_unique_clone();
  991. }
  992. // Simple side-effect free property lookup, following the prototype chain. Non-standard.
  993. Value Object::get_without_side_effects(PropertyKey const& property_key) const
  994. {
  995. auto* object = this;
  996. while (object) {
  997. auto value_and_attributes = object->storage_get(property_key);
  998. if (value_and_attributes.has_value())
  999. return value_and_attributes->value;
  1000. object = object->prototype();
  1001. }
  1002. return {};
  1003. }
  1004. void Object::define_native_function(Realm& realm, PropertyKey const& property_key, Function<ThrowCompletionOr<Value>(VM&)> native_function, i32 length, PropertyAttributes attribute, Optional<Bytecode::Builtin> builtin)
  1005. {
  1006. auto function = NativeFunction::create(realm, move(native_function), length, property_key, &realm);
  1007. define_direct_property(property_key, function, attribute);
  1008. if (builtin.has_value())
  1009. realm.define_builtin(builtin.value(), function);
  1010. }
  1011. // 20.1.2.3.1 ObjectDefineProperties ( O, Properties ), https://tc39.es/ecma262/#sec-objectdefineproperties
  1012. ThrowCompletionOr<Object*> Object::define_properties(Value properties)
  1013. {
  1014. auto& vm = this->vm();
  1015. // 1. Let props be ? ToObject(Properties).
  1016. auto props = TRY(properties.to_object(vm));
  1017. // 2. Let keys be ? props.[[OwnPropertyKeys]]().
  1018. auto keys = TRY(props->internal_own_property_keys());
  1019. struct NameAndDescriptor {
  1020. PropertyKey name;
  1021. PropertyDescriptor descriptor;
  1022. };
  1023. // 3. Let descriptors be a new empty List.
  1024. Vector<NameAndDescriptor> descriptors;
  1025. // 4. For each element nextKey of keys, do
  1026. for (auto& next_key : keys) {
  1027. auto property_key = MUST(PropertyKey::from_value(vm, next_key));
  1028. // a. Let propDesc be ? props.[[GetOwnProperty]](nextKey).
  1029. auto property_descriptor = TRY(props->internal_get_own_property(property_key));
  1030. // b. If propDesc is not undefined and propDesc.[[Enumerable]] is true, then
  1031. if (property_descriptor.has_value() && *property_descriptor->enumerable) {
  1032. // i. Let descObj be ? Get(props, nextKey).
  1033. auto descriptor_object = TRY(props->get(property_key));
  1034. // ii. Let desc be ? ToPropertyDescriptor(descObj).
  1035. auto descriptor = TRY(to_property_descriptor(vm, descriptor_object));
  1036. // iii. Append the pair (a two element List) consisting of nextKey and desc to the end of descriptors.
  1037. descriptors.append({ property_key, descriptor });
  1038. }
  1039. }
  1040. // 5. For each element pair of descriptors, do
  1041. for (auto& [name, descriptor] : descriptors) {
  1042. // a. Let P be the first element of pair.
  1043. // b. Let desc be the second element of pair.
  1044. // c. Perform ? DefinePropertyOrThrow(O, P, desc).
  1045. TRY(define_property_or_throw(name, descriptor));
  1046. }
  1047. // 6. Return O.
  1048. return this;
  1049. }
  1050. // 14.7.5.9 EnumerateObjectProperties ( O ), https://tc39.es/ecma262/#sec-enumerate-object-properties
  1051. Optional<Completion> Object::enumerate_object_properties(Function<Optional<Completion>(Value)> callback) const
  1052. {
  1053. // 1. Return an Iterator object (27.1.1.2) whose next method iterates over all the String-valued keys of enumerable properties of O. The iterator object is never directly accessible to ECMAScript code. The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.
  1054. // * Returned property keys do not include keys that are Symbols.
  1055. // * Properties of the target object may be deleted during enumeration.
  1056. // * A property that is deleted before it is processed is ignored.
  1057. // * If new properties are added to the target object during enumeration, the newly added properties are not guaranteed to be processed in the active enumeration.
  1058. // * A property name will be returned at most once in any enumeration.
  1059. // * Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively.
  1060. // * A property of a prototype is not processed if it has the same name as a property that has already been processed.
  1061. HashTable<DeprecatedFlyString> visited;
  1062. auto const* target = this;
  1063. while (target) {
  1064. auto own_keys = TRY(target->internal_own_property_keys());
  1065. for (auto& key : own_keys) {
  1066. if (!key.is_string())
  1067. continue;
  1068. DeprecatedFlyString property_key = key.as_string().deprecated_string();
  1069. if (visited.contains(property_key))
  1070. continue;
  1071. auto descriptor = TRY(target->internal_get_own_property(property_key));
  1072. if (!descriptor.has_value())
  1073. continue;
  1074. visited.set(property_key);
  1075. if (!*descriptor->enumerable)
  1076. continue;
  1077. if (auto completion = callback(key); completion.has_value())
  1078. return completion.release_value();
  1079. }
  1080. target = TRY(target->internal_get_prototype_of());
  1081. };
  1082. return {};
  1083. }
  1084. void Object::visit_edges(Cell::Visitor& visitor)
  1085. {
  1086. Base::visit_edges(visitor);
  1087. visitor.visit(m_shape);
  1088. for (auto& value : m_storage)
  1089. visitor.visit(value);
  1090. m_indexed_properties.for_each_value([&visitor](auto& value) {
  1091. visitor.visit(value);
  1092. });
  1093. }
  1094. // 7.1.1.1 OrdinaryToPrimitive ( O, hint ), https://tc39.es/ecma262/#sec-ordinarytoprimitive
  1095. ThrowCompletionOr<Value> Object::ordinary_to_primitive(Value::PreferredType preferred_type) const
  1096. {
  1097. VERIFY(preferred_type == Value::PreferredType::String || preferred_type == Value::PreferredType::Number);
  1098. auto& vm = this->vm();
  1099. AK::Array<PropertyKey, 2> method_names;
  1100. // 1. If hint is string, then
  1101. if (preferred_type == Value::PreferredType::String) {
  1102. // a. Let methodNames be « "toString", "valueOf" ».
  1103. method_names = { vm.names.toString, vm.names.valueOf };
  1104. }
  1105. // 2. Else,
  1106. else {
  1107. // a. Let methodNames be « "valueOf", "toString" ».
  1108. method_names = { vm.names.valueOf, vm.names.toString };
  1109. }
  1110. // 3. For each element name of methodNames, do
  1111. for (auto& method_name : method_names) {
  1112. // a. Let method be ? Get(O, name).
  1113. auto method = TRY(get(method_name));
  1114. // b. If IsCallable(method) is true, then
  1115. if (method.is_function()) {
  1116. // i. Let result be ? Call(method, O).
  1117. auto result = TRY(call(vm, method.as_function(), const_cast<Object*>(this)));
  1118. // ii. If Type(result) is not Object, return result.
  1119. if (!result.is_object())
  1120. return result;
  1121. }
  1122. }
  1123. // 4. Throw a TypeError exception.
  1124. return vm.throw_completion<TypeError>(ErrorType::Convert, "object", preferred_type == Value::PreferredType::String ? "string" : "number");
  1125. }
  1126. }