Object.cpp 40 KB

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