Object.cpp 46 KB

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