ArrayPrototype.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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("reverse", reverse, 0, attr);
  59. put_native_function("lastIndexOf", last_index_of, 1, attr);
  60. put_native_function("includes", includes, 1, attr);
  61. put_native_function("find", find, 1, attr);
  62. put_native_function("findIndex", find_index, 1, attr);
  63. put_native_function("some", some, 1, attr);
  64. put_native_function("every", every, 1, attr);
  65. put("length", Value(0), Attribute::Configurable);
  66. }
  67. ArrayPrototype::~ArrayPrototype()
  68. {
  69. }
  70. static Function* callback_from_args(Interpreter& interpreter, const String& name)
  71. {
  72. if (interpreter.argument_count() < 1) {
  73. interpreter.throw_exception<TypeError>(String::format("Array.prototype.%s() requires at least one argument", name.characters()));
  74. return nullptr;
  75. }
  76. auto callback = interpreter.argument(0);
  77. if (!callback.is_function()) {
  78. interpreter.throw_exception<TypeError>(String::format("%s is not a function", callback.to_string_without_side_effects().characters()));
  79. return nullptr;
  80. }
  81. return &callback.as_function();
  82. }
  83. static size_t get_length(Interpreter& interpreter, Object& object)
  84. {
  85. auto length_property = object.get("length");
  86. if (interpreter.exception())
  87. return 0;
  88. return length_property.to_size_t(interpreter);
  89. }
  90. 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)
  91. {
  92. auto* this_object = interpreter.this_value().to_object(interpreter);
  93. if (!this_object)
  94. return;
  95. auto initial_length = get_length(interpreter, *this_object);
  96. if (interpreter.exception())
  97. return;
  98. auto* callback_function = callback_from_args(interpreter, name);
  99. if (!callback_function)
  100. return;
  101. auto this_value = interpreter.argument(1);
  102. for (size_t i = 0; i < initial_length; ++i) {
  103. auto value = this_object->get_by_index(i);
  104. if (interpreter.exception())
  105. return;
  106. if (value.is_empty()) {
  107. if (skip_empty)
  108. continue;
  109. value = js_undefined();
  110. }
  111. MarkedValueList arguments(interpreter.heap());
  112. arguments.append(value);
  113. arguments.append(Value((i32)i));
  114. arguments.append(this_object);
  115. auto callback_result = interpreter.call(*callback_function, this_value, move(arguments));
  116. if (interpreter.exception())
  117. return;
  118. if (callback(i, value, callback_result) == IterationDecision::Break)
  119. break;
  120. }
  121. }
  122. Value ArrayPrototype::filter(Interpreter& interpreter)
  123. {
  124. auto* new_array = Array::create(interpreter.global_object());
  125. for_each_item(interpreter, "filter", [&](auto, auto value, auto callback_result) {
  126. if (callback_result.to_boolean())
  127. new_array->elements().append(value);
  128. return IterationDecision::Continue;
  129. });
  130. return Value(new_array);
  131. }
  132. Value ArrayPrototype::for_each(Interpreter& interpreter)
  133. {
  134. for_each_item(interpreter, "forEach", [](auto, auto, auto) {
  135. return IterationDecision::Continue;
  136. });
  137. return js_undefined();
  138. }
  139. Value ArrayPrototype::map(Interpreter& interpreter)
  140. {
  141. auto* this_object = interpreter.this_value().to_object(interpreter);
  142. if (!this_object)
  143. return {};
  144. auto initial_length = get_length(interpreter, *this_object);
  145. if (interpreter.exception())
  146. return {};
  147. auto* new_array = Array::create(interpreter.global_object());
  148. new_array->elements().resize(initial_length);
  149. for_each_item(interpreter, "map", [&](auto index, auto, auto callback_result) {
  150. new_array->elements()[index] = callback_result;
  151. return IterationDecision::Continue;
  152. });
  153. return Value(new_array);
  154. }
  155. Value ArrayPrototype::push(Interpreter& interpreter)
  156. {
  157. auto* this_object = interpreter.this_value().to_object(interpreter);
  158. if (!this_object)
  159. return {};
  160. if (this_object->is_array()) {
  161. auto* array = static_cast<Array*>(this_object);
  162. for (size_t i = 0; i < interpreter.argument_count(); ++i)
  163. array->elements().append(interpreter.argument(i));
  164. return Value(array->length());
  165. }
  166. auto length = get_length(interpreter, *this_object);
  167. if (interpreter.exception())
  168. return {};
  169. auto argument_count = interpreter.argument_count();
  170. auto new_length = length + argument_count;
  171. if (new_length > MAX_ARRAY_LIKE_INDEX)
  172. return interpreter.throw_exception<TypeError>("Maximum array size exceeded");
  173. for (size_t i = 0; i < argument_count; ++i)
  174. this_object->put_by_index(length + i, interpreter.argument(i));
  175. auto new_length_value = Value((i32)new_length);
  176. this_object->put("length", new_length_value);
  177. if (interpreter.exception())
  178. return {};
  179. return new_length_value;
  180. }
  181. Value ArrayPrototype::unshift(Interpreter& interpreter)
  182. {
  183. auto* array = array_from(interpreter);
  184. if (!array)
  185. return {};
  186. for (size_t i = 0; i < interpreter.argument_count(); ++i)
  187. array->elements().insert(i, interpreter.argument(i));
  188. return Value(array->length());
  189. }
  190. Value ArrayPrototype::pop(Interpreter& interpreter)
  191. {
  192. auto* this_object = interpreter.this_value().to_object(interpreter);
  193. if (!this_object)
  194. return {};
  195. if (this_object->is_array()) {
  196. auto* array = static_cast<Array*>(this_object);
  197. if (array->elements().is_empty())
  198. return js_undefined();
  199. return array->elements().take_last().value_or(js_undefined());
  200. }
  201. auto length = get_length(interpreter, *this_object);
  202. if (length == 0) {
  203. this_object->put("length", Value(0));
  204. return js_undefined();
  205. }
  206. auto index = length - 1;
  207. auto element = this_object->get_by_index(index).value_or(js_undefined());
  208. if (interpreter.exception())
  209. return {};
  210. this_object->delete_property(PropertyName(index));
  211. this_object->put("length", Value((i32)index));
  212. if (interpreter.exception())
  213. return {};
  214. return element;
  215. }
  216. Value ArrayPrototype::shift(Interpreter& interpreter)
  217. {
  218. auto* array = array_from(interpreter);
  219. if (!array)
  220. return {};
  221. if (array->elements().is_empty())
  222. return js_undefined();
  223. return array->elements().take_first().value_or(js_undefined());
  224. }
  225. Value ArrayPrototype::to_string(Interpreter& interpreter)
  226. {
  227. auto* this_object = interpreter.this_value().to_object(interpreter);
  228. if (!this_object)
  229. return {};
  230. auto join_function = this_object->get("join");
  231. if (interpreter.exception())
  232. return {};
  233. if (!join_function.is_function())
  234. return ObjectPrototype::to_string(interpreter);
  235. return interpreter.call(join_function.as_function(), this_object);
  236. }
  237. Value ArrayPrototype::join(Interpreter& interpreter)
  238. {
  239. auto* this_object = interpreter.this_value().to_object(interpreter);
  240. if (!this_object)
  241. return {};
  242. String separator = ",";
  243. if (interpreter.argument_count()) {
  244. separator = interpreter.argument(0).to_string(interpreter);
  245. if (interpreter.exception())
  246. return {};
  247. }
  248. auto length = get_length(interpreter, *this_object);
  249. if (interpreter.exception())
  250. return {};
  251. StringBuilder builder;
  252. for (size_t i = 0; i < length; ++i) {
  253. if (i > 0)
  254. builder.append(separator);
  255. auto value = this_object->get_by_index(i).value_or(js_undefined());
  256. if (interpreter.exception())
  257. return {};
  258. if (value.is_undefined() || value.is_null())
  259. continue;
  260. auto string = value.to_string(interpreter);
  261. if (interpreter.exception())
  262. return {};
  263. builder.append(string);
  264. }
  265. return js_string(interpreter, builder.to_string());
  266. }
  267. Value ArrayPrototype::concat(Interpreter& interpreter)
  268. {
  269. auto* array = array_from(interpreter);
  270. if (!array)
  271. return {};
  272. auto* new_array = Array::create(interpreter.global_object());
  273. new_array->elements().append(array->elements());
  274. for (size_t i = 0; i < interpreter.argument_count(); ++i) {
  275. auto argument = interpreter.argument(i);
  276. if (argument.is_array()) {
  277. auto& argument_object = argument.as_object();
  278. new_array->elements().append(argument_object.elements());
  279. } else {
  280. new_array->elements().append(argument);
  281. }
  282. }
  283. return Value(new_array);
  284. }
  285. Value ArrayPrototype::slice(Interpreter& interpreter)
  286. {
  287. auto* array = array_from(interpreter);
  288. if (!array)
  289. return {};
  290. auto* new_array = Array::create(interpreter.global_object());
  291. if (interpreter.argument_count() == 0) {
  292. new_array->elements().append(array->elements());
  293. return new_array;
  294. }
  295. ssize_t array_size = static_cast<ssize_t>(array->elements().size());
  296. auto start_slice = interpreter.argument(0).to_i32(interpreter);
  297. if (interpreter.exception())
  298. return {};
  299. auto end_slice = array_size;
  300. if (start_slice > array_size)
  301. return new_array;
  302. if (start_slice < 0)
  303. start_slice = end_slice + start_slice;
  304. if (interpreter.argument_count() >= 2) {
  305. end_slice = interpreter.argument(1).to_i32(interpreter);
  306. if (interpreter.exception())
  307. return {};
  308. if (end_slice < 0)
  309. end_slice = array_size + end_slice;
  310. else if (end_slice > array_size)
  311. end_slice = array_size;
  312. }
  313. size_t array_capacity = start_slice + array_size - end_slice;
  314. new_array->elements().ensure_capacity(array_capacity);
  315. for (ssize_t i = start_slice; i < end_slice; ++i) {
  316. new_array->elements().append(array->elements().at(i));
  317. }
  318. return new_array;
  319. }
  320. Value ArrayPrototype::index_of(Interpreter& interpreter)
  321. {
  322. auto* array = array_from(interpreter);
  323. if (!array)
  324. return {};
  325. i32 array_size = static_cast<i32>(array->elements().size());
  326. if (array_size == 0)
  327. return Value(-1);
  328. i32 from_index = 0;
  329. if (interpreter.argument_count() >= 2) {
  330. from_index = interpreter.argument(1).to_i32(interpreter);
  331. if (interpreter.exception())
  332. return {};
  333. if (from_index >= array_size)
  334. return Value(-1);
  335. auto negative_min_index = ((array_size - 1) * -1);
  336. if (from_index < negative_min_index)
  337. from_index = 0;
  338. else if (from_index < 0)
  339. from_index = array_size + from_index;
  340. }
  341. auto search_element = interpreter.argument(0);
  342. for (i32 i = from_index; i < array_size; ++i) {
  343. auto& element = array->elements().at(i);
  344. if (strict_eq(interpreter, element, search_element))
  345. return Value(i);
  346. }
  347. return Value(-1);
  348. }
  349. Value ArrayPrototype::reduce(Interpreter& interpreter)
  350. {
  351. auto* this_object = interpreter.this_value().to_object(interpreter);
  352. if (!this_object)
  353. return {};
  354. auto initial_length = get_length(interpreter, *this_object);
  355. if (interpreter.exception())
  356. return {};
  357. size_t start = 0;
  358. auto accumulator = js_undefined();
  359. if (interpreter.argument_count() > 1) {
  360. accumulator = interpreter.argument(1);
  361. } else {
  362. bool start_found = false;
  363. while (!start_found && start < initial_length) {
  364. auto value = this_object->get_by_index(start);
  365. if (interpreter.exception())
  366. return {};
  367. start_found = !value.is_empty();
  368. if (start_found)
  369. accumulator = value;
  370. start += 1;
  371. }
  372. if (!start_found) {
  373. interpreter.throw_exception<TypeError>("Reduce of empty array with no initial value");
  374. return {};
  375. }
  376. }
  377. auto* callback_function = callback_from_args(interpreter, "reduce");
  378. if (!callback_function)
  379. return {};
  380. auto this_value = js_undefined();
  381. for (size_t i = start; i < initial_length; ++i) {
  382. auto value = this_object->get_by_index(i);
  383. if (interpreter.exception())
  384. return {};
  385. if (value.is_empty())
  386. continue;
  387. MarkedValueList arguments(interpreter.heap());
  388. arguments.append(accumulator);
  389. arguments.append(value);
  390. arguments.append(Value((i32)i));
  391. arguments.append(this_object);
  392. accumulator = interpreter.call(*callback_function, this_value, move(arguments));
  393. if (interpreter.exception())
  394. return {};
  395. }
  396. return accumulator;
  397. }
  398. Value ArrayPrototype::reverse(Interpreter& interpreter)
  399. {
  400. auto* array = array_from(interpreter);
  401. if (!array)
  402. return {};
  403. if (array->elements().size() == 0)
  404. return array;
  405. Vector<Value> array_reverse;
  406. array_reverse.ensure_capacity(array->elements().size());
  407. for (ssize_t i = array->elements().size() - 1; i >= 0; --i)
  408. array_reverse.append(array->elements().at(i));
  409. array->elements() = move(array_reverse);
  410. return array;
  411. }
  412. Value ArrayPrototype::last_index_of(Interpreter& interpreter)
  413. {
  414. auto* array = array_from(interpreter);
  415. if (!array)
  416. return {};
  417. i32 array_size = static_cast<i32>(array->elements().size());
  418. if (array_size == 0)
  419. return Value(-1);
  420. i32 from_index = array_size - 1;
  421. if (interpreter.argument_count() >= 2) {
  422. from_index = interpreter.argument(1).to_i32(interpreter);
  423. if (interpreter.exception())
  424. return {};
  425. if (from_index >= 0)
  426. from_index = min(from_index, array_size - 1);
  427. else
  428. from_index = array_size + from_index;
  429. }
  430. auto search_element = interpreter.argument(0);
  431. for (i32 i = from_index; i >= 0; --i) {
  432. auto& element = array->elements().at(i);
  433. if (strict_eq(interpreter, element, search_element))
  434. return Value(i);
  435. }
  436. return Value(-1);
  437. }
  438. Value ArrayPrototype::includes(Interpreter& interpreter)
  439. {
  440. auto* array = array_from(interpreter);
  441. if (!array)
  442. return {};
  443. i32 array_size = array->elements().size();
  444. if (array_size == 0)
  445. return Value(false);
  446. i32 from_index = 0;
  447. if (interpreter.argument_count() >= 2) {
  448. from_index = interpreter.argument(1).to_i32(interpreter);
  449. if (interpreter.exception())
  450. return {};
  451. if (from_index >= array_size)
  452. return Value(false);
  453. auto negative_min_index = ((array_size - 1) * -1);
  454. if (from_index < negative_min_index)
  455. from_index = 0;
  456. else if (from_index < 0)
  457. from_index = array_size + from_index;
  458. }
  459. auto value_to_find = interpreter.argument(0);
  460. for (i32 i = from_index; i < array_size; ++i) {
  461. auto& element = array->elements().at(i);
  462. if (same_value_zero(interpreter, element, value_to_find))
  463. return Value(true);
  464. }
  465. return Value(false);
  466. }
  467. Value ArrayPrototype::find(Interpreter& interpreter)
  468. {
  469. auto result = js_undefined();
  470. for_each_item(
  471. interpreter, "find", [&](auto, auto value, auto callback_result) {
  472. if (callback_result.to_boolean()) {
  473. result = value;
  474. return IterationDecision::Break;
  475. }
  476. return IterationDecision::Continue;
  477. },
  478. false);
  479. return result;
  480. }
  481. Value ArrayPrototype::find_index(Interpreter& interpreter)
  482. {
  483. auto result_index = -1;
  484. for_each_item(
  485. interpreter, "findIndex", [&](auto index, auto, auto callback_result) {
  486. if (callback_result.to_boolean()) {
  487. result_index = index;
  488. return IterationDecision::Break;
  489. }
  490. return IterationDecision::Continue;
  491. },
  492. false);
  493. return Value(result_index);
  494. }
  495. Value ArrayPrototype::some(Interpreter& interpreter)
  496. {
  497. auto result = false;
  498. for_each_item(interpreter, "some", [&](auto, auto, auto callback_result) {
  499. if (callback_result.to_boolean()) {
  500. result = true;
  501. return IterationDecision::Break;
  502. }
  503. return IterationDecision::Continue;
  504. });
  505. return Value(result);
  506. }
  507. Value ArrayPrototype::every(Interpreter& interpreter)
  508. {
  509. auto result = true;
  510. for_each_item(interpreter, "every", [&](auto, auto, auto callback_result) {
  511. if (!callback_result.to_boolean()) {
  512. result = false;
  513. return IterationDecision::Break;
  514. }
  515. return IterationDecision::Continue;
  516. });
  517. return Value(result);
  518. }
  519. }