Object.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. if (!storage_has(property_name))
  428. return Optional<PropertyDescriptor> {};
  429. // 3. Let D be a newly created Property Descriptor with no fields.
  430. PropertyDescriptor descriptor;
  431. // 4. Let X be O's own property whose key is P.
  432. auto [value, attributes] = *storage_get(property_name);
  433. // 5. If X is a data property, then
  434. if (!value.is_accessor()) {
  435. // a. Set D.[[Value]] to the value of X's [[Value]] attribute.
  436. descriptor.value = value.value_or(js_undefined());
  437. // b. Set D.[[Writable]] to the value of X's [[Writable]] attribute.
  438. descriptor.writable = attributes.is_writable();
  439. }
  440. // 6. Else,
  441. else {
  442. // a. Assert: X is an accessor property.
  443. // b. Set D.[[Get]] to the value of X's [[Get]] attribute.
  444. descriptor.get = value.as_accessor().getter();
  445. // c. Set D.[[Set]] to the value of X's [[Set]] attribute.
  446. descriptor.set = value.as_accessor().setter();
  447. }
  448. // 7. Set D.[[Enumerable]] to the value of X's [[Enumerable]] attribute.
  449. descriptor.enumerable = attributes.is_enumerable();
  450. // 8. Set D.[[Configurable]] to the value of X's [[Configurable]] attribute.
  451. descriptor.configurable = attributes.is_configurable();
  452. // 9. Return D.
  453. return { descriptor };
  454. }
  455. // 10.1.6 [[DefineOwnProperty]] ( P, Desc ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc
  456. ThrowCompletionOr<bool> Object::internal_define_own_property(PropertyName const& property_name, PropertyDescriptor const& property_descriptor)
  457. {
  458. VERIFY(property_name.is_valid());
  459. // 1. Let current be ? O.[[GetOwnProperty]](P).
  460. auto current = TRY(internal_get_own_property(property_name));
  461. // 2. Let extensible be ? IsExtensible(O).
  462. auto extensible = TRY(is_extensible());
  463. // 3. Return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current).
  464. return validate_and_apply_property_descriptor(this, property_name, extensible, property_descriptor, current);
  465. }
  466. // 10.1.7 [[HasProperty]] ( P ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-hasproperty-p
  467. ThrowCompletionOr<bool> Object::internal_has_property(PropertyName const& property_name) const
  468. {
  469. auto& vm = this->vm();
  470. // 1. Assert: IsPropertyKey(P) is true.
  471. VERIFY(property_name.is_valid());
  472. // 2. Let hasOwn be ? O.[[GetOwnProperty]](P).
  473. auto has_own = TRY(internal_get_own_property(property_name));
  474. // 3. If hasOwn is not undefined, return true.
  475. if (has_own.has_value())
  476. return true;
  477. // 4. Let parent be ? O.[[GetPrototypeOf]]().
  478. auto* parent = TRY(internal_get_prototype_of());
  479. // 5. If parent is not null, then
  480. if (parent) {
  481. // a. Return ? parent.[[HasProperty]](P).
  482. auto result = parent->internal_has_property(property_name);
  483. if (auto* exception = vm.exception())
  484. return throw_completion(exception->value());
  485. return result;
  486. }
  487. // 6. Return false.
  488. return false;
  489. }
  490. // 10.1.8 [[Get]] ( P, Receiver ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-get-p-receiver
  491. ThrowCompletionOr<Value> Object::internal_get(PropertyName const& property_name, Value receiver) const
  492. {
  493. VERIFY(!receiver.is_empty());
  494. auto& vm = this->vm();
  495. // 1. Assert: IsPropertyKey(P) is true.
  496. VERIFY(property_name.is_valid());
  497. // 2. Let desc be ? O.[[GetOwnProperty]](P).
  498. auto descriptor = TRY(internal_get_own_property(property_name));
  499. // 3. If desc is undefined, then
  500. if (!descriptor.has_value()) {
  501. // a. Let parent be ? O.[[GetPrototypeOf]]().
  502. auto* parent = TRY(internal_get_prototype_of());
  503. // b. If parent is null, return undefined.
  504. if (!parent)
  505. return js_undefined();
  506. // c. Return ? parent.[[Get]](P, Receiver).
  507. return parent->internal_get(property_name, receiver);
  508. }
  509. // 4. If IsDataDescriptor(desc) is true, return desc.[[Value]].
  510. if (descriptor->is_data_descriptor())
  511. return *descriptor->value;
  512. // 5. Assert: IsAccessorDescriptor(desc) is true.
  513. VERIFY(descriptor->is_accessor_descriptor());
  514. // 6. Let getter be desc.[[Get]].
  515. auto* getter = *descriptor->get;
  516. // 7. If getter is undefined, return undefined.
  517. if (!getter)
  518. return js_undefined();
  519. // 8. Return ? Call(getter, Receiver).
  520. return TRY(vm.call(*getter, receiver));
  521. }
  522. // 10.1.9 [[Set]] ( P, V, Receiver ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  523. ThrowCompletionOr<bool> Object::internal_set(PropertyName const& property_name, Value value, Value receiver)
  524. {
  525. VERIFY(!value.is_empty());
  526. VERIFY(!receiver.is_empty());
  527. // 1. Assert: IsPropertyKey(P) is true.
  528. VERIFY(property_name.is_valid());
  529. // 2. Let ownDesc be ? O.[[GetOwnProperty]](P).
  530. auto own_descriptor = TRY(internal_get_own_property(property_name));
  531. // 3. Return OrdinarySetWithOwnDescriptor(O, P, V, Receiver, ownDesc).
  532. return ordinary_set_with_own_descriptor(property_name, value, receiver, own_descriptor);
  533. }
  534. // 10.1.9.2 OrdinarySetWithOwnDescriptor ( O, P, V, Receiver, ownDesc ), https://tc39.es/ecma262/#sec-ordinarysetwithowndescriptor
  535. ThrowCompletionOr<bool> Object::ordinary_set_with_own_descriptor(PropertyName const& property_name, Value value, Value receiver, Optional<PropertyDescriptor> own_descriptor)
  536. {
  537. auto& vm = this->vm();
  538. // 1. Assert: IsPropertyKey(P) is true.
  539. VERIFY(property_name.is_valid());
  540. // 2. If ownDesc is undefined, then
  541. if (!own_descriptor.has_value()) {
  542. // a. Let parent be ? O.[[GetPrototypeOf]]().
  543. auto* parent = TRY(internal_get_prototype_of());
  544. // b. If parent is not null, then
  545. if (parent) {
  546. // i. Return ? parent.[[Set]](P, V, Receiver).
  547. return TRY(parent->internal_set(property_name, value, receiver));
  548. }
  549. // c. Else,
  550. else {
  551. // i. Set ownDesc to the PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
  552. own_descriptor = PropertyDescriptor {
  553. .value = js_undefined(),
  554. .writable = true,
  555. .enumerable = true,
  556. .configurable = true,
  557. };
  558. }
  559. }
  560. // 3. If IsDataDescriptor(ownDesc) is true, then
  561. if (own_descriptor->is_data_descriptor()) {
  562. // a. If ownDesc.[[Writable]] is false, return false.
  563. if (!*own_descriptor->writable)
  564. return false;
  565. // b. If Type(Receiver) is not Object, return false.
  566. if (!receiver.is_object())
  567. return false;
  568. // c. Let existingDescriptor be ? Receiver.[[GetOwnProperty]](P).
  569. auto existing_descriptor = TRY(receiver.as_object().internal_get_own_property(property_name));
  570. // d. If existingDescriptor is not undefined, then
  571. if (existing_descriptor.has_value()) {
  572. // i. If IsAccessorDescriptor(existingDescriptor) is true, return false.
  573. if (existing_descriptor->is_accessor_descriptor())
  574. return false;
  575. // ii. If existingDescriptor.[[Writable]] is false, return false.
  576. if (!*existing_descriptor->writable)
  577. return false;
  578. // iii. Let valueDesc be the PropertyDescriptor { [[Value]]: V }.
  579. auto value_descriptor = PropertyDescriptor { .value = value };
  580. // iv. Return ? Receiver.[[DefineOwnProperty]](P, valueDesc).
  581. return TRY(receiver.as_object().internal_define_own_property(property_name, value_descriptor));
  582. }
  583. // e. Else,
  584. else {
  585. // i. Assert: Receiver does not currently have a property P.
  586. VERIFY(!receiver.as_object().storage_has(property_name));
  587. // ii. Return ? CreateDataProperty(Receiver, P, V).
  588. return TRY(receiver.as_object().create_data_property(property_name, value));
  589. }
  590. }
  591. // 4. Assert: IsAccessorDescriptor(ownDesc) is true.
  592. VERIFY(own_descriptor->is_accessor_descriptor());
  593. // 5. Let setter be ownDesc.[[Set]].
  594. auto* setter = *own_descriptor->set;
  595. // 6. If setter is undefined, return false.
  596. if (!setter)
  597. return false;
  598. // 7. Perform ? Call(setter, Receiver, « V »).
  599. (void)TRY(vm.call(*setter, receiver, value));
  600. // 8. Return true.
  601. return true;
  602. }
  603. // 10.1.10 [[Delete]] ( P ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-delete-p
  604. ThrowCompletionOr<bool> Object::internal_delete(PropertyName const& property_name)
  605. {
  606. // 1. Assert: IsPropertyKey(P) is true.
  607. VERIFY(property_name.is_valid());
  608. // 2. Let desc be ? O.[[GetOwnProperty]](P).
  609. auto descriptor = TRY(internal_get_own_property(property_name));
  610. // 3. If desc is undefined, return true.
  611. if (!descriptor.has_value())
  612. return true;
  613. // 4. If desc.[[Configurable]] is true, then
  614. if (*descriptor->configurable) {
  615. // a. Remove the own property with name P from O.
  616. storage_delete(property_name);
  617. // b. Return true.
  618. return true;
  619. }
  620. // 5. Return false.
  621. return false;
  622. }
  623. // 10.1.11 [[OwnPropertyKeys]] ( ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys
  624. ThrowCompletionOr<MarkedValueList> Object::internal_own_property_keys() const
  625. {
  626. auto& vm = this->vm();
  627. // 1. Let keys be a new empty List.
  628. MarkedValueList keys { heap() };
  629. // 2. For each own property key P of O such that P is an array index, in ascending numeric index order, do
  630. for (auto& entry : m_indexed_properties) {
  631. // a. Add P as the last element of keys.
  632. keys.append(js_string(vm, String::number(entry.index())));
  633. }
  634. // 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
  635. for (auto& it : shape().property_table_ordered()) {
  636. if (it.key.is_string()) {
  637. // a. Add P as the last element of keys.
  638. keys.append(it.key.to_value(vm));
  639. }
  640. }
  641. // 4. For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property creation, do
  642. for (auto& it : shape().property_table_ordered()) {
  643. if (it.key.is_symbol()) {
  644. // a. Add P as the last element of keys.
  645. keys.append(it.key.to_value(vm));
  646. }
  647. }
  648. // 5. Return keys.
  649. return { move(keys) };
  650. }
  651. // 10.4.7.2 SetImmutablePrototype ( O, V ), https://tc39.es/ecma262/#sec-set-immutable-prototype
  652. ThrowCompletionOr<bool> Object::set_immutable_prototype(Object* prototype)
  653. {
  654. // 1. Assert: Either Type(V) is Object or Type(V) is Null.
  655. // 2. Let current be ? O.[[GetPrototypeOf]]().
  656. auto* current = TRY(internal_get_prototype_of());
  657. // 3. If SameValue(V, current) is true, return true.
  658. if (prototype == current)
  659. return true;
  660. // 4. Return false.
  661. return false;
  662. }
  663. Optional<ValueAndAttributes> Object::storage_get(PropertyName const& property_name) const
  664. {
  665. VERIFY(property_name.is_valid());
  666. Value value;
  667. PropertyAttributes attributes;
  668. if (property_name.is_number()) {
  669. auto value_and_attributes = m_indexed_properties.get(property_name.as_number());
  670. if (!value_and_attributes.has_value())
  671. return {};
  672. value = value_and_attributes->value;
  673. attributes = value_and_attributes->attributes;
  674. } else {
  675. auto metadata = shape().lookup(property_name.to_string_or_symbol());
  676. if (!metadata.has_value())
  677. return {};
  678. value = m_storage[metadata->offset];
  679. attributes = metadata->attributes;
  680. }
  681. return ValueAndAttributes { .value = value, .attributes = attributes };
  682. }
  683. bool Object::storage_has(PropertyName const& property_name) const
  684. {
  685. VERIFY(property_name.is_valid());
  686. if (property_name.is_number())
  687. return m_indexed_properties.has_index(property_name.as_number());
  688. return shape().lookup(property_name.to_string_or_symbol()).has_value();
  689. }
  690. void Object::storage_set(PropertyName const& property_name, ValueAndAttributes const& value_and_attributes)
  691. {
  692. VERIFY(property_name.is_valid());
  693. auto [value, attributes] = value_and_attributes;
  694. if (property_name.is_number()) {
  695. auto index = property_name.as_number();
  696. m_indexed_properties.put(index, value, attributes);
  697. return;
  698. }
  699. auto property_name_string_or_symbol = property_name.to_string_or_symbol();
  700. auto metadata = shape().lookup(property_name_string_or_symbol);
  701. if (!metadata.has_value()) {
  702. if (!m_shape->is_unique() && shape().property_count() > 100) {
  703. // If you add more than 100 properties to an object, let's stop doing
  704. // transitions to avoid filling up the heap with shapes.
  705. ensure_shape_is_unique();
  706. }
  707. if (m_shape->is_unique())
  708. m_shape->add_property_to_unique_shape(property_name_string_or_symbol, attributes);
  709. else
  710. set_shape(*m_shape->create_put_transition(property_name_string_or_symbol, attributes));
  711. m_storage.append(value);
  712. return;
  713. }
  714. if (attributes != metadata->attributes) {
  715. if (m_shape->is_unique())
  716. m_shape->reconfigure_property_in_unique_shape(property_name_string_or_symbol, attributes);
  717. else
  718. set_shape(*m_shape->create_configure_transition(property_name_string_or_symbol, attributes));
  719. }
  720. m_storage[metadata->offset] = value;
  721. }
  722. void Object::storage_delete(PropertyName const& property_name)
  723. {
  724. VERIFY(property_name.is_valid());
  725. VERIFY(storage_has(property_name));
  726. if (property_name.is_number())
  727. return m_indexed_properties.remove(property_name.as_number());
  728. auto metadata = shape().lookup(property_name.to_string_or_symbol());
  729. VERIFY(metadata.has_value());
  730. ensure_shape_is_unique();
  731. shape().remove_property_from_unique_shape(property_name.to_string_or_symbol(), metadata->offset);
  732. m_storage.remove(metadata->offset);
  733. }
  734. void Object::set_prototype(Object* new_prototype)
  735. {
  736. if (prototype() == new_prototype)
  737. return;
  738. auto& shape = this->shape();
  739. if (shape.is_unique())
  740. shape.set_prototype_without_transition(new_prototype);
  741. else
  742. m_shape = shape.create_prototype_transition(new_prototype);
  743. }
  744. void Object::define_native_accessor(PropertyName const& property_name, Function<Value(VM&, GlobalObject&)> getter, Function<Value(VM&, GlobalObject&)> setter, PropertyAttributes attribute)
  745. {
  746. auto& vm = this->vm();
  747. String formatted_property_name;
  748. if (property_name.is_number()) {
  749. formatted_property_name = property_name.to_string();
  750. } else if (property_name.is_string()) {
  751. formatted_property_name = property_name.as_string();
  752. } else {
  753. formatted_property_name = String::formatted("[{}]", property_name.as_symbol()->description());
  754. }
  755. FunctionObject* getter_function = nullptr;
  756. if (getter) {
  757. auto name = String::formatted("get {}", formatted_property_name);
  758. getter_function = NativeFunction::create(global_object(), name, move(getter));
  759. getter_function->define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  760. getter_function->define_direct_property(vm.names.name, js_string(vm, name), Attribute::Configurable);
  761. }
  762. FunctionObject* setter_function = nullptr;
  763. if (setter) {
  764. auto name = String::formatted("set {}", formatted_property_name);
  765. setter_function = NativeFunction::create(global_object(), name, move(setter));
  766. setter_function->define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  767. setter_function->define_direct_property(vm.names.name, js_string(vm, name), Attribute::Configurable);
  768. }
  769. return define_direct_accessor(property_name, getter_function, setter_function, attribute);
  770. }
  771. void Object::define_direct_accessor(PropertyName const& property_name, FunctionObject* getter, FunctionObject* setter, PropertyAttributes attributes)
  772. {
  773. VERIFY(property_name.is_valid());
  774. auto existing_property = storage_get(property_name).value_or({}).value;
  775. auto* accessor = existing_property.is_accessor() ? &existing_property.as_accessor() : nullptr;
  776. if (!accessor) {
  777. accessor = Accessor::create(vm(), getter, setter);
  778. define_direct_property(property_name, accessor, attributes);
  779. } else {
  780. if (getter)
  781. accessor->set_getter(getter);
  782. if (setter)
  783. accessor->set_setter(setter);
  784. }
  785. }
  786. void Object::ensure_shape_is_unique()
  787. {
  788. if (shape().is_unique())
  789. return;
  790. m_shape = m_shape->create_unique_clone();
  791. }
  792. // Simple side-effect free property lookup, following the prototype chain. Non-standard.
  793. Value Object::get_without_side_effects(const PropertyName& property_name) const
  794. {
  795. auto* object = this;
  796. while (object) {
  797. auto value_and_attributes = object->storage_get(property_name);
  798. if (value_and_attributes.has_value())
  799. return value_and_attributes->value;
  800. object = object->prototype();
  801. }
  802. return {};
  803. }
  804. void Object::define_native_function(PropertyName const& property_name, Function<Value(VM&, GlobalObject&)> native_function, i32 length, PropertyAttributes attribute)
  805. {
  806. auto& vm = this->vm();
  807. String function_name;
  808. if (property_name.is_string()) {
  809. function_name = property_name.as_string();
  810. } else {
  811. function_name = String::formatted("[{}]", property_name.as_symbol()->description());
  812. }
  813. auto* function = NativeFunction::create(global_object(), function_name, move(native_function));
  814. function->define_direct_property(vm.names.length, Value(length), Attribute::Configurable);
  815. function->define_direct_property(vm.names.name, js_string(vm, function_name), Attribute::Configurable);
  816. define_direct_property(property_name, function, attribute);
  817. }
  818. // 20.1.2.3.1 ObjectDefineProperties ( O, Properties ), https://tc39.es/ecma262/#sec-objectdefineproperties
  819. ThrowCompletionOr<Object*> Object::define_properties(Value properties)
  820. {
  821. auto& vm = this->vm();
  822. auto& global_object = this->global_object();
  823. // 1. Assert: Type(O) is Object.
  824. // 2. Let props be ? ToObject(Properties).
  825. auto* props = properties.to_object(global_object);
  826. if (auto* exception = vm.exception())
  827. return throw_completion(exception->value());
  828. // 3. Let keys be ? props.[[OwnPropertyKeys]]().
  829. auto keys = TRY(props->internal_own_property_keys());
  830. struct NameAndDescriptor {
  831. PropertyName name;
  832. PropertyDescriptor descriptor;
  833. };
  834. // 4. Let descriptors be a new empty List.
  835. Vector<NameAndDescriptor> descriptors;
  836. // 5. For each element nextKey of keys, do
  837. for (auto& next_key : keys) {
  838. auto property_name = PropertyName::from_value(global_object, next_key);
  839. // a. Let propDesc be ? props.[[GetOwnProperty]](nextKey).
  840. auto property_descriptor = TRY(props->internal_get_own_property(property_name));
  841. // b. If propDesc is not undefined and propDesc.[[Enumerable]] is true, then
  842. if (property_descriptor.has_value() && *property_descriptor->enumerable) {
  843. // i. Let descObj be ? Get(props, nextKey).
  844. auto descriptor_object = TRY(props->get(property_name));
  845. // ii. Let desc be ? ToPropertyDescriptor(descObj).
  846. auto descriptor = TRY(to_property_descriptor(global_object, descriptor_object));
  847. // iii. Append the pair (a two element List) consisting of nextKey and desc to the end of descriptors.
  848. descriptors.append({ property_name, descriptor });
  849. }
  850. }
  851. // 6. For each element pair of descriptors, do
  852. for (auto& [name, descriptor] : descriptors) {
  853. // a. Let P be the first element of pair.
  854. // b. Let desc be the second element of pair.
  855. // c. Perform ? DefinePropertyOrThrow(O, P, desc).
  856. TRY(define_property_or_throw(name, descriptor));
  857. }
  858. // 7. Return O.
  859. return this;
  860. }
  861. void Object::visit_edges(Cell::Visitor& visitor)
  862. {
  863. Cell::visit_edges(visitor);
  864. visitor.visit(m_shape);
  865. for (auto& value : m_storage)
  866. visitor.visit(value);
  867. m_indexed_properties.for_each_value([&visitor](auto& value) {
  868. visitor.visit(value);
  869. });
  870. }
  871. // 7.1.1.1 OrdinaryToPrimitive ( O, hint ), https://tc39.es/ecma262/#sec-ordinarytoprimitive
  872. ThrowCompletionOr<Value> Object::ordinary_to_primitive(Value::PreferredType preferred_type) const
  873. {
  874. VERIFY(preferred_type == Value::PreferredType::String || preferred_type == Value::PreferredType::Number);
  875. auto& vm = this->vm();
  876. AK::Array<PropertyName, 2> method_names;
  877. // 1. If hint is string, then
  878. if (preferred_type == Value::PreferredType::String) {
  879. // a. Let methodNames be « "toString", "valueOf" ».
  880. method_names = { vm.names.toString, vm.names.valueOf };
  881. } else {
  882. // a. Let methodNames be « "valueOf", "toString" ».
  883. method_names = { vm.names.valueOf, vm.names.toString };
  884. }
  885. // 3. For each element name of methodNames, do
  886. for (auto& method_name : method_names) {
  887. // a. Let method be ? Get(O, name).
  888. auto method = TRY(get(method_name));
  889. // b. If IsCallable(method) is true, then
  890. if (method.is_function()) {
  891. // i. Let result be ? Call(method, O).
  892. auto result = TRY(vm.call(method.as_function(), const_cast<Object*>(this)));
  893. // ii. If Type(result) is not Object, return result.
  894. if (!result.is_object())
  895. return result;
  896. }
  897. }
  898. // 4. Throw a TypeError exception.
  899. return vm.throw_completion<TypeError>(global_object(), ErrorType::Convert, "object", preferred_type == Value::PreferredType::String ? "string" : "number");
  900. }
  901. }