Object.cpp 46 KB

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