Array.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Function.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/Array.h>
  10. #include <LibJS/Runtime/ArrayPrototype.h>
  11. #include <LibJS/Runtime/Completion.h>
  12. #include <LibJS/Runtime/Error.h>
  13. #include <LibJS/Runtime/GlobalObject.h>
  14. #include <LibJS/Runtime/NativeFunction.h>
  15. namespace JS {
  16. // 10.4.2.2 ArrayCreate ( length [ , proto ] ), https://tc39.es/ecma262/#sec-arraycreate
  17. ThrowCompletionOr<Array*> Array::create(GlobalObject& global_object, size_t length, Object* prototype)
  18. {
  19. auto& vm = global_object.vm();
  20. if (length > NumericLimits<u32>::max())
  21. return vm.throw_completion<RangeError>(global_object, ErrorType::InvalidLength, "array");
  22. if (!prototype)
  23. prototype = global_object.array_prototype();
  24. auto* array = global_object.heap().allocate<Array>(global_object, *prototype);
  25. MUST(array->internal_define_own_property(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = false }));
  26. return array;
  27. }
  28. // 7.3.18 CreateArrayFromList ( elements ), https://tc39.es/ecma262/#sec-createarrayfromlist
  29. Array* Array::create_from(GlobalObject& global_object, Vector<Value> const& elements)
  30. {
  31. // 1. Let array be ! ArrayCreate(0).
  32. auto* array = MUST(Array::create(global_object, 0));
  33. // 2. Let n be 0.
  34. // 3. For each element e of elements, do
  35. for (u32 n = 0; n < elements.size(); ++n) {
  36. // a. Perform ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), e).
  37. MUST(array->create_data_property_or_throw(n, elements[n]));
  38. // b. Set n to n + 1.
  39. }
  40. // 4. Return array.
  41. return array;
  42. }
  43. Array::Array(Object& prototype)
  44. : Object(prototype)
  45. {
  46. }
  47. // 10.4.2.4 ArraySetLength ( A, Desc ), https://tc39.es/ecma262/#sec-arraysetlength
  48. ThrowCompletionOr<bool> Array::set_length(PropertyDescriptor const& property_descriptor)
  49. {
  50. auto& global_object = this->global_object();
  51. auto& vm = this->vm();
  52. // 1. If Desc does not have a [[Value]] field, then
  53. // a. Return ! OrdinaryDefineOwnProperty(A, "length", Desc).
  54. // 2. Let newLenDesc be a copy of Desc.
  55. // NOTE: Handled by step 16
  56. size_t new_length = indexed_properties().array_like_size();
  57. if (property_descriptor.value.has_value()) {
  58. // 3. Let newLen be ? ToUint32(Desc.[[Value]]).
  59. new_length = TRY(property_descriptor.value->to_u32(global_object));
  60. // 4. Let numberLen be ? ToNumber(Desc.[[Value]]).
  61. auto number_length = TRY(property_descriptor.value->to_number(global_object));
  62. // 5. If newLen is not the same value as numberLen, throw a RangeError exception.
  63. if (new_length != number_length.as_double())
  64. return vm.throw_completion<RangeError>(global_object, ErrorType::InvalidLength, "array");
  65. }
  66. // 6. Set newLenDesc.[[Value]] to newLen.
  67. // 7. Let oldLenDesc be OrdinaryGetOwnProperty(A, "length").
  68. // 8. Assert: IsDataDescriptor(oldLenDesc) is true.
  69. // 9. Assert: oldLenDesc.[[Configurable]] is false.
  70. // 10. Let oldLen be oldLenDesc.[[Value]].
  71. // 11. If newLen ≥ oldLen, then
  72. // a. Return ! OrdinaryDefineOwnProperty(A, "length", newLenDesc).
  73. // 12. If oldLenDesc.[[Writable]] is false, return false.
  74. // NOTE: Handled by step 16
  75. // 13. If newLenDesc does not have a [[Writable]] field or newLenDesc.[[Writable]] true, let newWritable be true.
  76. // 14. Else,
  77. // a. NOTE: Setting the [[Writable]] attribute to false is deferred in case any elements cannot be deleted.
  78. // b. Let newWritable be false.
  79. auto new_writable = property_descriptor.writable.value_or(true);
  80. // c. Set newLenDesc.[[Writable]] to true.
  81. // 15. Let succeeded be ! OrdinaryDefineOwnProperty(A, "length", newLenDesc).
  82. // 16. If succeeded is false, return false.
  83. // NOTE: Because the length property does not actually exist calling OrdinaryDefineOwnProperty
  84. // will result in unintended behavior, so instead we only implement here the small subset of
  85. // checks performed inside of it that would have mattered to us:
  86. // 10.1.6.3 ValidateAndApplyPropertyDescriptor ( O, P, extensible, Desc, current ), https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor
  87. // 5. If current.[[Configurable]] is false, then
  88. // a. If Desc has a [[Configurable]] field and Desc.[[Configurable]] is true, return false.
  89. if (property_descriptor.configurable.has_value() && *property_descriptor.configurable)
  90. return false;
  91. // b. If Desc has an [[Enumerable]] field and SameValue(Desc.[[Enumerable]], current.[[Enumerable]]) is false, return false.
  92. if (property_descriptor.enumerable.has_value() && *property_descriptor.enumerable)
  93. return false;
  94. // c. If IsGenericDescriptor(Desc) is false and SameValue(IsAccessorDescriptor(Desc), IsAccessorDescriptor(current)) is false, return false.
  95. if (!property_descriptor.is_generic_descriptor() && property_descriptor.is_accessor_descriptor())
  96. return false;
  97. // NOTE: Step d. doesn't apply here.
  98. // e. Else if current.[[Writable]] is false, then
  99. if (!m_length_writable) {
  100. // i. If Desc has a [[Writable]] field and Desc.[[Writable]] is true, return false.
  101. if (property_descriptor.writable.has_value() && *property_descriptor.writable)
  102. return false;
  103. // ii. If Desc has a [[Value]] field and SameValue(Desc.[[Value]], current.[[Value]]) is false, return false.
  104. if (new_length != indexed_properties().array_like_size())
  105. return false;
  106. }
  107. // 17. For each own property key P of A that is an array index, whose numeric value is greater than or equal to newLen, in descending numeric index order, do
  108. // a. Let deleteSucceeded be ! A.[[Delete]](P).
  109. // b. If deleteSucceeded is false, then
  110. // i. Set newLenDesc.[[Value]] to ! ToUint32(P) + 1𝔽.
  111. bool success = indexed_properties().set_array_like_size(new_length);
  112. // ii. If newWritable is false, set newLenDesc.[[Writable]] to false.
  113. // iii. Perform ! OrdinaryDefineOwnProperty(A, "length", newLenDesc).
  114. // NOTE: Handled by step 18
  115. // 18. If newWritable is false, then
  116. // a. Set succeeded to ! OrdinaryDefineOwnProperty(A, "length", PropertyDescriptor { [[Writable]]: false }).
  117. // b. Assert: succeeded is true.
  118. if (!new_writable)
  119. m_length_writable = false;
  120. // NOTE: Continuation of step #17
  121. // iv. Return false.
  122. if (!success)
  123. return false;
  124. // 19. Return true.
  125. return true;
  126. }
  127. // 1.1.1.2 CompareArrayElements ( x, y, comparefn ), https://tc39.es/proposal-change-array-by-copy/#sec-comparearrayelements
  128. ThrowCompletionOr<double> compare_array_elements(GlobalObject& global_object, Value x, Value y, FunctionObject* comparefn)
  129. {
  130. auto& vm = global_object.vm();
  131. // 1. If x and y are both undefined, return +0𝔽.
  132. if (x.is_undefined() && y.is_undefined())
  133. return 0;
  134. // 2. If x is undefined, return 1𝔽.
  135. if (x.is_undefined())
  136. return 1;
  137. // 3. If y is undefined, return -1𝔽.
  138. if (y.is_undefined())
  139. return -1;
  140. // 4. If comparefn is not undefined, then
  141. if (comparefn != nullptr) {
  142. // a. Let v be ? ToNumber(? Call(comparefn, undefined, « x, y »)).
  143. auto value = TRY(call(global_object, comparefn, js_undefined(), x, y));
  144. auto value_number = TRY(value.to_number(global_object));
  145. // b. If v is NaN, return +0𝔽.
  146. if (value_number.is_nan())
  147. return 0;
  148. // c. Return v.
  149. return value_number.as_double();
  150. }
  151. // 5. Let xString be ? ToString(x).
  152. auto* x_string = js_string(vm, TRY(x.to_string(global_object)));
  153. // 6. Let yString be ? ToString(y).
  154. auto* y_string = js_string(vm, TRY(y.to_string(global_object)));
  155. // 7. Let xSmaller be ! IsLessThan(xString, yString, true).
  156. auto x_smaller = MUST(is_less_than(global_object, x_string, y_string, true));
  157. // 8. If xSmaller is true, return -1𝔽.
  158. if (x_smaller == TriState::True)
  159. return -1;
  160. // 9. Let ySmaller be ! IsLessThan(yString, xString, true).
  161. auto y_smaller = MUST(is_less_than(global_object, y_string, x_string, true));
  162. // 10. If ySmaller is true, return 1𝔽.
  163. if (y_smaller == TriState::True)
  164. return 1;
  165. // 11. Return +0𝔽.
  166. return 0;
  167. }
  168. // 1.1.1.3 SortIndexedProperties ( obj, len, SortCompare, skipHoles ), https://tc39.es/proposal-change-array-by-copy/#sec-sortindexedproperties
  169. ThrowCompletionOr<MarkedVector<Value>> sort_indexed_properties(GlobalObject& global_object, Object const& object, size_t length, Function<ThrowCompletionOr<double>(Value, Value)> const& sort_compare, bool skip_holes)
  170. {
  171. // 1. Let items be a new empty List.
  172. auto items = MarkedVector<Value> { global_object.heap() };
  173. // 2. Let k be 0.
  174. // 3. Repeat, while k < len,
  175. for (size_t k = 0; k < length; ++k) {
  176. // a. Let Pk be ! ToString(𝔽(k)).
  177. auto property_key = PropertyKey { k };
  178. bool k_read;
  179. // b. If skipHoles is true, then
  180. if (skip_holes) {
  181. // i. Let kRead be ? HasProperty(obj, Pk).
  182. k_read = TRY(object.has_property(property_key));
  183. }
  184. // c. Else,
  185. else {
  186. // i. Let kRead be true.
  187. k_read = true;
  188. }
  189. // d. If kRead is true, then
  190. if (k_read) {
  191. // i. Let kValue be ? Get(obj, Pk).
  192. auto k_value = TRY(object.get(property_key));
  193. // ii. Append kValue to items.
  194. items.append(k_value);
  195. }
  196. // e. Set k to k + 1.
  197. }
  198. // 4. Sort items using an implementation-defined sequence of calls to SortCompare. If any such call returns an abrupt completion, stop before performing any further calls to SortCompare or steps in this algorithm and return that Completion Record.
  199. // FIXME: Support AK::Function in array_merge_sort() to avoid having to create a NativeFunction.
  200. auto* native_comparefn = NativeFunction::create(global_object, "", [&](auto& vm, auto&) -> ThrowCompletionOr<Value> {
  201. auto x = vm.argument(0);
  202. auto y = vm.argument(1);
  203. return TRY(sort_compare(x, y));
  204. });
  205. TRY(array_merge_sort(global_object, native_comparefn, items));
  206. // 5. Return items.
  207. return items;
  208. }
  209. // NON-STANDARD: Used to return the value of the ephemeral length property
  210. ThrowCompletionOr<Optional<PropertyDescriptor>> Array::internal_get_own_property(PropertyKey const& property_key) const
  211. {
  212. auto& vm = this->vm();
  213. if (property_key.is_string() && property_key.as_string() == vm.names.length.as_string())
  214. return PropertyDescriptor { .value = Value(indexed_properties().array_like_size()), .writable = m_length_writable, .enumerable = false, .configurable = false };
  215. return Object::internal_get_own_property(property_key);
  216. }
  217. // 10.4.2.1 [[DefineOwnProperty]] ( P, Desc ), https://tc39.es/ecma262/#sec-array-exotic-objects-defineownproperty-p-desc
  218. ThrowCompletionOr<bool> Array::internal_define_own_property(PropertyKey const& property_key, PropertyDescriptor const& property_descriptor)
  219. {
  220. auto& vm = this->vm();
  221. VERIFY(property_key.is_valid());
  222. // 1. If P is "length", then
  223. if (property_key.is_string() && property_key.as_string() == vm.names.length.as_string()) {
  224. // a. Return ? ArraySetLength(A, Desc).
  225. return set_length(property_descriptor);
  226. }
  227. // 2. Else if P is an array index, then
  228. if (property_key.is_number()) {
  229. // a. Let oldLenDesc be OrdinaryGetOwnProperty(A, "length").
  230. // b. Assert: IsDataDescriptor(oldLenDesc) is true.
  231. // c. Assert: oldLenDesc.[[Configurable]] is false.
  232. // d. Let oldLen be oldLenDesc.[[Value]].
  233. // e. Assert: oldLen is a non-negative integral Number.
  234. // f. Let index be ! ToUint32(P).
  235. // g. If index ≥ oldLen and oldLenDesc.[[Writable]] is false, return false.
  236. if (property_key.as_number() >= indexed_properties().array_like_size() && !m_length_writable)
  237. return false;
  238. // h. Let succeeded be ! OrdinaryDefineOwnProperty(A, P, Desc).
  239. auto succeeded = MUST(Object::internal_define_own_property(property_key, property_descriptor));
  240. // i. If succeeded is false, return false.
  241. if (!succeeded)
  242. return false;
  243. // j. If index ≥ oldLen, then
  244. // i. Set oldLenDesc.[[Value]] to index + 1𝔽.
  245. // ii. Set succeeded to ! OrdinaryDefineOwnProperty(A, "length", oldLenDesc).
  246. // iii. Assert: succeeded is true.
  247. // k. Return true.
  248. return true;
  249. }
  250. // 3. Return ? OrdinaryDefineOwnProperty(A, P, Desc).
  251. return Object::internal_define_own_property(property_key, property_descriptor);
  252. }
  253. // NON-STANDARD: Used to reject deletes to ephemeral (non-configurable) length property
  254. ThrowCompletionOr<bool> Array::internal_delete(PropertyKey const& property_key)
  255. {
  256. auto& vm = this->vm();
  257. if (property_key.is_string() && property_key.as_string() == vm.names.length.as_string())
  258. return false;
  259. return Object::internal_delete(property_key);
  260. }
  261. // NON-STANDARD: Used to inject the ephemeral length property's key
  262. ThrowCompletionOr<MarkedVector<Value>> Array::internal_own_property_keys() const
  263. {
  264. auto& vm = this->vm();
  265. auto keys = TRY(Object::internal_own_property_keys());
  266. // FIXME: This is pretty expensive, find a better way to do this
  267. keys.insert(indexed_properties().real_size(), js_string(vm, vm.names.length.as_string()));
  268. return { move(keys) };
  269. }
  270. }