Object.cpp 41 KB

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