Array.cpp 15 KB

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