ArrayPrototype.cs 61 KB

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