ArrayPrototype.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/Function.h>
  28. #include <AK/StringBuilder.h>
  29. #include <LibJS/Heap/Heap.h>
  30. #include <LibJS/Interpreter.h>
  31. #include <LibJS/Runtime/Array.h>
  32. #include <LibJS/Runtime/ArrayPrototype.h>
  33. #include <LibJS/Runtime/Error.h>
  34. #include <LibJS/Runtime/Function.h>
  35. #include <LibJS/Runtime/GlobalObject.h>
  36. #include <LibJS/Runtime/MarkedValueList.h>
  37. #include <LibJS/Runtime/Value.h>
  38. namespace JS {
  39. ArrayPrototype::ArrayPrototype()
  40. : Object(interpreter().global_object().object_prototype())
  41. {
  42. u8 attr = Attribute::Writable | Attribute::Configurable;
  43. put_native_function("filter", filter, 1, attr);
  44. put_native_function("forEach", for_each, 1, attr);
  45. put_native_function("map", map, 1, attr);
  46. put_native_function("pop", pop, 0, attr);
  47. put_native_function("push", push, 1, attr);
  48. put_native_function("shift", shift, 0, attr);
  49. put_native_function("toString", to_string, 0, attr);
  50. put_native_function("unshift", unshift, 1, attr);
  51. put_native_function("join", join, 1, attr);
  52. put_native_function("concat", concat, 1, attr);
  53. put_native_function("slice", slice, 2, attr);
  54. put_native_function("indexOf", index_of, 1, attr);
  55. put_native_function("reverse", reverse, 0, attr);
  56. put_native_function("lastIndexOf", last_index_of, 1, attr);
  57. put_native_function("includes", includes, 1, attr);
  58. put_native_function("find", find, 1, attr);
  59. put_native_function("findIndex", find_index, 1, attr);
  60. put_native_function("some", some, 1, attr);
  61. put_native_function("every", every, 1, attr);
  62. put("length", Value(0), Attribute::Configurable);
  63. }
  64. ArrayPrototype::~ArrayPrototype()
  65. {
  66. }
  67. static Function* callback_from_args(Interpreter& interpreter, const String& name)
  68. {
  69. if (interpreter.argument_count() < 1) {
  70. interpreter.throw_exception<TypeError>(String::format("Array.prototype.%s() requires at least one argument", name.characters()));
  71. return nullptr;
  72. }
  73. auto callback = interpreter.argument(0);
  74. if (!callback.is_function()) {
  75. interpreter.throw_exception<TypeError>(String::format("%s is not a function", callback.to_string_without_side_effects().characters()));
  76. return nullptr;
  77. }
  78. return &callback.as_function();
  79. }
  80. static size_t get_length(Interpreter& interpreter, Object& object)
  81. {
  82. auto length_property = object.get("length");
  83. if (interpreter.exception())
  84. return 0;
  85. return length_property.to_size_t(interpreter);
  86. }
  87. static void for_each_item(Interpreter& interpreter, const String& name, AK::Function<IterationDecision(size_t index, Value value, Value callback_result)> callback, bool skip_empty = true)
  88. {
  89. auto* this_object = interpreter.this_value().to_object(interpreter);
  90. if (!this_object)
  91. return;
  92. auto initial_length = get_length(interpreter, *this_object);
  93. if (interpreter.exception())
  94. return;
  95. auto* callback_function = callback_from_args(interpreter, name);
  96. if (!callback_function)
  97. return;
  98. auto this_value = interpreter.argument(1);
  99. for (size_t i = 0; i < initial_length; ++i) {
  100. auto value = this_object->get_by_index(i);
  101. if (value.is_empty()) {
  102. if (skip_empty)
  103. continue;
  104. value = js_undefined();
  105. }
  106. MarkedValueList arguments(interpreter.heap());
  107. arguments.append(value);
  108. arguments.append(Value((i32)i));
  109. arguments.append(this_object);
  110. auto callback_result = interpreter.call(*callback_function, this_value, move(arguments));
  111. if (interpreter.exception())
  112. return;
  113. if (callback(i, value, callback_result) == IterationDecision::Break)
  114. break;
  115. }
  116. }
  117. Value ArrayPrototype::filter(Interpreter& interpreter)
  118. {
  119. auto* new_array = Array::create(interpreter.global_object());
  120. for_each_item(interpreter, "filter", [&](auto, auto value, auto callback_result) {
  121. if (callback_result.to_boolean())
  122. new_array->elements().append(value);
  123. return IterationDecision::Continue;
  124. });
  125. return Value(new_array);
  126. }
  127. Value ArrayPrototype::for_each(Interpreter& interpreter)
  128. {
  129. for_each_item(interpreter, "forEach", [](auto, auto, auto) {
  130. return IterationDecision::Continue;
  131. });
  132. return js_undefined();
  133. }
  134. Value ArrayPrototype::map(Interpreter& interpreter)
  135. {
  136. auto* this_object = interpreter.this_value().to_object(interpreter);
  137. if (!this_object)
  138. return {};
  139. auto initial_length = get_length(interpreter, *this_object);
  140. if (interpreter.exception())
  141. return {};
  142. auto* new_array = Array::create(interpreter.global_object());
  143. new_array->elements().resize(initial_length);
  144. for_each_item(interpreter, "map", [&](auto index, auto, auto callback_result) {
  145. new_array->elements()[index] = callback_result;
  146. return IterationDecision::Continue;
  147. });
  148. return Value(new_array);
  149. }
  150. Value ArrayPrototype::push(Interpreter& interpreter)
  151. {
  152. auto* this_object = interpreter.this_value().to_object(interpreter);
  153. if (!this_object)
  154. return {};
  155. if (this_object->is_array()) {
  156. auto* array = static_cast<Array*>(this_object);
  157. for (size_t i = 0; i < interpreter.argument_count(); ++i)
  158. array->elements().append(interpreter.argument(i));
  159. return Value(array->length());
  160. }
  161. auto length = get_length(interpreter, *this_object);
  162. if (interpreter.exception())
  163. return {};
  164. auto argument_count = interpreter.argument_count();
  165. auto new_length = length + argument_count;
  166. if (new_length > MAX_ARRAY_LIKE_INDEX)
  167. return interpreter.throw_exception<TypeError>("Maximum array size exceeded");
  168. for (size_t i = 0; i < argument_count; ++i)
  169. this_object->put_by_index(length + i, interpreter.argument(i));
  170. auto new_length_value = Value((i32)new_length);
  171. this_object->put("length", new_length_value);
  172. if (interpreter.exception())
  173. return {};
  174. return new_length_value;
  175. }
  176. Value ArrayPrototype::unshift(Interpreter& interpreter)
  177. {
  178. auto* array = array_from(interpreter);
  179. if (!array)
  180. return {};
  181. for (size_t i = 0; i < interpreter.argument_count(); ++i)
  182. array->elements().insert(i, interpreter.argument(i));
  183. return Value(array->length());
  184. }
  185. Value ArrayPrototype::pop(Interpreter& interpreter)
  186. {
  187. auto* this_object = interpreter.this_value().to_object(interpreter);
  188. if (!this_object)
  189. return {};
  190. if (this_object->is_array()) {
  191. auto* array = static_cast<Array*>(this_object);
  192. if (array->elements().is_empty())
  193. return js_undefined();
  194. return array->elements().take_last().value_or(js_undefined());
  195. }
  196. auto length = get_length(interpreter, *this_object);
  197. if (length == 0) {
  198. this_object->put("length", Value(0));
  199. return js_undefined();
  200. }
  201. auto index = length - 1;
  202. auto element = this_object->get_by_index(index).value_or(js_undefined());
  203. if (interpreter.exception())
  204. return {};
  205. this_object->delete_property(PropertyName(index));
  206. this_object->put("length", Value((i32)index));
  207. if (interpreter.exception())
  208. return {};
  209. return element;
  210. }
  211. Value ArrayPrototype::shift(Interpreter& interpreter)
  212. {
  213. auto* array = array_from(interpreter);
  214. if (!array)
  215. return {};
  216. if (array->elements().is_empty())
  217. return js_undefined();
  218. return array->elements().take_first().value_or(js_undefined());
  219. }
  220. static Value join_array_with_separator(Interpreter& interpreter, const Array& array, StringView separator)
  221. {
  222. StringBuilder builder;
  223. for (size_t i = 0; i < array.elements().size(); ++i) {
  224. if (i != 0)
  225. builder.append(separator);
  226. auto value = array.elements()[i];
  227. if (!value.is_empty() && !value.is_undefined() && !value.is_null()) {
  228. auto string = value.to_string(interpreter);
  229. if (interpreter.exception())
  230. return {};
  231. builder.append(string);
  232. }
  233. }
  234. return js_string(interpreter, builder.to_string());
  235. }
  236. Value ArrayPrototype::to_string(Interpreter& interpreter)
  237. {
  238. auto* array = array_from(interpreter);
  239. if (!array)
  240. return {};
  241. return join_array_with_separator(interpreter, *array, ",");
  242. }
  243. Value ArrayPrototype::join(Interpreter& interpreter)
  244. {
  245. auto* array = array_from(interpreter);
  246. if (!array)
  247. return {};
  248. String separator = ",";
  249. if (interpreter.argument_count()) {
  250. separator = interpreter.argument(0).to_string(interpreter);
  251. if (interpreter.exception())
  252. return {};
  253. }
  254. return join_array_with_separator(interpreter, *array, separator);
  255. }
  256. Value ArrayPrototype::concat(Interpreter& interpreter)
  257. {
  258. auto* array = array_from(interpreter);
  259. if (!array)
  260. return {};
  261. auto* new_array = Array::create(interpreter.global_object());
  262. new_array->elements().append(array->elements());
  263. for (size_t i = 0; i < interpreter.argument_count(); ++i) {
  264. auto argument = interpreter.argument(i);
  265. if (argument.is_array()) {
  266. auto& argument_object = argument.as_object();
  267. new_array->elements().append(argument_object.elements());
  268. } else {
  269. new_array->elements().append(argument);
  270. }
  271. }
  272. return Value(new_array);
  273. }
  274. Value ArrayPrototype::slice(Interpreter& interpreter)
  275. {
  276. auto* array = array_from(interpreter);
  277. if (!array)
  278. return {};
  279. auto* new_array = Array::create(interpreter.global_object());
  280. if (interpreter.argument_count() == 0) {
  281. new_array->elements().append(array->elements());
  282. return new_array;
  283. }
  284. ssize_t array_size = static_cast<ssize_t>(array->elements().size());
  285. auto start_slice = interpreter.argument(0).to_i32(interpreter);
  286. if (interpreter.exception())
  287. return {};
  288. auto end_slice = array_size;
  289. if (start_slice > array_size)
  290. return new_array;
  291. if (start_slice < 0)
  292. start_slice = end_slice + start_slice;
  293. if (interpreter.argument_count() >= 2) {
  294. end_slice = interpreter.argument(1).to_i32(interpreter);
  295. if (interpreter.exception())
  296. return {};
  297. if (end_slice < 0)
  298. end_slice = array_size + end_slice;
  299. else if (end_slice > array_size)
  300. end_slice = array_size;
  301. }
  302. size_t array_capacity = start_slice + array_size - end_slice;
  303. new_array->elements().ensure_capacity(array_capacity);
  304. for (ssize_t i = start_slice; i < end_slice; ++i) {
  305. new_array->elements().append(array->elements().at(i));
  306. }
  307. return new_array;
  308. }
  309. Value ArrayPrototype::index_of(Interpreter& interpreter)
  310. {
  311. auto* array = array_from(interpreter);
  312. if (!array)
  313. return {};
  314. i32 array_size = static_cast<i32>(array->elements().size());
  315. if (interpreter.argument_count() == 0 || array_size == 0)
  316. return Value(-1);
  317. i32 from_index = 0;
  318. if (interpreter.argument_count() >= 2) {
  319. from_index = interpreter.argument(1).to_i32(interpreter);
  320. if (interpreter.exception())
  321. return {};
  322. if (from_index >= array_size)
  323. return Value(-1);
  324. auto negative_min_index = ((array_size - 1) * -1);
  325. if (from_index < negative_min_index)
  326. from_index = 0;
  327. else if (from_index < 0)
  328. from_index = array_size + from_index;
  329. }
  330. auto search_element = interpreter.argument(0);
  331. for (i32 i = from_index; i < array_size; ++i) {
  332. auto& element = array->elements().at(i);
  333. if (strict_eq(interpreter, element, search_element))
  334. return Value(i);
  335. }
  336. return Value(-1);
  337. }
  338. Value ArrayPrototype::reverse(Interpreter& interpreter)
  339. {
  340. auto* array = array_from(interpreter);
  341. if (!array)
  342. return {};
  343. if (array->elements().size() == 0)
  344. return array;
  345. Vector<Value> array_reverse;
  346. array_reverse.ensure_capacity(array->elements().size());
  347. for (ssize_t i = array->elements().size() - 1; i >= 0; --i)
  348. array_reverse.append(array->elements().at(i));
  349. array->elements() = move(array_reverse);
  350. return array;
  351. }
  352. Value ArrayPrototype::last_index_of(Interpreter& interpreter)
  353. {
  354. auto* array = array_from(interpreter);
  355. if (!array)
  356. return {};
  357. i32 array_size = static_cast<i32>(array->elements().size());
  358. if (interpreter.argument_count() == 0 || array_size == 0)
  359. return Value(-1);
  360. i32 from_index = 0;
  361. if (interpreter.argument_count() >= 2) {
  362. from_index = interpreter.argument(1).to_i32(interpreter);
  363. if (interpreter.exception())
  364. return {};
  365. if (from_index >= array_size)
  366. return Value(-1);
  367. auto negative_min_index = ((array_size - 1) * -1);
  368. if (from_index < negative_min_index)
  369. from_index = 0;
  370. else if (from_index < 0)
  371. from_index = array_size + from_index;
  372. }
  373. auto search_element = interpreter.argument(0);
  374. for (i32 i = array_size - 1; i >= from_index; --i) {
  375. auto& element = array->elements().at(i);
  376. if (strict_eq(interpreter, element, search_element))
  377. return Value(i);
  378. }
  379. return Value(-1);
  380. }
  381. Value ArrayPrototype::includes(Interpreter& interpreter)
  382. {
  383. auto* array = array_from(interpreter);
  384. if (!array)
  385. return {};
  386. i32 array_size = array->elements().size();
  387. if (array_size == 0)
  388. return Value(false);
  389. i32 from_index = 0;
  390. if (interpreter.argument_count() >= 2) {
  391. from_index = interpreter.argument(1).to_i32(interpreter);
  392. if (interpreter.exception())
  393. return {};
  394. if (from_index >= array_size)
  395. return Value(false);
  396. auto negative_min_index = ((array_size - 1) * -1);
  397. if (from_index < negative_min_index)
  398. from_index = 0;
  399. else if (from_index < 0)
  400. from_index = array_size + from_index;
  401. }
  402. auto value_to_find = interpreter.argument(0);
  403. for (i32 i = from_index; i < array_size; ++i) {
  404. auto& element = array->elements().at(i);
  405. if (same_value_zero(interpreter, element, value_to_find))
  406. return Value(true);
  407. }
  408. return Value(false);
  409. }
  410. Value ArrayPrototype::find(Interpreter& interpreter)
  411. {
  412. auto result = js_undefined();
  413. for_each_item(
  414. interpreter, "find", [&](auto, auto value, auto callback_result) {
  415. if (callback_result.to_boolean()) {
  416. result = value;
  417. return IterationDecision::Break;
  418. }
  419. return IterationDecision::Continue;
  420. },
  421. false);
  422. return result;
  423. }
  424. Value ArrayPrototype::find_index(Interpreter& interpreter)
  425. {
  426. auto result_index = -1;
  427. for_each_item(
  428. interpreter, "findIndex", [&](auto index, auto, auto callback_result) {
  429. if (callback_result.to_boolean()) {
  430. result_index = index;
  431. return IterationDecision::Break;
  432. }
  433. return IterationDecision::Continue;
  434. },
  435. false);
  436. return Value(result_index);
  437. }
  438. Value ArrayPrototype::some(Interpreter& interpreter)
  439. {
  440. auto result = false;
  441. for_each_item(interpreter, "some", [&](auto, auto, auto callback_result) {
  442. if (callback_result.to_boolean()) {
  443. result = true;
  444. return IterationDecision::Break;
  445. }
  446. return IterationDecision::Continue;
  447. });
  448. return Value(result);
  449. }
  450. Value ArrayPrototype::every(Interpreter& interpreter)
  451. {
  452. auto result = true;
  453. for_each_item(interpreter, "every", [&](auto, auto, auto callback_result) {
  454. if (!callback_result.to_boolean()) {
  455. result = false;
  456. return IterationDecision::Break;
  457. }
  458. return IterationDecision::Continue;
  459. });
  460. return Value(result);
  461. }
  462. }