ArrayPrototype.cs 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  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 LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "at", prototype.At, 1, PropertyFlag.Configurable), PropertyFlags),
  41. ["concat"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "concat", prototype.Concat, 1, PropertyFlag.Configurable), PropertyFlags),
  42. ["copyWithin"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "copyWithin", prototype.CopyWithin, 2, PropertyFlag.Configurable), PropertyFlags),
  43. ["entries"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "entries", prototype.Entries, 0, PropertyFlag.Configurable), PropertyFlags),
  44. ["every"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "every", prototype.Every, 1, PropertyFlag.Configurable), PropertyFlags),
  45. ["fill"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "fill", prototype.Fill, 1, PropertyFlag.Configurable), PropertyFlags),
  46. ["filter"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "filter", prototype.Filter, 1, PropertyFlag.Configurable), PropertyFlags),
  47. ["find"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "find", prototype.Find, 1, PropertyFlag.Configurable), PropertyFlags),
  48. ["findIndex"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findIndex", prototype.FindIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  49. ["findLast"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLast", prototype.FindLast, 1, PropertyFlag.Configurable), PropertyFlags),
  50. ["findLastIndex"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLastIndex", prototype.FindLastIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  51. ["flat"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "flat", prototype.Flat, 0, PropertyFlag.Configurable), PropertyFlags),
  52. ["flatMap"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "flatMap", prototype.FlatMap, 1, PropertyFlag.Configurable), PropertyFlags),
  53. ["forEach"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "forEach", prototype.ForEach, 1, PropertyFlag.Configurable), PropertyFlags),
  54. ["includes"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "includes", prototype.Includes, 1, PropertyFlag.Configurable), PropertyFlags),
  55. ["indexOf"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "indexOf", prototype.IndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  56. ["join"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "join", prototype.Join, 1, PropertyFlag.Configurable), PropertyFlags),
  57. ["keys"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "keys", prototype.Keys, 0, PropertyFlag.Configurable), PropertyFlags),
  58. ["lastIndexOf"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "lastIndexOf", prototype.LastIndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  59. ["map"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "map", prototype.Map, 1, PropertyFlag.Configurable), PropertyFlags),
  60. ["pop"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "pop", prototype.Pop, 0, PropertyFlag.Configurable), PropertyFlags),
  61. ["push"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "push", prototype.Push, 1, PropertyFlag.Configurable), PropertyFlags),
  62. ["reduce"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduce", prototype.Reduce, 1, PropertyFlag.Configurable), PropertyFlags),
  63. ["reduceRight"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduceRight", prototype.ReduceRight, 1, PropertyFlag.Configurable), PropertyFlags),
  64. ["reverse"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reverse", prototype.Reverse, 0, PropertyFlag.Configurable), PropertyFlags),
  65. ["shift"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "shift",prototype. Shift, 0, PropertyFlag.Configurable), PropertyFlags),
  66. ["slice"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "slice", prototype.Slice, 2, PropertyFlag.Configurable), PropertyFlags),
  67. ["some"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "some", prototype.Some, 1, PropertyFlag.Configurable), PropertyFlags),
  68. ["sort"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "sort", prototype.Sort, 1, PropertyFlag.Configurable), PropertyFlags),
  69. ["splice"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "splice", prototype.Splice, 2, PropertyFlag.Configurable), PropertyFlags),
  70. ["toLocaleString"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLocaleString", prototype.ToLocaleString, 0, PropertyFlag.Configurable), PropertyFlags),
  71. ["toReversed"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toReversed", prototype.ToReversed, 0, PropertyFlag.Configurable), PropertyFlags),
  72. ["toSorted"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toSorted", prototype.ToSorted, 1, PropertyFlag.Configurable), PropertyFlags),
  73. ["toSpliced"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toSpliced", prototype.ToSpliced, 2, PropertyFlag.Configurable), PropertyFlags),
  74. ["toString"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toString", prototype.ToString, 0, PropertyFlag.Configurable), PropertyFlags),
  75. ["unshift"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "unshift", prototype.Unshift, 1, PropertyFlag.Configurable), PropertyFlags),
  76. ["values"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "values", prototype.Values, 0, PropertyFlag.Configurable), PropertyFlags),
  77. ["with"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "with", prototype.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>(_engine, static engine =>
  85. {
  86. var unscopables = new JsObject(engine)
  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 (!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. // only prepare for larger if we cannot rely on default growth algorithm
  891. if (len + argCount > 2 * len)
  892. {
  893. o.EnsureCapacity(len + argCount);
  894. }
  895. var minIndex = o.GetSmallestIndex(len);
  896. for (var k = len; k > minIndex; k--)
  897. {
  898. var from = k - 1;
  899. var to = k + argCount - 1;
  900. if (o.TryGetValue(from, out var fromValue))
  901. {
  902. o.Set(to, fromValue, updateLength: false);
  903. }
  904. else
  905. {
  906. o.DeletePropertyOrThrow(to);
  907. }
  908. }
  909. for (uint j = 0; j < argCount; j++)
  910. {
  911. o.Set(j, arguments[j], updateLength: false);
  912. }
  913. o.SetLength(len + argCount);
  914. return len + argCount;
  915. }
  916. /// <summary>
  917. /// https://tc39.es/ecma262/#sec-array.prototype.sort
  918. /// </summary>
  919. private JsValue Sort(JsValue thisObject, JsValue[] arguments)
  920. {
  921. var obj = ArrayOperations.For(_realm, thisObject, forWrite: true);
  922. var compareFn = GetCompareFunction(arguments.At(0));
  923. var len = obj.GetLength();
  924. if (len <= 1)
  925. {
  926. return obj.Target;
  927. }
  928. var items = new List<JsValue>((int) System.Math.Min(10_000, obj.GetLength()));
  929. for (ulong k = 0; k < len; ++k)
  930. {
  931. if (obj.TryGetValue(k, out var kValue))
  932. {
  933. items.Add(kValue);
  934. }
  935. }
  936. var itemCount = items.Count;
  937. // don't eat inner exceptions
  938. try
  939. {
  940. var comparer = ArrayComparer.WithFunction(_engine, compareFn);
  941. IEnumerable<JsValue> ordered;
  942. #if !NETCOREAPP
  943. if (comparer is not null)
  944. {
  945. // sort won't be stable on .NET Framework, but at least it cant go into infinite loop when comparer is badly implemented
  946. items.Sort(comparer);
  947. ordered = items;
  948. }
  949. else
  950. {
  951. ordered = items.OrderBy(x => x, comparer);
  952. }
  953. #else
  954. #if NET8_0_OR_GREATER
  955. ordered = items.Order(comparer);
  956. #else
  957. ordered = items.OrderBy(x => x, comparer);
  958. #endif
  959. #endif
  960. uint j = 0;
  961. foreach (var item in ordered)
  962. {
  963. obj.Set(j, item, updateLength: false, throwOnError: true);
  964. j++;
  965. }
  966. for (; j < len; ++j)
  967. {
  968. obj.DeletePropertyOrThrow(j);
  969. }
  970. }
  971. catch (InvalidOperationException e)
  972. {
  973. throw e.InnerException ?? e;
  974. }
  975. return obj.Target;
  976. }
  977. /// <summary>
  978. /// https://tc39.es/ecma262/#sec-array.prototype.slice
  979. /// </summary>
  980. private JsValue Slice(JsValue thisObject, JsValue[] arguments)
  981. {
  982. var start = arguments.At(0);
  983. var end = arguments.At(1);
  984. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  985. var len = o.GetLongLength();
  986. var relativeStart = TypeConverter.ToInteger(start);
  987. ulong k;
  988. if (relativeStart < 0)
  989. {
  990. k = (ulong) System.Math.Max(len + relativeStart, 0);
  991. }
  992. else
  993. {
  994. k = (ulong) System.Math.Min(TypeConverter.ToInteger(start), len);
  995. }
  996. ulong final;
  997. if (end.IsUndefined())
  998. {
  999. final = (ulong) TypeConverter.ToNumber(len);
  1000. }
  1001. else
  1002. {
  1003. double relativeEnd = TypeConverter.ToInteger(end);
  1004. if (relativeEnd < 0)
  1005. {
  1006. final = (ulong) System.Math.Max(len + relativeEnd, 0);
  1007. }
  1008. else
  1009. {
  1010. final = (ulong) System.Math.Min(relativeEnd, len);
  1011. }
  1012. }
  1013. if (k < final && final - k > ArrayOperations.MaxArrayLength)
  1014. {
  1015. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");
  1016. }
  1017. var length = (uint) System.Math.Max(0, (long) final - (long) k);
  1018. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), length);
  1019. if (thisObject is JsArray ai && a is JsArray a2)
  1020. {
  1021. a2.CopyValues(ai, (uint) k, 0, length);
  1022. }
  1023. else
  1024. {
  1025. // slower path
  1026. var operations = ArrayOperations.For(a, forWrite: true);
  1027. for (uint n = 0; k < final; k++, n++)
  1028. {
  1029. if (o.TryGetValue(k, out var kValue))
  1030. {
  1031. operations.CreateDataPropertyOrThrow(n, kValue);
  1032. }
  1033. }
  1034. }
  1035. return a;
  1036. }
  1037. private JsValue Shift(JsValue thisObject, JsValue[] arg2)
  1038. {
  1039. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1040. var len = o.GetLength();
  1041. if (len == 0)
  1042. {
  1043. o.SetLength(0);
  1044. return Undefined;
  1045. }
  1046. var first = o.Get(0);
  1047. for (uint k = 1; k < len; k++)
  1048. {
  1049. var to = k - 1;
  1050. if (o.TryGetValue(k, out var fromVal))
  1051. {
  1052. o.Set(to, fromVal, throwOnError: false);
  1053. }
  1054. else
  1055. {
  1056. o.DeletePropertyOrThrow(to);
  1057. }
  1058. }
  1059. o.DeletePropertyOrThrow(len - 1);
  1060. o.SetLength(len - 1);
  1061. return first;
  1062. }
  1063. /// <summary>
  1064. /// https://tc39.es/ecma262/#sec-array.prototype.reverse
  1065. /// </summary>
  1066. private JsValue Reverse(JsValue thisObject, JsValue[] arguments)
  1067. {
  1068. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1069. var len = o.GetLongLength();
  1070. var middle = (ulong) System.Math.Floor(len / 2.0);
  1071. uint lower = 0;
  1072. while (lower != middle)
  1073. {
  1074. var upper = len - lower - 1;
  1075. var lowerExists = o.HasProperty(lower);
  1076. var lowerValue = lowerExists ? o.Get(lower) : null;
  1077. var upperExists = o.HasProperty(upper);
  1078. var upperValue = upperExists ? o.Get(upper) : null;
  1079. if (lowerExists && upperExists)
  1080. {
  1081. o.Set(lower, upperValue!, throwOnError: true);
  1082. o.Set(upper, lowerValue!, throwOnError: true);
  1083. }
  1084. if (!lowerExists && upperExists)
  1085. {
  1086. o.Set(lower, upperValue!, throwOnError: true);
  1087. o.DeletePropertyOrThrow(upper);
  1088. }
  1089. if (lowerExists && !upperExists)
  1090. {
  1091. o.DeletePropertyOrThrow(lower);
  1092. o.Set(upper, lowerValue!, throwOnError: true);
  1093. }
  1094. lower++;
  1095. }
  1096. return o.Target;
  1097. }
  1098. /// <summary>
  1099. /// https://tc39.es/ecma262/#sec-array.prototype.join
  1100. /// </summary>
  1101. private JsValue Join(JsValue thisObject, JsValue[] arguments)
  1102. {
  1103. var separator = arguments.At(0);
  1104. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1105. var len = o.GetLength();
  1106. var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator);
  1107. // as per the spec, this has to be called after ToString(separator)
  1108. if (len == 0)
  1109. {
  1110. return JsString.Empty;
  1111. }
  1112. static string StringFromJsValue(JsValue value)
  1113. {
  1114. return value.IsNullOrUndefined()
  1115. ? ""
  1116. : TypeConverter.ToString(value);
  1117. }
  1118. var s = StringFromJsValue(o.Get(0));
  1119. if (len == 1)
  1120. {
  1121. return s;
  1122. }
  1123. using var sb = new ValueStringBuilder();
  1124. sb.Append(s);
  1125. for (uint k = 1; k < len; k++)
  1126. {
  1127. if (sep != "")
  1128. {
  1129. sb.Append(sep);
  1130. }
  1131. sb.Append(StringFromJsValue(o.Get(k)));
  1132. }
  1133. return sb.ToString();
  1134. }
  1135. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1136. {
  1137. var array = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1138. var len = array.GetLength();
  1139. const string Separator = ",";
  1140. if (len == 0)
  1141. {
  1142. return JsString.Empty;
  1143. }
  1144. JsValue r;
  1145. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1146. {
  1147. r = JsString.Empty;
  1148. }
  1149. else
  1150. {
  1151. r = Invoke(firstElement, "toLocaleString", System.Array.Empty<JsValue>());
  1152. }
  1153. for (uint k = 1; k < len; k++)
  1154. {
  1155. var s = r + Separator;
  1156. if (!array.TryGetValue(k, out var nextElement) || nextElement.IsNull())
  1157. {
  1158. r = JsString.Empty;
  1159. }
  1160. else
  1161. {
  1162. r = Invoke(nextElement, "toLocaleString", System.Array.Empty<JsValue>());
  1163. }
  1164. r = s + r;
  1165. }
  1166. return r;
  1167. }
  1168. /// <summary>
  1169. /// https://tc39.es/ecma262/#sec-array.prototype.concat
  1170. /// </summary>
  1171. private JsValue Concat(JsValue thisObject, JsValue[] arguments)
  1172. {
  1173. var o = TypeConverter.ToObject(_realm, thisObject);
  1174. var items = new List<JsValue>(arguments.Length + 1) { o };
  1175. items.AddRange(arguments);
  1176. uint n = 0;
  1177. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), 0);
  1178. var aOperations = ArrayOperations.For(a, forWrite: true);
  1179. for (var i = 0; i < items.Count; i++)
  1180. {
  1181. var e = items[i];
  1182. if (e is ObjectInstance { IsConcatSpreadable: true } oi)
  1183. {
  1184. if (e is JsArray eArray && a is JsArray a2)
  1185. {
  1186. a2.CopyValues(eArray, 0, n, eArray.GetLength());
  1187. n += eArray.GetLength();
  1188. }
  1189. else
  1190. {
  1191. var operations = ArrayOperations.For(oi, forWrite: false);
  1192. var len = operations.GetLongLength();
  1193. if (n + len > ArrayOperations.MaxArrayLikeLength)
  1194. {
  1195. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1196. }
  1197. for (uint k = 0; k < len; k++)
  1198. {
  1199. operations.TryGetValue(k, out var subElement);
  1200. aOperations.CreateDataPropertyOrThrow(n, subElement);
  1201. n++;
  1202. }
  1203. }
  1204. }
  1205. else
  1206. {
  1207. aOperations.CreateDataPropertyOrThrow(n, e);
  1208. n++;
  1209. }
  1210. }
  1211. // this is not in the specs, but is necessary in case the last element of the last
  1212. // array doesn't exist, and thus the length would not be incremented
  1213. a.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(n, PropertyFlag.OnlyWritable));
  1214. return a;
  1215. }
  1216. internal JsValue ToString(JsValue thisObject, JsValue[] arguments)
  1217. {
  1218. var array = TypeConverter.ToObject(_realm, thisObject);
  1219. Func<JsValue, JsValue[], JsValue> func;
  1220. if (array.Get("join") is ICallable joinFunc)
  1221. {
  1222. func = joinFunc.Call;
  1223. }
  1224. else
  1225. {
  1226. func = _realm.Intrinsics.Object.PrototypeObject.ToObjectString;
  1227. }
  1228. return func(array, Arguments.Empty);
  1229. }
  1230. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1231. {
  1232. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1233. var len = o.GetLongLength();
  1234. if (len == 0)
  1235. {
  1236. return new JsArray(_engine);
  1237. }
  1238. var a = CreateBackingArray(len);
  1239. ulong k = 0;
  1240. while (k < len)
  1241. {
  1242. var from = len - k - 1;
  1243. a[k++] = o.Get(from);
  1244. }
  1245. return new JsArray(_engine, a);
  1246. }
  1247. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1248. {
  1249. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1250. var compareFn = GetCompareFunction(arguments.At(0));
  1251. var len = o.GetLongLength();
  1252. ValidateArrayLength(len);
  1253. if (len == 0)
  1254. {
  1255. return new JsArray(_engine);
  1256. }
  1257. var array = o.GetAll(skipHoles: true);
  1258. array = SortArray(array, compareFn);
  1259. return new JsArray(_engine, array);
  1260. }
  1261. private JsValue ToSpliced(JsValue thisObject, JsValue[] arguments)
  1262. {
  1263. var start = arguments.At(0);
  1264. var deleteCount = arguments.At(1);
  1265. var o = ArrayOperations.For(_realm, TypeConverter.ToObject(_realm, thisObject), forWrite: false);
  1266. var len = o.GetLongLength();
  1267. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1268. ulong actualStart;
  1269. if (double.IsNegativeInfinity(relativeStart))
  1270. {
  1271. actualStart = 0;
  1272. }
  1273. else if (relativeStart < 0)
  1274. {
  1275. actualStart = (ulong) System.Math.Max(len + relativeStart, 0);
  1276. }
  1277. else
  1278. {
  1279. actualStart = (ulong) System.Math.Min(relativeStart, len);
  1280. }
  1281. var items = System.Array.Empty<JsValue>();
  1282. ulong insertCount;
  1283. ulong actualDeleteCount;
  1284. if (arguments.Length == 0)
  1285. {
  1286. insertCount = 0;
  1287. actualDeleteCount = 0;
  1288. }
  1289. else if (arguments.Length == 1)
  1290. {
  1291. insertCount = 0;
  1292. actualDeleteCount = len - actualStart;
  1293. }
  1294. else
  1295. {
  1296. insertCount = (ulong) (arguments.Length - 2);
  1297. var dc = TypeConverter.ToIntegerOrInfinity(deleteCount);
  1298. actualDeleteCount = (ulong) System.Math.Min(System.Math.Max(dc, 0), len - actualStart);
  1299. items = System.Array.Empty<JsValue>();
  1300. if (arguments.Length > 2)
  1301. {
  1302. items = new JsValue[arguments.Length - 2];
  1303. System.Array.Copy(arguments, 2, items, 0, items.Length);
  1304. }
  1305. }
  1306. var newLen = len + insertCount - actualDeleteCount;
  1307. if (newLen > ArrayOperations.MaxArrayLikeLength)
  1308. {
  1309. ExceptionHelper.ThrowTypeError(_realm, "Invalid input length");
  1310. }
  1311. ValidateArrayLength(newLen);
  1312. var r = actualStart + actualDeleteCount;
  1313. var a = new JsArray(_engine, (uint) newLen);
  1314. uint i = 0;
  1315. while (i < actualStart)
  1316. {
  1317. a.SetIndexValue(i, o.Get(i), updateLength: false);
  1318. i++;
  1319. }
  1320. a.SetLength((uint) actualStart);
  1321. foreach (var item in items)
  1322. {
  1323. a.SetIndexValue(i++, item, updateLength: false);
  1324. }
  1325. while (i < newLen)
  1326. {
  1327. var fromValue = o.Get(r);
  1328. a.SetIndexValue(i, fromValue, updateLength: false);
  1329. i++;
  1330. r++;
  1331. }
  1332. a.SetLength(i);
  1333. return a;
  1334. }
  1335. private JsValue[] SortArray(IEnumerable<JsValue> array, ICallable? compareFn)
  1336. {
  1337. var comparer = ArrayComparer.WithFunction(_engine, compareFn);
  1338. try
  1339. {
  1340. return array.OrderBy(x => x, comparer).ToArray();
  1341. }
  1342. catch (InvalidOperationException e)
  1343. {
  1344. throw e.InnerException ?? e;
  1345. }
  1346. }
  1347. private ICallable? GetCompareFunction(JsValue compareArg)
  1348. {
  1349. ICallable? compareFn = null;
  1350. if (!compareArg.IsUndefined())
  1351. {
  1352. if (compareArg is not ICallable callable)
  1353. {
  1354. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1355. return null;
  1356. }
  1357. compareFn = callable;
  1358. }
  1359. return compareFn;
  1360. }
  1361. /// <summary>
  1362. /// https://tc39.es/ecma262/#sec-array.prototype.reduceright
  1363. /// </summary>
  1364. private JsValue ReduceRight(JsValue thisObject, JsValue[] arguments)
  1365. {
  1366. var callbackfn = arguments.At(0);
  1367. var initialValue = arguments.At(1);
  1368. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1369. var len = o.GetLongLength();
  1370. var callable = GetCallable(callbackfn);
  1371. if (len == 0 && arguments.Length < 2)
  1372. {
  1373. ExceptionHelper.ThrowTypeError(_realm);
  1374. }
  1375. long k = (long) (len - 1);
  1376. JsValue accumulator = Undefined;
  1377. if (arguments.Length > 1)
  1378. {
  1379. accumulator = initialValue;
  1380. }
  1381. else
  1382. {
  1383. var kPresent = false;
  1384. while (kPresent == false && k >= 0)
  1385. {
  1386. if ((kPresent = o.TryGetValue((ulong) k, out var temp)))
  1387. {
  1388. accumulator = temp;
  1389. }
  1390. k--;
  1391. }
  1392. if (kPresent == false)
  1393. {
  1394. ExceptionHelper.ThrowTypeError(_realm);
  1395. }
  1396. }
  1397. var jsValues = new JsValue[4];
  1398. jsValues[3] = o.Target;
  1399. for (; k >= 0; k--)
  1400. {
  1401. if (o.TryGetValue((ulong) k, out var kvalue))
  1402. {
  1403. jsValues[0] = accumulator;
  1404. jsValues[1] = kvalue;
  1405. jsValues[2] = k;
  1406. accumulator = callable.Call(Undefined, jsValues);
  1407. }
  1408. }
  1409. return accumulator;
  1410. }
  1411. /// <summary>
  1412. /// https://tc39.es/ecma262/#sec-array.prototype.push
  1413. /// </summary>
  1414. public JsValue Push(JsValue thisObject, JsValue[] arguments)
  1415. {
  1416. if (thisObject is JsArray { CanUseFastAccess: true } arrayInstance)
  1417. {
  1418. return arrayInstance.Push(arguments);
  1419. }
  1420. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1421. var n = o.GetLongLength();
  1422. if (n + (ulong) arguments.Length > ArrayOperations.MaxArrayLikeLength)
  1423. {
  1424. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1425. }
  1426. foreach (var a in arguments)
  1427. {
  1428. o.Set(n, a, true);
  1429. n++;
  1430. }
  1431. o.SetLength(n);
  1432. return n;
  1433. }
  1434. public JsValue Pop(JsValue thisObject, JsValue[] arguments)
  1435. {
  1436. if (thisObject is JsArray { CanUseFastAccess: true } array)
  1437. {
  1438. return array.Pop();
  1439. }
  1440. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1441. ulong len = o.GetLongLength();
  1442. if (len == 0)
  1443. {
  1444. o.SetLength(0);
  1445. return Undefined;
  1446. }
  1447. len -= 1;
  1448. JsValue element = o.Get(len);
  1449. o.DeletePropertyOrThrow(len);
  1450. o.SetLength(len);
  1451. return element;
  1452. }
  1453. private JsValue[] CreateBackingArray(ulong length)
  1454. {
  1455. ValidateArrayLength(length);
  1456. return new JsValue[length];
  1457. }
  1458. private void ValidateArrayLength(ulong length)
  1459. {
  1460. if (length > ArrayOperations.MaxArrayLength)
  1461. {
  1462. ExceptionHelper.ThrowRangeError(_engine.Realm, "Invalid array length " + length);
  1463. }
  1464. }
  1465. internal sealed class ArrayComparer : IComparer<JsValue>
  1466. {
  1467. /// <summary>
  1468. /// Default instance without any compare function.
  1469. /// </summary>
  1470. public static readonly ArrayComparer Default = new(null, null);
  1471. public static ArrayComparer WithFunction(Engine engine, ICallable? compare)
  1472. {
  1473. return compare is null ? Default : new ArrayComparer(engine, compare);
  1474. }
  1475. private readonly Engine? _engine;
  1476. private readonly ICallable? _compare;
  1477. private readonly JsValue[] _comparableArray = new JsValue[2];
  1478. private ArrayComparer(Engine? engine, ICallable? compare)
  1479. {
  1480. _engine = engine;
  1481. _compare = compare;
  1482. }
  1483. public int Compare(JsValue? x, JsValue? y)
  1484. {
  1485. var xIsNull = x is null;
  1486. var yIsNull = y is null;
  1487. if (xIsNull)
  1488. {
  1489. if (yIsNull)
  1490. {
  1491. return 0;
  1492. }
  1493. return 1;
  1494. }
  1495. else
  1496. {
  1497. if (yIsNull)
  1498. {
  1499. return -1;
  1500. }
  1501. }
  1502. var xUndefined = x!.IsUndefined();
  1503. var yUndefined = y!.IsUndefined();
  1504. if (xUndefined && yUndefined)
  1505. {
  1506. return 0;
  1507. }
  1508. if (xUndefined)
  1509. {
  1510. return 1;
  1511. }
  1512. if (yUndefined)
  1513. {
  1514. return -1;
  1515. }
  1516. if (_compare != null)
  1517. {
  1518. _engine!.RunBeforeExecuteStatementChecks(null);
  1519. _comparableArray[0] = x!;
  1520. _comparableArray[1] = y!;
  1521. var s = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1522. if (s < 0)
  1523. {
  1524. return -1;
  1525. }
  1526. if (s > 0)
  1527. {
  1528. return 1;
  1529. }
  1530. return 0;
  1531. }
  1532. var xString = TypeConverter.ToString(x!);
  1533. var yString = TypeConverter.ToString(y!);
  1534. return string.CompareOrdinal(xString, yString);
  1535. }
  1536. }
  1537. }
  1538. }