2
0

ArrayPrototype.cs 58 KB

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