Object.cpp 41 KB

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