ArrayPrototype.cs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  1. #pragma warning disable CA1859 // Use concrete types when possible for improved performance -- most of prototype methods return JsValue
  2. using System.Linq;
  3. using System.Text;
  4. using Jint.Collections;
  5. using Jint.Native.Iterator;
  6. using Jint.Native.Number;
  7. using Jint.Native.Object;
  8. using Jint.Native.Symbol;
  9. using Jint.Runtime;
  10. using Jint.Runtime.Descriptors;
  11. using Jint.Runtime.Descriptors.Specialized;
  12. using Jint.Runtime.Interop;
  13. namespace Jint.Native.Array
  14. {
  15. /// <summary>
  16. /// https://tc39.es/ecma262/#sec-properties-of-the-array-prototype-object
  17. /// </summary>
  18. public sealed class ArrayPrototype : ArrayInstance
  19. {
  20. private readonly Realm _realm;
  21. private readonly ArrayConstructor _constructor;
  22. internal ClrFunction? _originalIteratorFunction;
  23. internal ArrayPrototype(
  24. Engine engine,
  25. Realm realm,
  26. ArrayConstructor arrayConstructor,
  27. ObjectPrototype objectPrototype) : base(engine, InternalTypes.Object)
  28. {
  29. _prototype = objectPrototype;
  30. _length = new PropertyDescriptor(JsNumber.PositiveZero, PropertyFlag.Writable);
  31. _realm = realm;
  32. _constructor = arrayConstructor;
  33. }
  34. protected override void Initialize()
  35. {
  36. const PropertyFlag PropertyFlags = PropertyFlag.Writable | PropertyFlag.Configurable;
  37. var properties = new PropertyDictionary(38, checkExistingKeys: false)
  38. {
  39. ["constructor"] = new PropertyDescriptor(_constructor, PropertyFlag.NonEnumerable),
  40. ["at"] = new PropertyDescriptor(new ClrFunction(Engine, "at", At, 1, PropertyFlag.Configurable), PropertyFlags),
  41. ["concat"] = new PropertyDescriptor(new ClrFunction(Engine, "concat", Concat, 1, PropertyFlag.Configurable), PropertyFlags),
  42. ["copyWithin"] = new PropertyDescriptor(new ClrFunction(Engine, "copyWithin", CopyWithin, 2, PropertyFlag.Configurable), PropertyFlags),
  43. ["entries"] = new PropertyDescriptor(new ClrFunction(Engine, "entries", Entries, 0, PropertyFlag.Configurable), PropertyFlags),
  44. ["every"] = new PropertyDescriptor(new ClrFunction(Engine, "every", Every, 1, PropertyFlag.Configurable), PropertyFlags),
  45. ["fill"] = new PropertyDescriptor(new ClrFunction(Engine, "fill", Fill, 1, PropertyFlag.Configurable), PropertyFlags),
  46. ["filter"] = new PropertyDescriptor(new ClrFunction(Engine, "filter", Filter, 1, PropertyFlag.Configurable), PropertyFlags),
  47. ["find"] = new PropertyDescriptor(new ClrFunction(Engine, "find", Find, 1, PropertyFlag.Configurable), PropertyFlags),
  48. ["findIndex"] = new PropertyDescriptor(new ClrFunction(Engine, "findIndex", FindIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  49. ["findLast"] = new PropertyDescriptor(new ClrFunction(Engine, "findLast", FindLast, 1, PropertyFlag.Configurable), PropertyFlags),
  50. ["findLastIndex"] = new PropertyDescriptor(new ClrFunction(Engine, "findLastIndex", FindLastIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  51. ["flat"] = new PropertyDescriptor(new ClrFunction(Engine, "flat", Flat, 0, PropertyFlag.Configurable), PropertyFlags),
  52. ["flatMap"] = new PropertyDescriptor(new ClrFunction(Engine, "flatMap", FlatMap, 1, PropertyFlag.Configurable), PropertyFlags),
  53. ["forEach"] = new PropertyDescriptor(new ClrFunction(Engine, "forEach", ForEach, 1, PropertyFlag.Configurable), PropertyFlags),
  54. ["includes"] = new PropertyDescriptor(new ClrFunction(Engine, "includes", Includes, 1, PropertyFlag.Configurable), PropertyFlags),
  55. ["indexOf"] = new PropertyDescriptor(new ClrFunction(Engine, "indexOf", IndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  56. ["join"] = new PropertyDescriptor(new ClrFunction(Engine, "join", Join, 1, PropertyFlag.Configurable), PropertyFlags),
  57. ["keys"] = new PropertyDescriptor(new ClrFunction(Engine, "keys", Keys, 0, PropertyFlag.Configurable), PropertyFlags),
  58. ["lastIndexOf"] = new PropertyDescriptor(new ClrFunction(Engine, "lastIndexOf", LastIndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  59. ["map"] = new PropertyDescriptor(new ClrFunction(Engine, "map", Map, 1, PropertyFlag.Configurable), PropertyFlags),
  60. ["pop"] = new PropertyDescriptor(new ClrFunction(Engine, "pop", Pop, 0, PropertyFlag.Configurable), PropertyFlags),
  61. ["push"] = new PropertyDescriptor(new ClrFunction(Engine, "push", Push, 1, PropertyFlag.Configurable), PropertyFlags),
  62. ["reduce"] = new PropertyDescriptor(new ClrFunction(Engine, "reduce", Reduce, 1, PropertyFlag.Configurable), PropertyFlags),
  63. ["reduceRight"] = new PropertyDescriptor(new ClrFunction(Engine, "reduceRight", ReduceRight, 1, PropertyFlag.Configurable), PropertyFlags),
  64. ["reverse"] = new PropertyDescriptor(new ClrFunction(Engine, "reverse", Reverse, 0, PropertyFlag.Configurable), PropertyFlags),
  65. ["shift"] = new PropertyDescriptor(new ClrFunction(Engine, "shift", Shift, 0, PropertyFlag.Configurable), PropertyFlags),
  66. ["slice"] = new PropertyDescriptor(new ClrFunction(Engine, "slice", Slice, 2, PropertyFlag.Configurable), PropertyFlags),
  67. ["some"] = new PropertyDescriptor(new ClrFunction(Engine, "some", Some, 1, PropertyFlag.Configurable), PropertyFlags),
  68. ["sort"] = new PropertyDescriptor(new ClrFunction(Engine, "sort", Sort, 1, PropertyFlag.Configurable), PropertyFlags),
  69. ["splice"] = new PropertyDescriptor(new ClrFunction(Engine, "splice", Splice, 2, PropertyFlag.Configurable), PropertyFlags),
  70. ["toLocaleString"] = new PropertyDescriptor(new ClrFunction(Engine, "toLocaleString", ToLocaleString, 0, PropertyFlag.Configurable), PropertyFlags),
  71. ["toReversed"] = new PropertyDescriptor(new ClrFunction(Engine, "toReversed", ToReversed, 0, PropertyFlag.Configurable), PropertyFlags),
  72. ["toSorted"] = new PropertyDescriptor(new ClrFunction(Engine, "toSorted", ToSorted, 1, PropertyFlag.Configurable), PropertyFlags),
  73. ["toSpliced"] = new PropertyDescriptor(new ClrFunction(Engine, "toSpliced", ToSpliced, 2, PropertyFlag.Configurable), PropertyFlags),
  74. ["toString"] = new PropertyDescriptor(new ClrFunction(Engine, "toString", ToString, 0, PropertyFlag.Configurable), PropertyFlags),
  75. ["unshift"] = new PropertyDescriptor(new ClrFunction(Engine, "unshift", Unshift, 1, PropertyFlag.Configurable), PropertyFlags),
  76. ["values"] = new PropertyDescriptor(new ClrFunction(Engine, "values", Values, 0, PropertyFlag.Configurable), PropertyFlags),
  77. ["with"] = new PropertyDescriptor(new ClrFunction(Engine, "with", With, 2, PropertyFlag.Configurable), PropertyFlags),
  78. };
  79. SetProperties(properties);
  80. _originalIteratorFunction = new ClrFunction(Engine, "iterator", Values, 1);
  81. var symbols = new SymbolDictionary(2)
  82. {
  83. [GlobalSymbolRegistry.Iterator] = new PropertyDescriptor(_originalIteratorFunction, PropertyFlags),
  84. [GlobalSymbolRegistry.Unscopables] = new LazyPropertyDescriptor(_engine, static state =>
  85. {
  86. var unscopables = new JsObject((Engine) state!)
  87. {
  88. _prototype = null
  89. };
  90. unscopables.FastSetDataProperty("at", JsBoolean.True);
  91. unscopables.FastSetDataProperty("copyWithin", JsBoolean.True);
  92. unscopables.FastSetDataProperty("entries", JsBoolean.True);
  93. unscopables.FastSetDataProperty("fill", JsBoolean.True);
  94. unscopables.FastSetDataProperty("find", JsBoolean.True);
  95. unscopables.FastSetDataProperty("findIndex", JsBoolean.True);
  96. unscopables.FastSetDataProperty("findLast", JsBoolean.True);
  97. unscopables.FastSetDataProperty("findLastIndex", JsBoolean.True);
  98. unscopables.FastSetDataProperty("flat", JsBoolean.True);
  99. unscopables.FastSetDataProperty("flatMap", JsBoolean.True);
  100. unscopables.FastSetDataProperty("includes", JsBoolean.True);
  101. unscopables.FastSetDataProperty("keys", JsBoolean.True);
  102. unscopables.FastSetDataProperty("toReversed", JsBoolean.True);
  103. unscopables.FastSetDataProperty("toSorted", JsBoolean.True);
  104. unscopables.FastSetDataProperty("toSpliced", JsBoolean.True);
  105. unscopables.FastSetDataProperty("values", JsBoolean.True);
  106. return unscopables;
  107. }, PropertyFlag.Configurable)
  108. };
  109. SetSymbols(symbols);
  110. }
  111. private ObjectInstance Keys(JsValue thisObject, JsValue[] arguments)
  112. {
  113. if (thisObject is ObjectInstance oi && oi.IsArrayLike)
  114. {
  115. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.Key);
  116. }
  117. ExceptionHelper.ThrowTypeError(_realm, "cannot construct iterator");
  118. return null;
  119. }
  120. internal ObjectInstance Values(JsValue thisObject, JsValue[] arguments)
  121. {
  122. if (thisObject is ObjectInstance oi && oi.IsArrayLike)
  123. {
  124. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.Value);
  125. }
  126. ExceptionHelper.ThrowTypeError(_realm, "cannot construct iterator");
  127. return null;
  128. }
  129. private ObjectInstance With(JsValue thisObject, JsValue[] arguments)
  130. {
  131. var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObject), forWrite: false);
  132. var len = o.GetLongLength();
  133. var relativeIndex = TypeConverter.ToIntegerOrInfinity(arguments.At(0));
  134. var value = arguments.At(1);
  135. long actualIndex;
  136. if (relativeIndex >= 0)
  137. {
  138. actualIndex = (long) relativeIndex;
  139. }
  140. else
  141. {
  142. actualIndex = (long) (len + relativeIndex);
  143. }
  144. if (actualIndex >= (long) len || actualIndex < 0)
  145. {
  146. ExceptionHelper.ThrowRangeError(_realm, "Invalid start index");
  147. }
  148. var a = CreateBackingArray(len);
  149. ulong k = 0;
  150. while (k < len)
  151. {
  152. a[k] = k == (ulong) actualIndex ? value : o.Get(k);
  153. k++;
  154. }
  155. return new JsArray(_engine, a);
  156. }
  157. private ObjectInstance Entries(JsValue thisObject, JsValue[] arguments)
  158. {
  159. if (thisObject is ObjectInstance oi && oi.IsArrayLike)
  160. {
  161. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.KeyAndValue);
  162. }
  163. ExceptionHelper.ThrowTypeError(_realm, "cannot construct iterator");
  164. return null;
  165. }
  166. /// <summary>
  167. /// https://tc39.es/ecma262/#sec-array.prototype.fill
  168. /// </summary>
  169. private JsValue Fill(JsValue thisObject, JsValue[] arguments)
  170. {
  171. var value = arguments.At(0);
  172. var start = arguments.At(1);
  173. var end = arguments.At(2);
  174. var o = TypeConverter.ToObject(_realm, thisObject);
  175. var operations = ArrayOperations.For(o, forWrite: true);
  176. var length = operations.GetLongLength();
  177. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  178. ulong k;
  179. if (double.IsNegativeInfinity(relativeStart))
  180. {
  181. k = 0;
  182. }
  183. else if (relativeStart < 0)
  184. {
  185. k = (ulong) System.Math.Max(length + relativeStart, 0);
  186. }
  187. else
  188. {
  189. k = (ulong) System.Math.Min(relativeStart, length);
  190. }
  191. var relativeEnd = end.IsUndefined() ? length : TypeConverter.ToIntegerOrInfinity(end);
  192. ulong final;
  193. if (double.IsNegativeInfinity(relativeEnd))
  194. {
  195. final = 0;
  196. }
  197. else if (relativeEnd < 0)
  198. {
  199. final = (ulong) System.Math.Max(length + relativeEnd, 0);
  200. }
  201. else
  202. {
  203. final = (ulong) System.Math.Min(relativeEnd, length);
  204. }
  205. for (var i = k; i < final; ++i)
  206. {
  207. operations.Set(i, value, throwOnError: false);
  208. }
  209. return o;
  210. }
  211. /// <summary>
  212. /// https://tc39.es/ecma262/#sec-array.prototype.copywithin
  213. /// </summary>
  214. private JsValue CopyWithin(JsValue thisObject, JsValue[] arguments)
  215. {
  216. var o = TypeConverter.ToObject(_realm, thisObject);
  217. JsValue target = arguments.At(0);
  218. JsValue start = arguments.At(1);
  219. JsValue end = arguments.At(2);
  220. var operations = ArrayOperations.For(o, forWrite: true);
  221. var len = operations.GetLongLength();
  222. var relativeTarget = TypeConverter.ToIntegerOrInfinity(target);
  223. var to = relativeTarget < 0 ?
  224. System.Math.Max(len + relativeTarget, 0) :
  225. System.Math.Min(relativeTarget, len);
  226. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  227. long from;
  228. if (double.IsNegativeInfinity(relativeStart))
  229. {
  230. from = 0;
  231. }
  232. else if (relativeStart < 0)
  233. {
  234. from = (long) System.Math.Max(len + relativeStart, 0);
  235. }
  236. else
  237. {
  238. from = (long) System.Math.Min(relativeStart, len);
  239. }
  240. var relativeEnd = end.IsUndefined() ? len : TypeConverter.ToIntegerOrInfinity(end);
  241. long final;
  242. if (double.IsNegativeInfinity(relativeEnd))
  243. {
  244. final = 0;
  245. }
  246. else if (relativeEnd < 0)
  247. {
  248. final = (long) System.Math.Max(len + relativeEnd, 0);
  249. }
  250. else
  251. {
  252. final = (long) System.Math.Min(relativeEnd, len);
  253. }
  254. var count = (long) System.Math.Min(final - from, len - to);
  255. long direction = 1;
  256. if (from < to && to < from + count)
  257. {
  258. direction = -1;
  259. from += count - 1;
  260. to += count - 1;
  261. }
  262. while (count > 0)
  263. {
  264. var fromPresent = operations.HasProperty((ulong) from);
  265. if (fromPresent)
  266. {
  267. var fromValue = operations.Get((ulong) from);
  268. operations.Set((ulong) to, fromValue, updateLength: true, throwOnError: true);
  269. }
  270. else
  271. {
  272. operations.DeletePropertyOrThrow((ulong) to);
  273. }
  274. from += direction;
  275. to += direction;
  276. count--;
  277. }
  278. return o;
  279. }
  280. /// <summary>
  281. /// https://tc39.es/ecma262/#sec-array.prototype.lastindexof
  282. /// </summary>
  283. private JsValue LastIndexOf(JsValue thisObject, JsValue[] arguments)
  284. {
  285. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  286. var len = o.GetLongLength();
  287. if (len == 0)
  288. {
  289. return JsNumber.IntegerNegativeOne;
  290. }
  291. var n = arguments.Length > 1
  292. ? TypeConverter.ToInteger(arguments[1])
  293. : len - 1;
  294. double k;
  295. if (n >= 0)
  296. {
  297. k = System.Math.Min(n, len - 1); // min
  298. }
  299. else
  300. {
  301. k = len - System.Math.Abs(n);
  302. }
  303. if (k < 0 || k > ArrayOperations.MaxArrayLikeLength)
  304. {
  305. return JsNumber.IntegerNegativeOne;
  306. }
  307. var searchElement = arguments.At(0);
  308. var i = (ulong) k;
  309. for (; ; i--)
  310. {
  311. var kPresent = o.HasProperty(i);
  312. if (kPresent)
  313. {
  314. var elementK = o.Get(i);
  315. if (elementK == searchElement)
  316. {
  317. return i;
  318. }
  319. }
  320. if (i == 0)
  321. {
  322. break;
  323. }
  324. }
  325. return JsNumber.IntegerNegativeOne;
  326. }
  327. /// <summary>
  328. /// https://tc39.es/ecma262/#sec-array.prototype.reduce
  329. /// </summary>
  330. private JsValue Reduce(JsValue thisObject, JsValue[] arguments)
  331. {
  332. var callbackfn = arguments.At(0);
  333. var initialValue = arguments.At(1);
  334. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  335. var len = o.GetLength();
  336. var callable = GetCallable(callbackfn);
  337. if (len == 0 && arguments.Length < 2)
  338. {
  339. ExceptionHelper.ThrowTypeError(_realm);
  340. }
  341. var k = 0;
  342. JsValue accumulator = Undefined;
  343. if (arguments.Length > 1)
  344. {
  345. accumulator = initialValue;
  346. }
  347. else
  348. {
  349. var kPresent = false;
  350. while (kPresent == false && k < len)
  351. {
  352. if (kPresent = o.TryGetValue((uint) k, out var temp))
  353. {
  354. accumulator = temp;
  355. }
  356. k++;
  357. }
  358. if (kPresent == false)
  359. {
  360. ExceptionHelper.ThrowTypeError(_realm);
  361. }
  362. }
  363. var args = new JsValue[4];
  364. args[3] = o.Target;
  365. while (k < len)
  366. {
  367. var i = (uint) k;
  368. if (o.TryGetValue(i, out var kvalue))
  369. {
  370. args[0] = accumulator;
  371. args[1] = kvalue;
  372. args[2] = i;
  373. accumulator = callable.Call(Undefined, args);
  374. }
  375. k++;
  376. }
  377. return accumulator;
  378. }
  379. /// <summary>
  380. /// https://tc39.es/ecma262/#sec-array.prototype.filter
  381. /// </summary>
  382. private JsValue Filter(JsValue thisObject, JsValue[] arguments)
  383. {
  384. var callbackfn = arguments.At(0);
  385. var thisArg = arguments.At(1);
  386. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  387. var len = o.GetLength();
  388. var callable = GetCallable(callbackfn);
  389. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), 0);
  390. var operations = ArrayOperations.For(a, forWrite: true);
  391. uint to = 0;
  392. var args = _engine._jsValueArrayPool.RentArray(3);
  393. args[2] = o.Target;
  394. for (uint k = 0; k < len; k++)
  395. {
  396. if (o.TryGetValue(k, out var kvalue))
  397. {
  398. args[0] = kvalue;
  399. args[1] = k;
  400. var selected = callable.Call(thisArg, args);
  401. if (TypeConverter.ToBoolean(selected))
  402. {
  403. operations.CreateDataPropertyOrThrow(to, kvalue);
  404. to++;
  405. }
  406. }
  407. }
  408. operations.SetLength(to);
  409. _engine._jsValueArrayPool.ReturnArray(args);
  410. return a;
  411. }
  412. /// <summary>
  413. /// https://tc39.es/ecma262/#sec-array.prototype.map
  414. /// </summary>
  415. private JsValue Map(JsValue thisObject, JsValue[] arguments)
  416. {
  417. if (thisObject is JsArray { CanUseFastAccess: true } arrayInstance
  418. && !arrayInstance.HasOwnProperty(CommonProperties.Constructor))
  419. {
  420. return arrayInstance.Map(arguments);
  421. }
  422. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  423. var len = o.GetLongLength();
  424. if (len > ArrayOperations.MaxArrayLength)
  425. {
  426. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");
  427. }
  428. var callbackfn = arguments.At(0);
  429. var thisArg = arguments.At(1);
  430. var callable = GetCallable(callbackfn);
  431. var a = ArrayOperations.For(_realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), (uint) len), forWrite: true);
  432. var args = _engine._jsValueArrayPool.RentArray(3);
  433. args[2] = o.Target;
  434. for (uint k = 0; k < len; k++)
  435. {
  436. if (o.TryGetValue(k, out var kvalue))
  437. {
  438. args[0] = kvalue;
  439. args[1] = k;
  440. var mappedValue = callable.Call(thisArg, args);
  441. a.CreateDataPropertyOrThrow(k, mappedValue);
  442. }
  443. }
  444. _engine._jsValueArrayPool.ReturnArray(args);
  445. return a.Target;
  446. }
  447. /// <summary>
  448. /// https://tc39.es/ecma262/#sec-array.prototype.flat
  449. /// </summary>
  450. private JsValue Flat(JsValue thisObject, JsValue[] arguments)
  451. {
  452. var operations = ArrayOperations.For(_realm, thisObject, forWrite: false);
  453. var sourceLen = operations.GetLength();
  454. double depthNum = 1;
  455. var depth = arguments.At(0);
  456. if (!depth.IsUndefined())
  457. {
  458. depthNum = TypeConverter.ToIntegerOrInfinity(depth);
  459. }
  460. if (depthNum < 0)
  461. {
  462. depthNum = 0;
  463. }
  464. var A = _realm.Intrinsics.Array.ArraySpeciesCreate(operations.Target, 0);
  465. FlattenIntoArray(A, operations, sourceLen, 0, depthNum);
  466. return A;
  467. }
  468. /// <summary>
  469. /// https://tc39.es/ecma262/#sec-array.prototype.flatmap
  470. /// </summary>
  471. private JsValue FlatMap(JsValue thisObject, JsValue[] arguments)
  472. {
  473. var O = ArrayOperations.For(_realm, thisObject, forWrite: false);
  474. var mapperFunction = arguments.At(0);
  475. var thisArg = arguments.At(1);
  476. var sourceLen = O.GetLength();
  477. if (!mapperFunction.IsCallable)
  478. {
  479. ExceptionHelper.ThrowTypeError(_realm, "flatMap mapper function is not callable");
  480. }
  481. var A = _realm.Intrinsics.Array.ArraySpeciesCreate(O.Target, 0);
  482. FlattenIntoArray(A, O, sourceLen, 0, 1, (ICallable) mapperFunction, thisArg);
  483. return A;
  484. }
  485. /// <summary>
  486. /// https://tc39.es/ecma262/#sec-flattenintoarray
  487. /// </summary>
  488. private ulong FlattenIntoArray(
  489. ObjectInstance target,
  490. ArrayOperations source,
  491. uint sourceLen,
  492. ulong start,
  493. double depth,
  494. ICallable? mapperFunction = null,
  495. JsValue? thisArg = null)
  496. {
  497. var targetIndex = start;
  498. ulong sourceIndex = 0;
  499. var callArguments = System.Array.Empty<JsValue>();
  500. if (mapperFunction is not null)
  501. {
  502. callArguments = _engine._jsValueArrayPool.RentArray(3);
  503. callArguments[2] = source.Target;
  504. }
  505. while (sourceIndex < sourceLen)
  506. {
  507. var exists = source.HasProperty(sourceIndex);
  508. if (exists)
  509. {
  510. var element = source.Get(sourceIndex);
  511. if (mapperFunction is not null)
  512. {
  513. callArguments[0] = element;
  514. callArguments[1] = JsNumber.Create(sourceIndex);
  515. element = mapperFunction.Call(thisArg ?? Undefined, callArguments);
  516. }
  517. var shouldFlatten = false;
  518. if (depth > 0)
  519. {
  520. shouldFlatten = element.IsArray();
  521. }
  522. if (shouldFlatten)
  523. {
  524. var newDepth = double.IsPositiveInfinity(depth)
  525. ? depth
  526. : depth - 1;
  527. var objectInstance = (ObjectInstance) element;
  528. var elementLen = objectInstance.GetLength();
  529. targetIndex = FlattenIntoArray(target, ArrayOperations.For(objectInstance, forWrite: false), elementLen, targetIndex, newDepth);
  530. }
  531. else
  532. {
  533. if (targetIndex >= NumberConstructor.MaxSafeInteger)
  534. {
  535. ExceptionHelper.ThrowTypeError(_realm);
  536. }
  537. target.CreateDataPropertyOrThrow(targetIndex, element);
  538. targetIndex += 1;
  539. }
  540. }
  541. sourceIndex++;
  542. }
  543. if (mapperFunction is not null)
  544. {
  545. _engine._jsValueArrayPool.ReturnArray(callArguments);
  546. }
  547. return targetIndex;
  548. }
  549. private JsValue ForEach(JsValue thisObject, JsValue[] arguments)
  550. {
  551. var callbackfn = arguments.At(0);
  552. var thisArg = arguments.At(1);
  553. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  554. var len = o.GetLength();
  555. var callable = GetCallable(callbackfn);
  556. var args = _engine._jsValueArrayPool.RentArray(3);
  557. args[2] = o.Target;
  558. for (uint k = 0; k < len; k++)
  559. {
  560. if (o.TryGetValue(k, out var kvalue))
  561. {
  562. args[0] = kvalue;
  563. args[1] = k;
  564. callable.Call(thisArg, args);
  565. }
  566. }
  567. _engine._jsValueArrayPool.ReturnArray(args);
  568. return Undefined;
  569. }
  570. /// <summary>
  571. /// https://tc39.es/ecma262/#sec-array.prototype.includes
  572. /// </summary>
  573. private JsValue Includes(JsValue thisObject, JsValue[] arguments)
  574. {
  575. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  576. var len = (long) o.GetLongLength();
  577. if (len == 0)
  578. {
  579. return JsBoolean.False;
  580. }
  581. var searchElement = arguments.At(0);
  582. var fromIndex = arguments.At(1);
  583. long k = 0;
  584. var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
  585. if (double.IsPositiveInfinity(n))
  586. {
  587. return JsBoolean.False;
  588. }
  589. else if (double.IsNegativeInfinity(n))
  590. {
  591. n = 0;
  592. }
  593. else if (n >= 0)
  594. {
  595. k = (long) n;
  596. }
  597. else
  598. {
  599. k = len + (long) n;
  600. if (k < 0)
  601. {
  602. k = 0;
  603. }
  604. }
  605. while (k < len)
  606. {
  607. var value = o.Get((ulong) k);
  608. if (SameValueZeroComparer.Equals(value, searchElement))
  609. {
  610. return true;
  611. }
  612. k++;
  613. }
  614. return false;
  615. }
  616. private JsValue Some(JsValue thisObject, JsValue[] arguments)
  617. {
  618. var target = TypeConverter.ToObject(_realm, thisObject);
  619. return target.FindWithCallback(arguments, out _, out _, false);
  620. }
  621. /// <summary>
  622. /// https://tc39.es/ecma262/#sec-array.prototype.every
  623. /// </summary>
  624. private JsValue Every(JsValue thisObject, JsValue[] arguments)
  625. {
  626. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  627. ulong len = o.GetLongLength();
  628. if (len == 0)
  629. {
  630. return JsBoolean.True;
  631. }
  632. var callbackfn = arguments.At(0);
  633. var thisArg = arguments.At(1);
  634. var callable = GetCallable(callbackfn);
  635. var args = _engine._jsValueArrayPool.RentArray(3);
  636. args[2] = o.Target;
  637. for (uint k = 0; k < len; k++)
  638. {
  639. if (o.TryGetValue(k, out var kvalue))
  640. {
  641. args[0] = kvalue;
  642. args[1] = k;
  643. var testResult = callable.Call(thisArg, args);
  644. if (false == TypeConverter.ToBoolean(testResult))
  645. {
  646. return JsBoolean.False;
  647. }
  648. }
  649. }
  650. _engine._jsValueArrayPool.ReturnArray(args);
  651. return JsBoolean.True;
  652. }
  653. /// <summary>
  654. /// https://tc39.es/ecma262/#sec-array.prototype.indexof
  655. /// </summary>
  656. private JsValue IndexOf(JsValue thisObject, JsValue[] arguments)
  657. {
  658. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  659. var len = o.GetLongLength();
  660. if (len == 0)
  661. {
  662. return -1;
  663. }
  664. var startIndex = arguments.Length > 1
  665. ? TypeConverter.ToIntegerOrInfinity(arguments.At(1))
  666. : 0;
  667. if (startIndex > ArrayOperations.MaxArrayLikeLength)
  668. {
  669. return JsNumber.IntegerNegativeOne;
  670. }
  671. ulong k;
  672. if (startIndex < 0)
  673. {
  674. var abs = System.Math.Abs(startIndex);
  675. ulong temp = len - (uint) abs;
  676. if (abs > len || temp < 0)
  677. {
  678. temp = 0;
  679. }
  680. k = temp;
  681. }
  682. else
  683. {
  684. k = (ulong) startIndex;
  685. }
  686. if (k >= len)
  687. {
  688. return -1;
  689. }
  690. ulong smallestIndex = o.GetSmallestIndex(len);
  691. if (smallestIndex > k)
  692. {
  693. k = smallestIndex;
  694. }
  695. var searchElement = arguments.At(0);
  696. for (; k < len; k++)
  697. {
  698. var kPresent = o.HasProperty(k);
  699. if (kPresent)
  700. {
  701. var elementK = o.Get(k);
  702. if (elementK == searchElement)
  703. {
  704. return k;
  705. }
  706. }
  707. }
  708. return -1;
  709. }
  710. /// <summary>
  711. /// https://tc39.es/ecma262/#sec-array.prototype.find
  712. /// </summary>
  713. private JsValue Find(JsValue thisObject, JsValue[] arguments)
  714. {
  715. var target = TypeConverter.ToObject(_realm, thisObject);
  716. target.FindWithCallback(arguments, out _, out var value, visitUnassigned: true);
  717. return value;
  718. }
  719. /// <summary>
  720. /// https://tc39.es/ecma262/#sec-array.prototype.findindex
  721. /// </summary>
  722. private JsValue FindIndex(JsValue thisObject, JsValue[] arguments)
  723. {
  724. var target = TypeConverter.ToObject(_realm, thisObject);
  725. if (target.FindWithCallback(arguments, out var index, out _, visitUnassigned: true))
  726. {
  727. return index;
  728. }
  729. return -1;
  730. }
  731. private JsValue FindLast(JsValue thisObject, JsValue[] arguments)
  732. {
  733. var target = TypeConverter.ToObject(_realm, thisObject);
  734. target.FindWithCallback(arguments, out _, out var value, visitUnassigned: true, fromEnd: true);
  735. return value;
  736. }
  737. private JsValue FindLastIndex(JsValue thisObject, JsValue[] arguments)
  738. {
  739. var target = TypeConverter.ToObject(_realm, thisObject);
  740. if (target.FindWithCallback(arguments, out var index, out _, visitUnassigned: true, fromEnd: true))
  741. {
  742. return index;
  743. }
  744. return -1;
  745. }
  746. /// <summary>
  747. /// https://tc39.es/proposal-relative-indexing-method/#sec-array-prototype-additions
  748. /// </summary>
  749. private JsValue At(JsValue thisObject, JsValue[] arguments)
  750. {
  751. var target = TypeConverter.ToObject(_realm, thisObject);
  752. var len = target.GetLength();
  753. var relativeIndex = TypeConverter.ToInteger(arguments.At(0));
  754. ulong actualIndex;
  755. if (relativeIndex < 0)
  756. {
  757. actualIndex = (ulong) (len + relativeIndex);
  758. }
  759. else
  760. {
  761. actualIndex = (ulong) relativeIndex;
  762. }
  763. if (actualIndex < 0 || actualIndex >= len)
  764. {
  765. return Undefined;
  766. }
  767. return target.Get(actualIndex);
  768. }
  769. /// <summary>
  770. /// https://tc39.es/ecma262/#sec-array.prototype.splice
  771. /// </summary>
  772. private JsValue Splice(JsValue thisObject, JsValue[] arguments)
  773. {
  774. var start = arguments.At(0);
  775. var deleteCount = arguments.At(1);
  776. var obj = TypeConverter.ToObject(_realm, thisObject);
  777. var o = ArrayOperations.For(_realm, obj, forWrite: true);
  778. var len = o.GetLongLength();
  779. var relativeStart = TypeConverter.ToInteger(start);
  780. ulong actualStart;
  781. if (relativeStart < 0)
  782. {
  783. actualStart = (ulong) System.Math.Max(len + relativeStart, 0);
  784. }
  785. else
  786. {
  787. actualStart = (ulong) System.Math.Min(relativeStart, len);
  788. }
  789. var items = System.Array.Empty<JsValue>();
  790. ulong insertCount;
  791. ulong actualDeleteCount;
  792. if (arguments.Length == 0)
  793. {
  794. insertCount = 0;
  795. actualDeleteCount = 0;
  796. }
  797. else if (arguments.Length == 1)
  798. {
  799. insertCount = 0;
  800. actualDeleteCount = len - actualStart;
  801. }
  802. else
  803. {
  804. insertCount = (ulong) (arguments.Length - 2);
  805. var dc = TypeConverter.ToInteger(deleteCount);
  806. actualDeleteCount = (ulong) System.Math.Min(System.Math.Max(dc, 0), len - actualStart);
  807. items = System.Array.Empty<JsValue>();
  808. if (arguments.Length > 2)
  809. {
  810. items = new JsValue[arguments.Length - 2];
  811. System.Array.Copy(arguments, 2, items, 0, items.Length);
  812. }
  813. }
  814. if (len + insertCount - actualDeleteCount > ArrayOperations.MaxArrayLikeLength)
  815. {
  816. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  817. }
  818. var instance = _realm.Intrinsics.Array.ArraySpeciesCreate(obj, actualDeleteCount);
  819. var a = ArrayOperations.For(instance, forWrite: true);
  820. for (uint k = 0; k < actualDeleteCount; k++)
  821. {
  822. var index = actualStart + k;
  823. if (o.HasProperty(index))
  824. {
  825. var fromValue = o.Get(index);
  826. a.CreateDataPropertyOrThrow(k, fromValue);
  827. }
  828. }
  829. a.SetLength((uint) actualDeleteCount);
  830. var length = len - actualDeleteCount + (uint) items.Length;
  831. o.EnsureCapacity(length);
  832. if ((ulong) items.Length < actualDeleteCount)
  833. {
  834. for (ulong k = actualStart; k < len - actualDeleteCount; k++)
  835. {
  836. var from = k + actualDeleteCount;
  837. var to = k + (ulong) items.Length;
  838. if (o.HasProperty(from))
  839. {
  840. var fromValue = o.Get(from);
  841. o.Set(to, fromValue, throwOnError: false);
  842. }
  843. else
  844. {
  845. o.DeletePropertyOrThrow(to);
  846. }
  847. }
  848. for (var k = len; k > len - actualDeleteCount + (ulong) items.Length; k--)
  849. {
  850. o.DeletePropertyOrThrow(k - 1);
  851. }
  852. }
  853. else if ((ulong) items.Length > actualDeleteCount)
  854. {
  855. for (var k = len - actualDeleteCount; k > actualStart; k--)
  856. {
  857. var from = k + actualDeleteCount - 1;
  858. var to = k + (ulong) items.Length - 1;
  859. if (o.HasProperty(from))
  860. {
  861. var fromValue = o.Get(from);
  862. o.Set(to, fromValue, throwOnError: true);
  863. }
  864. else
  865. {
  866. o.DeletePropertyOrThrow(to);
  867. }
  868. }
  869. }
  870. for (uint k = 0; k < items.Length; k++)
  871. {
  872. var e = items[k];
  873. o.Set(k + actualStart, e, throwOnError: true);
  874. }
  875. o.SetLength(length);
  876. return a.Target;
  877. }
  878. /// <summary>
  879. /// /https://tc39.es/ecma262/#sec-array.prototype.unshift
  880. /// </summary>
  881. private JsValue Unshift(JsValue thisObject, JsValue[] arguments)
  882. {
  883. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  884. var len = o.GetLongLength();
  885. var argCount = (uint) arguments.Length;
  886. if (len + argCount > ArrayOperations.MaxArrayLikeLength)
  887. {
  888. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  889. }
  890. o.EnsureCapacity(len + argCount);
  891. var minIndex = o.GetSmallestIndex(len);
  892. for (var k = len; k > minIndex; k--)
  893. {
  894. var from = k - 1;
  895. var to = k + argCount - 1;
  896. if (o.TryGetValue(from, out var fromValue))
  897. {
  898. o.Set(to, fromValue, updateLength: false);
  899. }
  900. else
  901. {
  902. o.DeletePropertyOrThrow(to);
  903. }
  904. }
  905. for (uint j = 0; j < argCount; j++)
  906. {
  907. o.Set(j, arguments[j], updateLength: false);
  908. }
  909. o.SetLength(len + argCount);
  910. return len + argCount;
  911. }
  912. /// <summary>
  913. /// https://tc39.es/ecma262/#sec-array.prototype.sort
  914. /// </summary>
  915. private JsValue Sort(JsValue thisObject, JsValue[] arguments)
  916. {
  917. var obj = ArrayOperations.For(_realm, thisObject, forWrite: true);
  918. var compareFn = GetCompareFunction(arguments.At(0));
  919. var len = obj.GetLength();
  920. if (len <= 1)
  921. {
  922. return obj.Target;
  923. }
  924. var items = new List<JsValue>((int) System.Math.Min(10_000, obj.GetLength()));
  925. for (ulong k = 0; k < len; ++k)
  926. {
  927. if (obj.TryGetValue(k, out var kValue))
  928. {
  929. items.Add(kValue);
  930. }
  931. }
  932. var itemCount = items.Count;
  933. // don't eat inner exceptions
  934. try
  935. {
  936. var array = items.OrderBy(x => x, ArrayComparer.WithFunction(_engine, compareFn!)).ToArray();
  937. uint j;
  938. for (j = 0; j < itemCount; ++j)
  939. {
  940. var updateLength = j == itemCount - 1;
  941. obj.Set(j, array[j], updateLength: updateLength, throwOnError: true);
  942. }
  943. for (; j < len; ++j)
  944. {
  945. obj.DeletePropertyOrThrow(j);
  946. }
  947. }
  948. catch (InvalidOperationException e)
  949. {
  950. throw e.InnerException ?? e;
  951. }
  952. return obj.Target;
  953. }
  954. /// <summary>
  955. /// https://tc39.es/ecma262/#sec-array.prototype.slice
  956. /// </summary>
  957. private JsValue Slice(JsValue thisObject, JsValue[] arguments)
  958. {
  959. var start = arguments.At(0);
  960. var end = arguments.At(1);
  961. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  962. var len = o.GetLongLength();
  963. var relativeStart = TypeConverter.ToInteger(start);
  964. ulong k;
  965. if (relativeStart < 0)
  966. {
  967. k = (ulong) System.Math.Max(len + relativeStart, 0);
  968. }
  969. else
  970. {
  971. k = (ulong) System.Math.Min(TypeConverter.ToInteger(start), len);
  972. }
  973. ulong final;
  974. if (end.IsUndefined())
  975. {
  976. final = (ulong) TypeConverter.ToNumber(len);
  977. }
  978. else
  979. {
  980. double relativeEnd = TypeConverter.ToInteger(end);
  981. if (relativeEnd < 0)
  982. {
  983. final = (ulong) System.Math.Max(len + relativeEnd, 0);
  984. }
  985. else
  986. {
  987. final = (ulong) System.Math.Min(relativeEnd, len);
  988. }
  989. }
  990. if (k < final && final - k > ArrayOperations.MaxArrayLength)
  991. {
  992. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");
  993. }
  994. var length = (uint) System.Math.Max(0, (long) final - (long) k);
  995. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), length);
  996. if (thisObject is JsArray ai && a is JsArray a2)
  997. {
  998. a2.CopyValues(ai, (uint) k, 0, length);
  999. }
  1000. else
  1001. {
  1002. // slower path
  1003. var operations = ArrayOperations.For(a, forWrite: true);
  1004. for (uint n = 0; k < final; k++, n++)
  1005. {
  1006. if (o.TryGetValue(k, out var kValue))
  1007. {
  1008. operations.CreateDataPropertyOrThrow(n, kValue);
  1009. }
  1010. }
  1011. }
  1012. return a;
  1013. }
  1014. private JsValue Shift(JsValue thisObject, JsValue[] arg2)
  1015. {
  1016. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1017. var len = o.GetLength();
  1018. if (len == 0)
  1019. {
  1020. o.SetLength(0);
  1021. return Undefined;
  1022. }
  1023. var first = o.Get(0);
  1024. for (uint k = 1; k < len; k++)
  1025. {
  1026. var to = k - 1;
  1027. if (o.TryGetValue(k, out var fromVal))
  1028. {
  1029. o.Set(to, fromVal, throwOnError: false);
  1030. }
  1031. else
  1032. {
  1033. o.DeletePropertyOrThrow(to);
  1034. }
  1035. }
  1036. o.DeletePropertyOrThrow(len - 1);
  1037. o.SetLength(len - 1);
  1038. return first;
  1039. }
  1040. /// <summary>
  1041. /// https://tc39.es/ecma262/#sec-array.prototype.reverse
  1042. /// </summary>
  1043. private JsValue Reverse(JsValue thisObject, JsValue[] arguments)
  1044. {
  1045. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1046. var len = o.GetLongLength();
  1047. var middle = (ulong) System.Math.Floor(len / 2.0);
  1048. uint lower = 0;
  1049. while (lower != middle)
  1050. {
  1051. var upper = len - lower - 1;
  1052. var lowerExists = o.HasProperty(lower);
  1053. var lowerValue = lowerExists ? o.Get(lower) : null;
  1054. var upperExists = o.HasProperty(upper);
  1055. var upperValue = upperExists ? o.Get(upper) : null;
  1056. if (lowerExists && upperExists)
  1057. {
  1058. o.Set(lower, upperValue!, throwOnError: true);
  1059. o.Set(upper, lowerValue!, throwOnError: true);
  1060. }
  1061. if (!lowerExists && upperExists)
  1062. {
  1063. o.Set(lower, upperValue!, throwOnError: true);
  1064. o.DeletePropertyOrThrow(upper);
  1065. }
  1066. if (lowerExists && !upperExists)
  1067. {
  1068. o.DeletePropertyOrThrow(lower);
  1069. o.Set(upper, lowerValue!, throwOnError: true);
  1070. }
  1071. lower++;
  1072. }
  1073. return o.Target;
  1074. }
  1075. /// <summary>
  1076. /// https://tc39.es/ecma262/#sec-array.prototype.join
  1077. /// </summary>
  1078. private JsValue Join(JsValue thisObject, JsValue[] arguments)
  1079. {
  1080. var separator = arguments.At(0);
  1081. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1082. var len = o.GetLength();
  1083. var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator);
  1084. // as per the spec, this has to be called after ToString(separator)
  1085. if (len == 0)
  1086. {
  1087. return JsString.Empty;
  1088. }
  1089. static string StringFromJsValue(JsValue value)
  1090. {
  1091. return value.IsNullOrUndefined()
  1092. ? ""
  1093. : TypeConverter.ToString(value);
  1094. }
  1095. var s = StringFromJsValue(o.Get(0));
  1096. if (len == 1)
  1097. {
  1098. return s;
  1099. }
  1100. using var sb = new ValueStringBuilder(stackalloc char[256]);
  1101. sb.Append(s);
  1102. for (uint k = 1; k < len; k++)
  1103. {
  1104. if (sep != "")
  1105. {
  1106. sb.Append(sep);
  1107. }
  1108. sb.Append(StringFromJsValue(o.Get(k)));
  1109. }
  1110. return sb.ToString();
  1111. }
  1112. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1113. {
  1114. var array = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1115. var len = array.GetLength();
  1116. const string Separator = ",";
  1117. if (len == 0)
  1118. {
  1119. return JsString.Empty;
  1120. }
  1121. JsValue r;
  1122. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1123. {
  1124. r = JsString.Empty;
  1125. }
  1126. else
  1127. {
  1128. r = Invoke(firstElement, "toLocaleString", System.Array.Empty<JsValue>());
  1129. }
  1130. for (uint k = 1; k < len; k++)
  1131. {
  1132. var s = r + Separator;
  1133. if (!array.TryGetValue(k, out var nextElement) || nextElement.IsNull())
  1134. {
  1135. r = JsString.Empty;
  1136. }
  1137. else
  1138. {
  1139. r = Invoke(nextElement, "toLocaleString", System.Array.Empty<JsValue>());
  1140. }
  1141. r = s + r;
  1142. }
  1143. return r;
  1144. }
  1145. /// <summary>
  1146. /// https://tc39.es/ecma262/#sec-array.prototype.concat
  1147. /// </summary>
  1148. private JsValue Concat(JsValue thisObject, JsValue[] arguments)
  1149. {
  1150. var o = TypeConverter.ToObject(_realm, thisObject);
  1151. var items = new List<JsValue>(arguments.Length + 1) { o };
  1152. items.AddRange(arguments);
  1153. uint n = 0;
  1154. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), 0);
  1155. var aOperations = ArrayOperations.For(a, forWrite: true);
  1156. for (var i = 0; i < items.Count; i++)
  1157. {
  1158. var e = items[i];
  1159. if (e is ObjectInstance { IsConcatSpreadable: true } oi)
  1160. {
  1161. if (e is JsArray eArray && a is JsArray a2)
  1162. {
  1163. a2.CopyValues(eArray, 0, n, eArray.GetLength());
  1164. n += eArray.GetLength();
  1165. }
  1166. else
  1167. {
  1168. var operations = ArrayOperations.For(oi, forWrite: false);
  1169. var len = operations.GetLongLength();
  1170. if (n + len > ArrayOperations.MaxArrayLikeLength)
  1171. {
  1172. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1173. }
  1174. for (uint k = 0; k < len; k++)
  1175. {
  1176. operations.TryGetValue(k, out var subElement);
  1177. aOperations.CreateDataPropertyOrThrow(n, subElement);
  1178. n++;
  1179. }
  1180. }
  1181. }
  1182. else
  1183. {
  1184. aOperations.CreateDataPropertyOrThrow(n, e);
  1185. n++;
  1186. }
  1187. }
  1188. // this is not in the specs, but is necessary in case the last element of the last
  1189. // array doesn't exist, and thus the length would not be incremented
  1190. a.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(n, PropertyFlag.OnlyWritable));
  1191. return a;
  1192. }
  1193. internal JsValue ToString(JsValue thisObject, JsValue[] arguments)
  1194. {
  1195. var array = TypeConverter.ToObject(_realm, thisObject);
  1196. Func<JsValue, JsValue[], JsValue> func;
  1197. if (array.Get("join") is ICallable joinFunc)
  1198. {
  1199. func = joinFunc.Call;
  1200. }
  1201. else
  1202. {
  1203. func = _realm.Intrinsics.Object.PrototypeObject.ToObjectString;
  1204. }
  1205. return func(array, Arguments.Empty);
  1206. }
  1207. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1208. {
  1209. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1210. var len = o.GetLongLength();
  1211. if (len == 0)
  1212. {
  1213. return new JsArray(_engine);
  1214. }
  1215. var a = CreateBackingArray(len);
  1216. ulong k = 0;
  1217. while (k < len)
  1218. {
  1219. var from = len - k - 1;
  1220. a[k++] = o.Get(from);
  1221. }
  1222. return new JsArray(_engine, a);
  1223. }
  1224. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1225. {
  1226. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1227. var compareFn = GetCompareFunction(arguments.At(0));
  1228. var len = o.GetLongLength();
  1229. ValidateArrayLength(len);
  1230. if (len == 0)
  1231. {
  1232. return new JsArray(_engine);
  1233. }
  1234. var array = o.GetAll(skipHoles: true);
  1235. array = SortArray(array, compareFn);
  1236. return new JsArray(_engine, array);
  1237. }
  1238. private JsValue ToSpliced(JsValue thisObject, JsValue[] arguments)
  1239. {
  1240. var start = arguments.At(0);
  1241. var deleteCount = arguments.At(1);
  1242. var o = ArrayOperations.For(_realm, TypeConverter.ToObject(_realm, thisObject), forWrite: false);
  1243. var len = o.GetLongLength();
  1244. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1245. ulong actualStart;
  1246. if (double.IsNegativeInfinity(relativeStart))
  1247. {
  1248. actualStart = 0;
  1249. }
  1250. else if (relativeStart < 0)
  1251. {
  1252. actualStart = (ulong) System.Math.Max(len + relativeStart, 0);
  1253. }
  1254. else
  1255. {
  1256. actualStart = (ulong) System.Math.Min(relativeStart, len);
  1257. }
  1258. var items = System.Array.Empty<JsValue>();
  1259. ulong insertCount;
  1260. ulong actualDeleteCount;
  1261. if (arguments.Length == 0)
  1262. {
  1263. insertCount = 0;
  1264. actualDeleteCount = 0;
  1265. }
  1266. else if (arguments.Length == 1)
  1267. {
  1268. insertCount = 0;
  1269. actualDeleteCount = len - actualStart;
  1270. }
  1271. else
  1272. {
  1273. insertCount = (ulong) (arguments.Length - 2);
  1274. var dc = TypeConverter.ToIntegerOrInfinity(deleteCount);
  1275. actualDeleteCount = (ulong) System.Math.Min(System.Math.Max(dc, 0), len - actualStart);
  1276. items = System.Array.Empty<JsValue>();
  1277. if (arguments.Length > 2)
  1278. {
  1279. items = new JsValue[arguments.Length - 2];
  1280. System.Array.Copy(arguments, 2, items, 0, items.Length);
  1281. }
  1282. }
  1283. var newLen = len + insertCount - actualDeleteCount;
  1284. if (newLen > ArrayOperations.MaxArrayLikeLength)
  1285. {
  1286. ExceptionHelper.ThrowTypeError(_realm, "Invalid input length");
  1287. }
  1288. ValidateArrayLength(newLen);
  1289. var r = actualStart + actualDeleteCount;
  1290. var a = new JsArray(_engine, (uint) newLen);
  1291. uint i = 0;
  1292. while (i < actualStart)
  1293. {
  1294. a.SetIndexValue(i, o.Get(i), updateLength: false);
  1295. i++;
  1296. }
  1297. a.SetLength((uint) actualStart);
  1298. foreach (var item in items)
  1299. {
  1300. a.SetIndexValue(i++, item, updateLength: false);
  1301. }
  1302. while (i < newLen)
  1303. {
  1304. var fromValue = o.Get(r);
  1305. a.SetIndexValue(i, fromValue, updateLength: false);
  1306. i++;
  1307. r++;
  1308. }
  1309. a.SetLength(i);
  1310. return a;
  1311. }
  1312. private JsValue[] SortArray(IEnumerable<JsValue> array, ICallable? compareFn)
  1313. {
  1314. var comparer = ArrayComparer.WithFunction(_engine, compareFn);
  1315. try
  1316. {
  1317. return array.OrderBy(x => x, comparer).ToArray();
  1318. }
  1319. catch (InvalidOperationException e)
  1320. {
  1321. throw e.InnerException ?? e;
  1322. }
  1323. }
  1324. private ICallable? GetCompareFunction(JsValue compareArg)
  1325. {
  1326. ICallable? compareFn = null;
  1327. if (!compareArg.IsUndefined())
  1328. {
  1329. if (compareArg is not ICallable callable)
  1330. {
  1331. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1332. return null;
  1333. }
  1334. compareFn = callable;
  1335. }
  1336. return compareFn;
  1337. }
  1338. /// <summary>
  1339. /// https://tc39.es/ecma262/#sec-array.prototype.reduceright
  1340. /// </summary>
  1341. private JsValue ReduceRight(JsValue thisObject, JsValue[] arguments)
  1342. {
  1343. var callbackfn = arguments.At(0);
  1344. var initialValue = arguments.At(1);
  1345. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1346. var len = o.GetLongLength();
  1347. var callable = GetCallable(callbackfn);
  1348. if (len == 0 && arguments.Length < 2)
  1349. {
  1350. ExceptionHelper.ThrowTypeError(_realm);
  1351. }
  1352. long k = (long) (len - 1);
  1353. JsValue accumulator = Undefined;
  1354. if (arguments.Length > 1)
  1355. {
  1356. accumulator = initialValue;
  1357. }
  1358. else
  1359. {
  1360. var kPresent = false;
  1361. while (kPresent == false && k >= 0)
  1362. {
  1363. if ((kPresent = o.TryGetValue((ulong) k, out var temp)))
  1364. {
  1365. accumulator = temp;
  1366. }
  1367. k--;
  1368. }
  1369. if (kPresent == false)
  1370. {
  1371. ExceptionHelper.ThrowTypeError(_realm);
  1372. }
  1373. }
  1374. var jsValues = new JsValue[4];
  1375. jsValues[3] = o.Target;
  1376. for (; k >= 0; k--)
  1377. {
  1378. if (o.TryGetValue((ulong) k, out var kvalue))
  1379. {
  1380. jsValues[0] = accumulator;
  1381. jsValues[1] = kvalue;
  1382. jsValues[2] = k;
  1383. accumulator = callable.Call(Undefined, jsValues);
  1384. }
  1385. }
  1386. return accumulator;
  1387. }
  1388. /// <summary>
  1389. /// https://tc39.es/ecma262/#sec-array.prototype.push
  1390. /// </summary>
  1391. public JsValue Push(JsValue thisObject, JsValue[] arguments)
  1392. {
  1393. if (thisObject is JsArray { CanUseFastAccess: true } arrayInstance)
  1394. {
  1395. return arrayInstance.Push(arguments);
  1396. }
  1397. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1398. var n = o.GetLongLength();
  1399. if (n + (ulong) arguments.Length > ArrayOperations.MaxArrayLikeLength)
  1400. {
  1401. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1402. }
  1403. foreach (var a in arguments)
  1404. {
  1405. o.Set(n, a, true);
  1406. n++;
  1407. }
  1408. o.SetLength(n);
  1409. return n;
  1410. }
  1411. public JsValue Pop(JsValue thisObject, JsValue[] arguments)
  1412. {
  1413. if (thisObject is JsArray { CanUseFastAccess: true } array)
  1414. {
  1415. return array.Pop();
  1416. }
  1417. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1418. ulong len = o.GetLongLength();
  1419. if (len == 0)
  1420. {
  1421. o.SetLength(0);
  1422. return Undefined;
  1423. }
  1424. len -= 1;
  1425. JsValue element = o.Get(len);
  1426. o.DeletePropertyOrThrow(len);
  1427. o.SetLength(len);
  1428. return element;
  1429. }
  1430. private JsValue[] CreateBackingArray(ulong length)
  1431. {
  1432. ValidateArrayLength(length);
  1433. return new JsValue[length];
  1434. }
  1435. private void ValidateArrayLength(ulong length)
  1436. {
  1437. if (length > ArrayOperations.MaxArrayLength)
  1438. {
  1439. ExceptionHelper.ThrowRangeError(_engine.Realm, "Invalid array length " + length);
  1440. }
  1441. }
  1442. internal sealed class ArrayComparer : IComparer<JsValue>
  1443. {
  1444. /// <summary>
  1445. /// Default instance without any compare function.
  1446. /// </summary>
  1447. public static readonly ArrayComparer Default = new(null, null);
  1448. public static ArrayComparer WithFunction(Engine engine, ICallable? compare)
  1449. {
  1450. return compare is null ? Default : new ArrayComparer(engine, compare);
  1451. }
  1452. private readonly Engine? _engine;
  1453. private readonly ICallable? _compare;
  1454. private readonly JsValue[] _comparableArray = new JsValue[2];
  1455. private ArrayComparer(Engine? engine, ICallable? compare)
  1456. {
  1457. _engine = engine;
  1458. _compare = compare;
  1459. }
  1460. public int Compare(JsValue? x, JsValue? y)
  1461. {
  1462. var xIsNull = ReferenceEquals(x, null);
  1463. var yIsNull = ReferenceEquals(y, null);
  1464. if (xIsNull)
  1465. {
  1466. if (yIsNull)
  1467. {
  1468. return 0;
  1469. }
  1470. return 1;
  1471. }
  1472. else
  1473. {
  1474. if (yIsNull)
  1475. {
  1476. return -1;
  1477. }
  1478. }
  1479. var xUndefined = x!.IsUndefined();
  1480. var yUndefined = y!.IsUndefined();
  1481. if (xUndefined && yUndefined)
  1482. {
  1483. return 0;
  1484. }
  1485. if (xUndefined)
  1486. {
  1487. return 1;
  1488. }
  1489. if (yUndefined)
  1490. {
  1491. return -1;
  1492. }
  1493. if (_compare != null)
  1494. {
  1495. _engine!.RunBeforeExecuteStatementChecks(null);
  1496. _comparableArray[0] = x!;
  1497. _comparableArray[1] = y!;
  1498. var s = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1499. if (s < 0)
  1500. {
  1501. return -1;
  1502. }
  1503. if (s > 0)
  1504. {
  1505. return 1;
  1506. }
  1507. return 0;
  1508. }
  1509. var xString = TypeConverter.ToString(x!);
  1510. var yString = TypeConverter.ToString(y!);
  1511. return string.CompareOrdinal(xString, yString);
  1512. }
  1513. }
  1514. }
  1515. }