ArrayPrototype.cs 63 KB

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