ArrayPrototype.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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. }