ArrayPrototype.cs 60 KB

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