ArrayPrototype.cpp 21 KB

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