Object.cpp 46 KB

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