Object.cpp 54 KB

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