ArrayPrototype.cs 63 KB

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