Array.cpp 14 KB

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