ArrayPrototype.cs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. #pragma warning disable CA1859 // Use concrete types when possible for improved performance -- most of prototype methods return JsValue
  2. using System.Linq;
  3. using System.Text;
  4. using Jint.Collections;
  5. using Jint.Native.Iterator;
  6. using Jint.Native.Number;
  7. using Jint.Native.Object;
  8. using Jint.Native.Symbol;
  9. using Jint.Runtime;
  10. using Jint.Runtime.Descriptors;
  11. using Jint.Runtime.Descriptors.Specialized;
  12. using Jint.Runtime.Interop;
  13. namespace Jint.Native.Array;
  14. /// <summary>
  15. /// https://tc39.es/ecma262/#sec-properties-of-the-array-prototype-object
  16. /// </summary>
  17. public sealed class ArrayPrototype : ArrayInstance
  18. {
  19. private readonly Realm _realm;
  20. private readonly ArrayConstructor _constructor;
  21. internal ClrFunction? _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 LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "at", prototype.At, 1, PropertyFlag.Configurable), PropertyFlags),
  40. ["concat"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "concat", prototype.Concat, 1, PropertyFlag.Configurable), PropertyFlags),
  41. ["copyWithin"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "copyWithin", prototype.CopyWithin, 2, PropertyFlag.Configurable), PropertyFlags),
  42. ["entries"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "entries", prototype.Entries, 0, PropertyFlag.Configurable), PropertyFlags),
  43. ["every"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "every", prototype.Every, 1, PropertyFlag.Configurable), PropertyFlags),
  44. ["fill"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "fill", prototype.Fill, 1, PropertyFlag.Configurable), PropertyFlags),
  45. ["filter"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "filter", prototype.Filter, 1, PropertyFlag.Configurable), PropertyFlags),
  46. ["find"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "find", prototype.Find, 1, PropertyFlag.Configurable), PropertyFlags),
  47. ["findIndex"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findIndex", prototype.FindIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  48. ["findLast"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLast", prototype.FindLast, 1, PropertyFlag.Configurable), PropertyFlags),
  49. ["findLastIndex"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLastIndex", prototype.FindLastIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  50. ["flat"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "flat", prototype.Flat, 0, PropertyFlag.Configurable), PropertyFlags),
  51. ["flatMap"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "flatMap", prototype.FlatMap, 1, PropertyFlag.Configurable), PropertyFlags),
  52. ["forEach"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "forEach", prototype.ForEach, 1, PropertyFlag.Configurable), PropertyFlags),
  53. ["includes"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "includes", prototype.Includes, 1, PropertyFlag.Configurable), PropertyFlags),
  54. ["indexOf"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "indexOf", prototype.IndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  55. ["join"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "join", prototype.Join, 1, PropertyFlag.Configurable), PropertyFlags),
  56. ["keys"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "keys", prototype.Keys, 0, PropertyFlag.Configurable), PropertyFlags),
  57. ["lastIndexOf"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "lastIndexOf", prototype.LastIndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  58. ["map"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "map", prototype.Map, 1, PropertyFlag.Configurable), PropertyFlags),
  59. ["pop"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "pop", prototype.Pop, 0, PropertyFlag.Configurable), PropertyFlags),
  60. ["push"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "push", prototype.Push, 1, PropertyFlag.Configurable), PropertyFlags),
  61. ["reduce"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduce", prototype.Reduce, 1, PropertyFlag.Configurable), PropertyFlags),
  62. ["reduceRight"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduceRight", prototype.ReduceRight, 1, PropertyFlag.Configurable), PropertyFlags),
  63. ["reverse"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reverse", prototype.Reverse, 0, PropertyFlag.Configurable), PropertyFlags),
  64. ["shift"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "shift",prototype. Shift, 0, PropertyFlag.Configurable), PropertyFlags),
  65. ["slice"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "slice", prototype.Slice, 2, PropertyFlag.Configurable), PropertyFlags),
  66. ["some"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "some", prototype.Some, 1, PropertyFlag.Configurable), PropertyFlags),
  67. ["sort"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "sort", prototype.Sort, 1, PropertyFlag.Configurable), PropertyFlags),
  68. ["splice"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "splice", prototype.Splice, 2, PropertyFlag.Configurable), PropertyFlags),
  69. ["toLocaleString"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLocaleString", prototype.ToLocaleString, 0, PropertyFlag.Configurable), PropertyFlags),
  70. ["toReversed"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toReversed", prototype.ToReversed, 0, PropertyFlag.Configurable), PropertyFlags),
  71. ["toSorted"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toSorted", prototype.ToSorted, 1, PropertyFlag.Configurable), PropertyFlags),
  72. ["toSpliced"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toSpliced", prototype.ToSpliced, 2, PropertyFlag.Configurable), PropertyFlags),
  73. ["toString"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toString", prototype.ToString, 0, PropertyFlag.Configurable), PropertyFlags),
  74. ["unshift"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "unshift", prototype.Unshift, 1, PropertyFlag.Configurable), PropertyFlags),
  75. ["values"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "values", prototype.Values, 0, PropertyFlag.Configurable), PropertyFlags),
  76. ["with"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "with", prototype.With, 2, PropertyFlag.Configurable), PropertyFlags),
  77. };
  78. SetProperties(properties);
  79. _originalIteratorFunction = new ClrFunction(_engine, "iterator", Values, 1);
  80. var symbols = new SymbolDictionary(2)
  81. {
  82. [GlobalSymbolRegistry.Iterator] = new PropertyDescriptor(_originalIteratorFunction, PropertyFlags),
  83. [GlobalSymbolRegistry.Unscopables] = new LazyPropertyDescriptor<Engine>(_engine, static engine =>
  84. {
  85. var unscopables = new JsObject(engine)
  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), forWrite: false);
  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, forWrite: true);
  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, forWrite: true);
  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, forWrite: false);
  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, forWrite: true);
  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, forWrite: false);
  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, forWrite: true);
  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, forWrite: false);
  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), forWrite: true);
  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 operations = ArrayOperations.For(_realm, thisObject, forWrite: false);
  452. var sourceLen = operations.GetLength();
  453. double depthNum = 1;
  454. var depth = arguments.At(0);
  455. if (!depth.IsUndefined())
  456. {
  457. depthNum = TypeConverter.ToIntegerOrInfinity(depth);
  458. }
  459. if (depthNum < 0)
  460. {
  461. depthNum = 0;
  462. }
  463. var A = _realm.Intrinsics.Array.ArraySpeciesCreate(operations.Target, 0);
  464. FlattenIntoArray(A, operations, sourceLen, 0, depthNum);
  465. return A;
  466. }
  467. /// <summary>
  468. /// https://tc39.es/ecma262/#sec-array.prototype.flatmap
  469. /// </summary>
  470. private JsValue FlatMap(JsValue thisObject, JsValue[] arguments)
  471. {
  472. var O = ArrayOperations.For(_realm, thisObject, forWrite: false);
  473. var mapperFunction = arguments.At(0);
  474. var thisArg = arguments.At(1);
  475. var sourceLen = O.GetLength();
  476. if (!mapperFunction.IsCallable)
  477. {
  478. ExceptionHelper.ThrowTypeError(_realm, "flatMap mapper function is not callable");
  479. }
  480. var A = _realm.Intrinsics.Array.ArraySpeciesCreate(O.Target, 0);
  481. FlattenIntoArray(A, O, sourceLen, 0, 1, (ICallable) mapperFunction, thisArg);
  482. return A;
  483. }
  484. /// <summary>
  485. /// https://tc39.es/ecma262/#sec-flattenintoarray
  486. /// </summary>
  487. private ulong FlattenIntoArray(
  488. ObjectInstance target,
  489. ArrayOperations source,
  490. uint sourceLen,
  491. ulong start,
  492. double depth,
  493. ICallable? mapperFunction = null,
  494. JsValue? thisArg = null)
  495. {
  496. var targetIndex = start;
  497. ulong sourceIndex = 0;
  498. var callArguments = System.Array.Empty<JsValue>();
  499. if (mapperFunction is not null)
  500. {
  501. callArguments = _engine._jsValueArrayPool.RentArray(3);
  502. callArguments[2] = source.Target;
  503. }
  504. while (sourceIndex < sourceLen)
  505. {
  506. var exists = source.HasProperty(sourceIndex);
  507. if (exists)
  508. {
  509. var element = source.Get(sourceIndex);
  510. if (mapperFunction is not null)
  511. {
  512. callArguments[0] = element;
  513. callArguments[1] = JsNumber.Create(sourceIndex);
  514. element = mapperFunction.Call(thisArg ?? Undefined, callArguments);
  515. }
  516. var shouldFlatten = false;
  517. if (depth > 0)
  518. {
  519. shouldFlatten = element.IsArray();
  520. }
  521. if (shouldFlatten)
  522. {
  523. var newDepth = double.IsPositiveInfinity(depth)
  524. ? depth
  525. : depth - 1;
  526. var objectInstance = (ObjectInstance) element;
  527. var elementLen = objectInstance.GetLength();
  528. targetIndex = FlattenIntoArray(target, ArrayOperations.For(objectInstance, forWrite: false), elementLen, targetIndex, newDepth);
  529. }
  530. else
  531. {
  532. if (targetIndex >= NumberConstructor.MaxSafeInteger)
  533. {
  534. ExceptionHelper.ThrowTypeError(_realm);
  535. }
  536. target.CreateDataPropertyOrThrow(targetIndex, element);
  537. targetIndex += 1;
  538. }
  539. }
  540. sourceIndex++;
  541. }
  542. if (mapperFunction is not null)
  543. {
  544. _engine._jsValueArrayPool.ReturnArray(callArguments);
  545. }
  546. return targetIndex;
  547. }
  548. private JsValue ForEach(JsValue thisObject, JsValue[] arguments)
  549. {
  550. var callbackfn = arguments.At(0);
  551. var thisArg = arguments.At(1);
  552. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  553. var len = o.GetLength();
  554. var callable = GetCallable(callbackfn);
  555. var args = _engine._jsValueArrayPool.RentArray(3);
  556. args[2] = o.Target;
  557. for (uint k = 0; k < len; k++)
  558. {
  559. if (o.TryGetValue(k, out var kvalue))
  560. {
  561. args[0] = kvalue;
  562. args[1] = k;
  563. callable.Call(thisArg, args);
  564. }
  565. }
  566. _engine._jsValueArrayPool.ReturnArray(args);
  567. return Undefined;
  568. }
  569. /// <summary>
  570. /// https://tc39.es/ecma262/#sec-array.prototype.includes
  571. /// </summary>
  572. private JsValue Includes(JsValue thisObject, JsValue[] arguments)
  573. {
  574. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  575. var len = (long) o.GetLongLength();
  576. if (len == 0)
  577. {
  578. return JsBoolean.False;
  579. }
  580. var searchElement = arguments.At(0);
  581. var fromIndex = arguments.At(1);
  582. long k = 0;
  583. var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
  584. if (double.IsPositiveInfinity(n))
  585. {
  586. return JsBoolean.False;
  587. }
  588. else if (double.IsNegativeInfinity(n))
  589. {
  590. n = 0;
  591. }
  592. else if (n >= 0)
  593. {
  594. k = (long) n;
  595. }
  596. else
  597. {
  598. k = len + (long) n;
  599. if (k < 0)
  600. {
  601. k = 0;
  602. }
  603. }
  604. while (k < len)
  605. {
  606. var value = o.Get((ulong) k);
  607. if (SameValueZeroComparer.Equals(value, searchElement))
  608. {
  609. return true;
  610. }
  611. k++;
  612. }
  613. return false;
  614. }
  615. private JsValue Some(JsValue thisObject, JsValue[] arguments)
  616. {
  617. var target = TypeConverter.ToObject(_realm, thisObject);
  618. return target.FindWithCallback(arguments, out _, out _, false);
  619. }
  620. /// <summary>
  621. /// https://tc39.es/ecma262/#sec-array.prototype.every
  622. /// </summary>
  623. private JsValue Every(JsValue thisObject, JsValue[] arguments)
  624. {
  625. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  626. ulong len = o.GetLongLength();
  627. if (len == 0)
  628. {
  629. return JsBoolean.True;
  630. }
  631. var callbackfn = arguments.At(0);
  632. var thisArg = arguments.At(1);
  633. var callable = GetCallable(callbackfn);
  634. var args = _engine._jsValueArrayPool.RentArray(3);
  635. args[2] = o.Target;
  636. for (uint k = 0; k < len; k++)
  637. {
  638. if (o.TryGetValue(k, out var kvalue))
  639. {
  640. args[0] = kvalue;
  641. args[1] = k;
  642. var testResult = callable.Call(thisArg, args);
  643. if (!TypeConverter.ToBoolean(testResult))
  644. {
  645. return JsBoolean.False;
  646. }
  647. }
  648. }
  649. _engine._jsValueArrayPool.ReturnArray(args);
  650. return JsBoolean.True;
  651. }
  652. /// <summary>
  653. /// https://tc39.es/ecma262/#sec-array.prototype.indexof
  654. /// </summary>
  655. private JsValue IndexOf(JsValue thisObject, JsValue[] arguments)
  656. {
  657. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  658. var len = o.GetLongLength();
  659. if (len == 0)
  660. {
  661. return -1;
  662. }
  663. var startIndex = arguments.Length > 1
  664. ? TypeConverter.ToIntegerOrInfinity(arguments.At(1))
  665. : 0;
  666. if (startIndex > ArrayOperations.MaxArrayLikeLength)
  667. {
  668. return JsNumber.IntegerNegativeOne;
  669. }
  670. ulong k;
  671. if (startIndex < 0)
  672. {
  673. var abs = System.Math.Abs(startIndex);
  674. ulong temp = len - (uint) abs;
  675. if (abs > len || temp < 0)
  676. {
  677. temp = 0;
  678. }
  679. k = temp;
  680. }
  681. else
  682. {
  683. k = (ulong) startIndex;
  684. }
  685. if (k >= len)
  686. {
  687. return -1;
  688. }
  689. ulong smallestIndex = o.GetSmallestIndex(len);
  690. if (smallestIndex > k)
  691. {
  692. k = smallestIndex;
  693. }
  694. var searchElement = arguments.At(0);
  695. for (; k < len; k++)
  696. {
  697. var kPresent = o.HasProperty(k);
  698. if (kPresent)
  699. {
  700. var elementK = o.Get(k);
  701. if (elementK == searchElement)
  702. {
  703. return k;
  704. }
  705. }
  706. }
  707. return -1;
  708. }
  709. /// <summary>
  710. /// https://tc39.es/ecma262/#sec-array.prototype.find
  711. /// </summary>
  712. private JsValue Find(JsValue thisObject, JsValue[] arguments)
  713. {
  714. var target = TypeConverter.ToObject(_realm, thisObject);
  715. target.FindWithCallback(arguments, out _, out var value, visitUnassigned: true);
  716. return value;
  717. }
  718. /// <summary>
  719. /// https://tc39.es/ecma262/#sec-array.prototype.findindex
  720. /// </summary>
  721. private JsValue FindIndex(JsValue thisObject, JsValue[] arguments)
  722. {
  723. var target = TypeConverter.ToObject(_realm, thisObject);
  724. if (target.FindWithCallback(arguments, out var index, out _, visitUnassigned: true))
  725. {
  726. return index;
  727. }
  728. return -1;
  729. }
  730. private JsValue FindLast(JsValue thisObject, JsValue[] arguments)
  731. {
  732. var target = TypeConverter.ToObject(_realm, thisObject);
  733. target.FindWithCallback(arguments, out _, out var value, visitUnassigned: true, fromEnd: true);
  734. return value;
  735. }
  736. private JsValue FindLastIndex(JsValue thisObject, JsValue[] arguments)
  737. {
  738. var target = TypeConverter.ToObject(_realm, thisObject);
  739. if (target.FindWithCallback(arguments, out var index, out _, visitUnassigned: true, fromEnd: true))
  740. {
  741. return index;
  742. }
  743. return -1;
  744. }
  745. /// <summary>
  746. /// https://tc39.es/proposal-relative-indexing-method/#sec-array-prototype-additions
  747. /// </summary>
  748. private JsValue At(JsValue thisObject, JsValue[] arguments)
  749. {
  750. var target = TypeConverter.ToObject(_realm, thisObject);
  751. var len = target.GetLength();
  752. var relativeIndex = TypeConverter.ToInteger(arguments.At(0));
  753. ulong actualIndex;
  754. if (relativeIndex < 0)
  755. {
  756. actualIndex = (ulong) (len + relativeIndex);
  757. }
  758. else
  759. {
  760. actualIndex = (ulong) relativeIndex;
  761. }
  762. if (actualIndex < 0 || actualIndex >= len)
  763. {
  764. return Undefined;
  765. }
  766. return target.Get(actualIndex);
  767. }
  768. /// <summary>
  769. /// https://tc39.es/ecma262/#sec-array.prototype.splice
  770. /// </summary>
  771. private JsValue Splice(JsValue thisObject, JsValue[] arguments)
  772. {
  773. var start = arguments.At(0);
  774. var deleteCount = arguments.At(1);
  775. var obj = TypeConverter.ToObject(_realm, thisObject);
  776. var o = ArrayOperations.For(_realm, obj, forWrite: true);
  777. var len = o.GetLongLength();
  778. var relativeStart = TypeConverter.ToInteger(start);
  779. ulong actualStart;
  780. if (relativeStart < 0)
  781. {
  782. actualStart = (ulong) System.Math.Max(len + relativeStart, 0);
  783. }
  784. else
  785. {
  786. actualStart = (ulong) System.Math.Min(relativeStart, len);
  787. }
  788. var items = System.Array.Empty<JsValue>();
  789. ulong insertCount;
  790. ulong actualDeleteCount;
  791. if (arguments.Length == 0)
  792. {
  793. insertCount = 0;
  794. actualDeleteCount = 0;
  795. }
  796. else if (arguments.Length == 1)
  797. {
  798. insertCount = 0;
  799. actualDeleteCount = len - actualStart;
  800. }
  801. else
  802. {
  803. insertCount = (ulong) (arguments.Length - 2);
  804. var dc = TypeConverter.ToInteger(deleteCount);
  805. actualDeleteCount = (ulong) System.Math.Min(System.Math.Max(dc, 0), len - actualStart);
  806. items = System.Array.Empty<JsValue>();
  807. if (arguments.Length > 2)
  808. {
  809. items = new JsValue[arguments.Length - 2];
  810. System.Array.Copy(arguments, 2, items, 0, items.Length);
  811. }
  812. }
  813. if (len + insertCount - actualDeleteCount > ArrayOperations.MaxArrayLikeLength)
  814. {
  815. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  816. }
  817. var instance = _realm.Intrinsics.Array.ArraySpeciesCreate(obj, actualDeleteCount);
  818. var a = ArrayOperations.For(instance, forWrite: true);
  819. for (uint k = 0; k < actualDeleteCount; k++)
  820. {
  821. var index = actualStart + k;
  822. if (o.HasProperty(index))
  823. {
  824. var fromValue = o.Get(index);
  825. a.CreateDataPropertyOrThrow(k, fromValue);
  826. }
  827. }
  828. a.SetLength((uint) actualDeleteCount);
  829. var length = len - actualDeleteCount + (uint) items.Length;
  830. o.EnsureCapacity(length);
  831. if ((ulong) items.Length < actualDeleteCount)
  832. {
  833. for (ulong k = actualStart; k < len - actualDeleteCount; k++)
  834. {
  835. var from = k + actualDeleteCount;
  836. var to = k + (ulong) items.Length;
  837. if (o.HasProperty(from))
  838. {
  839. var fromValue = o.Get(from);
  840. o.Set(to, fromValue, throwOnError: false);
  841. }
  842. else
  843. {
  844. o.DeletePropertyOrThrow(to);
  845. }
  846. }
  847. for (var k = len; k > len - actualDeleteCount + (ulong) items.Length; k--)
  848. {
  849. o.DeletePropertyOrThrow(k - 1);
  850. }
  851. }
  852. else if ((ulong) items.Length > actualDeleteCount)
  853. {
  854. for (var k = len - actualDeleteCount; k > actualStart; k--)
  855. {
  856. var from = k + actualDeleteCount - 1;
  857. var to = k + (ulong) items.Length - 1;
  858. if (o.HasProperty(from))
  859. {
  860. var fromValue = o.Get(from);
  861. o.Set(to, fromValue, throwOnError: true);
  862. }
  863. else
  864. {
  865. o.DeletePropertyOrThrow(to);
  866. }
  867. }
  868. }
  869. for (uint k = 0; k < items.Length; k++)
  870. {
  871. var e = items[k];
  872. o.Set(k + actualStart, e, throwOnError: true);
  873. }
  874. o.SetLength(length);
  875. return a.Target;
  876. }
  877. /// <summary>
  878. /// /https://tc39.es/ecma262/#sec-array.prototype.unshift
  879. /// </summary>
  880. private JsValue Unshift(JsValue thisObject, JsValue[] arguments)
  881. {
  882. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  883. var len = o.GetLongLength();
  884. var argCount = (uint) arguments.Length;
  885. if (len + argCount > ArrayOperations.MaxArrayLikeLength)
  886. {
  887. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  888. }
  889. // only prepare for larger if we cannot rely on default growth algorithm
  890. if (len + argCount > 2 * len)
  891. {
  892. o.EnsureCapacity(len + argCount);
  893. }
  894. var minIndex = o.GetSmallestIndex(len);
  895. for (var k = len; k > minIndex; k--)
  896. {
  897. var from = k - 1;
  898. var to = k + argCount - 1;
  899. if (o.TryGetValue(from, out var fromValue))
  900. {
  901. o.Set(to, fromValue, updateLength: false);
  902. }
  903. else
  904. {
  905. o.DeletePropertyOrThrow(to);
  906. }
  907. }
  908. for (uint j = 0; j < argCount; j++)
  909. {
  910. o.Set(j, arguments[j], updateLength: false);
  911. }
  912. o.SetLength(len + argCount);
  913. return len + argCount;
  914. }
  915. /// <summary>
  916. /// https://tc39.es/ecma262/#sec-array.prototype.sort
  917. /// </summary>
  918. private JsValue Sort(JsValue thisObject, JsValue[] arguments)
  919. {
  920. var obj = ArrayOperations.For(_realm, thisObject, forWrite: true);
  921. var compareFn = GetCompareFunction(arguments.At(0));
  922. var len = obj.GetLength();
  923. if (len <= 1)
  924. {
  925. return obj.Target;
  926. }
  927. var items = new List<JsValue>((int) System.Math.Min(10_000, obj.GetLength()));
  928. for (ulong k = 0; k < len; ++k)
  929. {
  930. if (obj.TryGetValue(k, out var kValue))
  931. {
  932. items.Add(kValue);
  933. }
  934. }
  935. var itemCount = items.Count;
  936. // don't eat inner exceptions
  937. try
  938. {
  939. var comparer = ArrayComparer.WithFunction(_engine, compareFn);
  940. IEnumerable<JsValue> ordered;
  941. #if !NETCOREAPP
  942. if (comparer is not null)
  943. {
  944. // sort won't be stable on .NET Framework, but at least it cant go into infinite loop when comparer is badly implemented
  945. items.Sort(comparer);
  946. ordered = items;
  947. }
  948. else
  949. {
  950. ordered = items.OrderBy(x => x, comparer);
  951. }
  952. #else
  953. #if NET8_0_OR_GREATER
  954. ordered = items.Order(comparer);
  955. #else
  956. ordered = items.OrderBy(x => x, comparer);
  957. #endif
  958. #endif
  959. uint j = 0;
  960. foreach (var item in ordered)
  961. {
  962. obj.Set(j, item, updateLength: false, throwOnError: true);
  963. j++;
  964. }
  965. for (; j < len; ++j)
  966. {
  967. obj.DeletePropertyOrThrow(j);
  968. }
  969. }
  970. catch (InvalidOperationException e)
  971. {
  972. throw e.InnerException ?? e;
  973. }
  974. return obj.Target;
  975. }
  976. /// <summary>
  977. /// https://tc39.es/ecma262/#sec-array.prototype.slice
  978. /// </summary>
  979. private JsValue Slice(JsValue thisObject, JsValue[] arguments)
  980. {
  981. var start = arguments.At(0);
  982. var end = arguments.At(1);
  983. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  984. var len = o.GetLongLength();
  985. var relativeStart = TypeConverter.ToInteger(start);
  986. ulong k;
  987. if (relativeStart < 0)
  988. {
  989. k = (ulong) System.Math.Max(len + relativeStart, 0);
  990. }
  991. else
  992. {
  993. k = (ulong) System.Math.Min(TypeConverter.ToInteger(start), len);
  994. }
  995. ulong final;
  996. if (end.IsUndefined())
  997. {
  998. final = (ulong) TypeConverter.ToNumber(len);
  999. }
  1000. else
  1001. {
  1002. double relativeEnd = TypeConverter.ToInteger(end);
  1003. if (relativeEnd < 0)
  1004. {
  1005. final = (ulong) System.Math.Max(len + relativeEnd, 0);
  1006. }
  1007. else
  1008. {
  1009. final = (ulong) System.Math.Min(relativeEnd, len);
  1010. }
  1011. }
  1012. if (k < final && final - k > ArrayOperations.MaxArrayLength)
  1013. {
  1014. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");
  1015. }
  1016. var length = (uint) System.Math.Max(0, (long) final - (long) k);
  1017. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), length);
  1018. if (thisObject is JsArray ai && a is JsArray a2)
  1019. {
  1020. a2.CopyValues(ai, (uint) k, 0, length);
  1021. }
  1022. else
  1023. {
  1024. // slower path
  1025. var operations = ArrayOperations.For(a, forWrite: true);
  1026. for (uint n = 0; k < final; k++, n++)
  1027. {
  1028. if (o.TryGetValue(k, out var kValue))
  1029. {
  1030. operations.CreateDataPropertyOrThrow(n, kValue);
  1031. }
  1032. }
  1033. }
  1034. return a;
  1035. }
  1036. private JsValue Shift(JsValue thisObject, JsValue[] arg2)
  1037. {
  1038. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1039. var len = o.GetLength();
  1040. if (len == 0)
  1041. {
  1042. o.SetLength(0);
  1043. return Undefined;
  1044. }
  1045. var first = o.Get(0);
  1046. for (uint k = 1; k < len; k++)
  1047. {
  1048. var to = k - 1;
  1049. if (o.TryGetValue(k, out var fromVal))
  1050. {
  1051. o.Set(to, fromVal, throwOnError: false);
  1052. }
  1053. else
  1054. {
  1055. o.DeletePropertyOrThrow(to);
  1056. }
  1057. }
  1058. o.DeletePropertyOrThrow(len - 1);
  1059. o.SetLength(len - 1);
  1060. return first;
  1061. }
  1062. /// <summary>
  1063. /// https://tc39.es/ecma262/#sec-array.prototype.reverse
  1064. /// </summary>
  1065. private JsValue Reverse(JsValue thisObject, JsValue[] arguments)
  1066. {
  1067. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1068. var len = o.GetLongLength();
  1069. var middle = (ulong) System.Math.Floor(len / 2.0);
  1070. uint lower = 0;
  1071. while (lower != middle)
  1072. {
  1073. var upper = len - lower - 1;
  1074. var lowerExists = o.HasProperty(lower);
  1075. var lowerValue = lowerExists ? o.Get(lower) : null;
  1076. var upperExists = o.HasProperty(upper);
  1077. var upperValue = upperExists ? o.Get(upper) : null;
  1078. if (lowerExists && upperExists)
  1079. {
  1080. o.Set(lower, upperValue!, throwOnError: true);
  1081. o.Set(upper, lowerValue!, throwOnError: true);
  1082. }
  1083. if (!lowerExists && upperExists)
  1084. {
  1085. o.Set(lower, upperValue!, throwOnError: true);
  1086. o.DeletePropertyOrThrow(upper);
  1087. }
  1088. if (lowerExists && !upperExists)
  1089. {
  1090. o.DeletePropertyOrThrow(lower);
  1091. o.Set(upper, lowerValue!, throwOnError: true);
  1092. }
  1093. lower++;
  1094. }
  1095. return o.Target;
  1096. }
  1097. /// <summary>
  1098. /// https://tc39.es/ecma262/#sec-array.prototype.join
  1099. /// </summary>
  1100. private JsValue Join(JsValue thisObject, JsValue[] arguments)
  1101. {
  1102. var separator = arguments.At(0);
  1103. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1104. var len = o.GetLength();
  1105. var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator);
  1106. // as per the spec, this has to be called after ToString(separator)
  1107. if (len == 0)
  1108. {
  1109. return JsString.Empty;
  1110. }
  1111. static string StringFromJsValue(JsValue value)
  1112. {
  1113. return value.IsNullOrUndefined()
  1114. ? ""
  1115. : TypeConverter.ToString(value);
  1116. }
  1117. var s = StringFromJsValue(o.Get(0));
  1118. if (len == 1)
  1119. {
  1120. return s;
  1121. }
  1122. using var sb = new ValueStringBuilder();
  1123. sb.Append(s);
  1124. for (uint k = 1; k < len; k++)
  1125. {
  1126. if (sep != "")
  1127. {
  1128. sb.Append(sep);
  1129. }
  1130. sb.Append(StringFromJsValue(o.Get(k)));
  1131. }
  1132. return sb.ToString();
  1133. }
  1134. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1135. {
  1136. var array = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1137. var len = array.GetLength();
  1138. const string Separator = ",";
  1139. if (len == 0)
  1140. {
  1141. return JsString.Empty;
  1142. }
  1143. JsValue r;
  1144. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1145. {
  1146. r = JsString.Empty;
  1147. }
  1148. else
  1149. {
  1150. r = Invoke(firstElement, "toLocaleString", System.Array.Empty<JsValue>());
  1151. }
  1152. for (uint k = 1; k < len; k++)
  1153. {
  1154. var s = r + Separator;
  1155. if (!array.TryGetValue(k, out var nextElement) || nextElement.IsNull())
  1156. {
  1157. r = JsString.Empty;
  1158. }
  1159. else
  1160. {
  1161. r = Invoke(nextElement, "toLocaleString", System.Array.Empty<JsValue>());
  1162. }
  1163. r = s + r;
  1164. }
  1165. return r;
  1166. }
  1167. /// <summary>
  1168. /// https://tc39.es/ecma262/#sec-array.prototype.concat
  1169. /// </summary>
  1170. private JsValue Concat(JsValue thisObject, JsValue[] arguments)
  1171. {
  1172. var o = TypeConverter.ToObject(_realm, thisObject);
  1173. var items = new List<JsValue>(arguments.Length + 1) { o };
  1174. items.AddRange(arguments);
  1175. uint n = 0;
  1176. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), 0);
  1177. var aOperations = ArrayOperations.For(a, forWrite: true);
  1178. for (var i = 0; i < items.Count; i++)
  1179. {
  1180. var e = items[i];
  1181. if (e is ObjectInstance { IsConcatSpreadable: true } oi)
  1182. {
  1183. if (e is JsArray eArray && a is JsArray a2)
  1184. {
  1185. a2.CopyValues(eArray, 0, n, eArray.GetLength());
  1186. n += eArray.GetLength();
  1187. }
  1188. else
  1189. {
  1190. var operations = ArrayOperations.For(oi, forWrite: false);
  1191. var len = operations.GetLongLength();
  1192. if (n + len > ArrayOperations.MaxArrayLikeLength)
  1193. {
  1194. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1195. }
  1196. for (uint k = 0; k < len; k++)
  1197. {
  1198. operations.TryGetValue(k, out var subElement);
  1199. aOperations.CreateDataPropertyOrThrow(n, subElement);
  1200. n++;
  1201. }
  1202. }
  1203. }
  1204. else
  1205. {
  1206. aOperations.CreateDataPropertyOrThrow(n, e);
  1207. n++;
  1208. }
  1209. }
  1210. // this is not in the specs, but is necessary in case the last element of the last
  1211. // array doesn't exist, and thus the length would not be incremented
  1212. a.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(n, PropertyFlag.OnlyWritable));
  1213. return a;
  1214. }
  1215. internal JsValue ToString(JsValue thisObject, JsValue[] arguments)
  1216. {
  1217. var array = TypeConverter.ToObject(_realm, thisObject);
  1218. Func<JsValue, JsValue[], JsValue> func;
  1219. if (array.Get("join") is ICallable joinFunc)
  1220. {
  1221. func = joinFunc.Call;
  1222. }
  1223. else
  1224. {
  1225. func = _realm.Intrinsics.Object.PrototypeObject.ToObjectString;
  1226. }
  1227. return func(array, Arguments.Empty);
  1228. }
  1229. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1230. {
  1231. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1232. var len = o.GetLongLength();
  1233. if (len == 0)
  1234. {
  1235. return new JsArray(_engine);
  1236. }
  1237. var a = CreateBackingArray(len);
  1238. ulong k = 0;
  1239. while (k < len)
  1240. {
  1241. var from = len - k - 1;
  1242. a[k++] = o.Get(from);
  1243. }
  1244. return new JsArray(_engine, a);
  1245. }
  1246. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1247. {
  1248. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1249. var compareFn = GetCompareFunction(arguments.At(0));
  1250. var len = o.GetLongLength();
  1251. ValidateArrayLength(len);
  1252. if (len == 0)
  1253. {
  1254. return new JsArray(_engine);
  1255. }
  1256. var array = o.GetAll(skipHoles: true);
  1257. array = SortArray(array, compareFn);
  1258. return new JsArray(_engine, array);
  1259. }
  1260. private JsValue ToSpliced(JsValue thisObject, JsValue[] arguments)
  1261. {
  1262. var start = arguments.At(0);
  1263. var deleteCount = arguments.At(1);
  1264. var o = ArrayOperations.For(_realm, TypeConverter.ToObject(_realm, thisObject), forWrite: false);
  1265. var len = o.GetLongLength();
  1266. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1267. ulong actualStart;
  1268. if (double.IsNegativeInfinity(relativeStart))
  1269. {
  1270. actualStart = 0;
  1271. }
  1272. else if (relativeStart < 0)
  1273. {
  1274. actualStart = (ulong) System.Math.Max(len + relativeStart, 0);
  1275. }
  1276. else
  1277. {
  1278. actualStart = (ulong) System.Math.Min(relativeStart, len);
  1279. }
  1280. var items = System.Array.Empty<JsValue>();
  1281. ulong insertCount;
  1282. ulong actualDeleteCount;
  1283. if (arguments.Length == 0)
  1284. {
  1285. insertCount = 0;
  1286. actualDeleteCount = 0;
  1287. }
  1288. else if (arguments.Length == 1)
  1289. {
  1290. insertCount = 0;
  1291. actualDeleteCount = len - actualStart;
  1292. }
  1293. else
  1294. {
  1295. insertCount = (ulong) (arguments.Length - 2);
  1296. var dc = TypeConverter.ToIntegerOrInfinity(deleteCount);
  1297. actualDeleteCount = (ulong) System.Math.Min(System.Math.Max(dc, 0), len - actualStart);
  1298. items = System.Array.Empty<JsValue>();
  1299. if (arguments.Length > 2)
  1300. {
  1301. items = new JsValue[arguments.Length - 2];
  1302. System.Array.Copy(arguments, 2, items, 0, items.Length);
  1303. }
  1304. }
  1305. var newLen = len + insertCount - actualDeleteCount;
  1306. if (newLen > ArrayOperations.MaxArrayLikeLength)
  1307. {
  1308. ExceptionHelper.ThrowTypeError(_realm, "Invalid input length");
  1309. }
  1310. ValidateArrayLength(newLen);
  1311. var r = actualStart + actualDeleteCount;
  1312. var a = new JsArray(_engine, (uint) newLen);
  1313. uint i = 0;
  1314. while (i < actualStart)
  1315. {
  1316. a.SetIndexValue(i, o.Get(i), updateLength: false);
  1317. i++;
  1318. }
  1319. a.SetLength((uint) actualStart);
  1320. foreach (var item in items)
  1321. {
  1322. a.SetIndexValue(i++, item, updateLength: false);
  1323. }
  1324. while (i < newLen)
  1325. {
  1326. var fromValue = o.Get(r);
  1327. a.SetIndexValue(i, fromValue, updateLength: false);
  1328. i++;
  1329. r++;
  1330. }
  1331. a.SetLength(i);
  1332. return a;
  1333. }
  1334. private JsValue[] SortArray(IEnumerable<JsValue> array, ICallable? compareFn)
  1335. {
  1336. var comparer = ArrayComparer.WithFunction(_engine, compareFn);
  1337. try
  1338. {
  1339. return array.OrderBy(x => x, comparer).ToArray();
  1340. }
  1341. catch (InvalidOperationException e)
  1342. {
  1343. throw e.InnerException ?? e;
  1344. }
  1345. }
  1346. private ICallable? GetCompareFunction(JsValue compareArg)
  1347. {
  1348. ICallable? compareFn = null;
  1349. if (!compareArg.IsUndefined())
  1350. {
  1351. if (compareArg is not ICallable callable)
  1352. {
  1353. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1354. return null;
  1355. }
  1356. compareFn = callable;
  1357. }
  1358. return compareFn;
  1359. }
  1360. /// <summary>
  1361. /// https://tc39.es/ecma262/#sec-array.prototype.reduceright
  1362. /// </summary>
  1363. private JsValue ReduceRight(JsValue thisObject, JsValue[] arguments)
  1364. {
  1365. var callbackfn = arguments.At(0);
  1366. var initialValue = arguments.At(1);
  1367. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1368. var len = o.GetLongLength();
  1369. var callable = GetCallable(callbackfn);
  1370. if (len == 0 && arguments.Length < 2)
  1371. {
  1372. ExceptionHelper.ThrowTypeError(_realm);
  1373. }
  1374. long k = (long) (len - 1);
  1375. JsValue accumulator = Undefined;
  1376. if (arguments.Length > 1)
  1377. {
  1378. accumulator = initialValue;
  1379. }
  1380. else
  1381. {
  1382. var kPresent = false;
  1383. while (kPresent == false && k >= 0)
  1384. {
  1385. if ((kPresent = o.TryGetValue((ulong) k, out var temp)))
  1386. {
  1387. accumulator = temp;
  1388. }
  1389. k--;
  1390. }
  1391. if (kPresent == false)
  1392. {
  1393. ExceptionHelper.ThrowTypeError(_realm);
  1394. }
  1395. }
  1396. var jsValues = new JsValue[4];
  1397. jsValues[3] = o.Target;
  1398. for (; k >= 0; k--)
  1399. {
  1400. if (o.TryGetValue((ulong) k, out var kvalue))
  1401. {
  1402. jsValues[0] = accumulator;
  1403. jsValues[1] = kvalue;
  1404. jsValues[2] = k;
  1405. accumulator = callable.Call(Undefined, jsValues);
  1406. }
  1407. }
  1408. return accumulator;
  1409. }
  1410. /// <summary>
  1411. /// https://tc39.es/ecma262/#sec-array.prototype.push
  1412. /// </summary>
  1413. public JsValue Push(JsValue thisObject, JsValue[] arguments)
  1414. {
  1415. if (thisObject is JsArray { CanUseFastAccess: true } arrayInstance)
  1416. {
  1417. return arrayInstance.Push(arguments);
  1418. }
  1419. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1420. var n = o.GetLongLength();
  1421. if (n + (ulong) arguments.Length > ArrayOperations.MaxArrayLikeLength)
  1422. {
  1423. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1424. }
  1425. foreach (var a in arguments)
  1426. {
  1427. o.Set(n, a, true);
  1428. n++;
  1429. }
  1430. o.SetLength(n);
  1431. return n;
  1432. }
  1433. public JsValue Pop(JsValue thisObject, JsValue[] arguments)
  1434. {
  1435. if (thisObject is JsArray { CanUseFastAccess: true } array)
  1436. {
  1437. return array.Pop();
  1438. }
  1439. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1440. ulong len = o.GetLongLength();
  1441. if (len == 0)
  1442. {
  1443. o.SetLength(0);
  1444. return Undefined;
  1445. }
  1446. len -= 1;
  1447. JsValue element = o.Get(len);
  1448. o.DeletePropertyOrThrow(len);
  1449. o.SetLength(len);
  1450. return element;
  1451. }
  1452. private JsValue[] CreateBackingArray(ulong length)
  1453. {
  1454. ValidateArrayLength(length);
  1455. return new JsValue[length];
  1456. }
  1457. private void ValidateArrayLength(ulong length)
  1458. {
  1459. if (length > ArrayOperations.MaxArrayLength)
  1460. {
  1461. ExceptionHelper.ThrowRangeError(_engine.Realm, "Invalid array length " + length);
  1462. }
  1463. }
  1464. internal sealed class ArrayComparer : IComparer<JsValue>
  1465. {
  1466. /// <summary>
  1467. /// Default instance without any compare function.
  1468. /// </summary>
  1469. public static readonly ArrayComparer Default = new(null, null);
  1470. public static ArrayComparer WithFunction(Engine engine, ICallable? compare)
  1471. {
  1472. return compare is null ? Default : new ArrayComparer(engine, compare);
  1473. }
  1474. private readonly Engine? _engine;
  1475. private readonly ICallable? _compare;
  1476. private readonly JsValue[] _comparableArray = new JsValue[2];
  1477. private ArrayComparer(Engine? engine, ICallable? compare)
  1478. {
  1479. _engine = engine;
  1480. _compare = compare;
  1481. }
  1482. public int Compare(JsValue? x, JsValue? y)
  1483. {
  1484. var xIsNull = x is null;
  1485. var yIsNull = y is null;
  1486. if (xIsNull)
  1487. {
  1488. if (yIsNull)
  1489. {
  1490. return 0;
  1491. }
  1492. return 1;
  1493. }
  1494. else
  1495. {
  1496. if (yIsNull)
  1497. {
  1498. return -1;
  1499. }
  1500. }
  1501. var xUndefined = x!.IsUndefined();
  1502. var yUndefined = y!.IsUndefined();
  1503. if (xUndefined && yUndefined)
  1504. {
  1505. return 0;
  1506. }
  1507. if (xUndefined)
  1508. {
  1509. return 1;
  1510. }
  1511. if (yUndefined)
  1512. {
  1513. return -1;
  1514. }
  1515. if (_compare != null)
  1516. {
  1517. _engine!.RunBeforeExecuteStatementChecks(null);
  1518. _comparableArray[0] = x!;
  1519. _comparableArray[1] = y!;
  1520. var s = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1521. if (s < 0)
  1522. {
  1523. return -1;
  1524. }
  1525. if (s > 0)
  1526. {
  1527. return 1;
  1528. }
  1529. return 0;
  1530. }
  1531. var xString = TypeConverter.ToString(x!);
  1532. var yString = TypeConverter.ToString(y!);
  1533. return string.CompareOrdinal(xString, yString);
  1534. }
  1535. }
  1536. }