Array.cpp 14 KB

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