Object.cpp 48 KB

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