ArrayPrototype.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  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 LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "at", prototype.At, 1, PropertyFlag.Configurable), PropertyFlags),
  41. ["concat"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "concat", prototype.Concat, 1, PropertyFlag.Configurable), PropertyFlags),
  42. ["copyWithin"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "copyWithin", prototype.CopyWithin, 2, PropertyFlag.Configurable), PropertyFlags),
  43. ["entries"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "entries", prototype.Entries, 0, PropertyFlag.Configurable), PropertyFlags),
  44. ["every"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "every", prototype.Every, 1, PropertyFlag.Configurable), PropertyFlags),
  45. ["fill"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "fill", prototype.Fill, 1, PropertyFlag.Configurable), PropertyFlags),
  46. ["filter"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "filter", prototype.Filter, 1, PropertyFlag.Configurable), PropertyFlags),
  47. ["find"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "find", prototype.Find, 1, PropertyFlag.Configurable), PropertyFlags),
  48. ["findIndex"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findIndex", prototype.FindIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  49. ["findLast"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLast", prototype.FindLast, 1, PropertyFlag.Configurable), PropertyFlags),
  50. ["findLastIndex"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLastIndex", prototype.FindLastIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  51. ["flat"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "flat", prototype.Flat, 0, PropertyFlag.Configurable), PropertyFlags),
  52. ["flatMap"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "flatMap", prototype.FlatMap, 1, PropertyFlag.Configurable), PropertyFlags),
  53. ["forEach"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "forEach", prototype.ForEach, 1, PropertyFlag.Configurable), PropertyFlags),
  54. ["includes"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "includes", prototype.Includes, 1, PropertyFlag.Configurable), PropertyFlags),
  55. ["indexOf"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "indexOf", prototype.IndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  56. ["join"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "join", prototype.Join, 1, PropertyFlag.Configurable), PropertyFlags),
  57. ["keys"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "keys", prototype.Keys, 0, PropertyFlag.Configurable), PropertyFlags),
  58. ["lastIndexOf"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "lastIndexOf", prototype.LastIndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  59. ["map"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "map", prototype.Map, 1, PropertyFlag.Configurable), PropertyFlags),
  60. ["pop"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "pop", prototype.Pop, 0, PropertyFlag.Configurable), PropertyFlags),
  61. ["push"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "push", prototype.Push, 1, PropertyFlag.Configurable), PropertyFlags),
  62. ["reduce"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduce", prototype.Reduce, 1, PropertyFlag.Configurable), PropertyFlags),
  63. ["reduceRight"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduceRight", prototype.ReduceRight, 1, PropertyFlag.Configurable), PropertyFlags),
  64. ["reverse"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reverse", prototype.Reverse, 0, PropertyFlag.Configurable), PropertyFlags),
  65. ["shift"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "shift",prototype. Shift, 0, PropertyFlag.Configurable), PropertyFlags),
  66. ["slice"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "slice", prototype.Slice, 2, PropertyFlag.Configurable), PropertyFlags),
  67. ["some"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "some", prototype.Some, 1, PropertyFlag.Configurable), PropertyFlags),
  68. ["sort"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "sort", prototype.Sort, 1, PropertyFlag.Configurable), PropertyFlags),
  69. ["splice"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "splice", prototype.Splice, 2, PropertyFlag.Configurable), PropertyFlags),
  70. ["toLocaleString"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLocaleString", prototype.ToLocaleString, 0, PropertyFlag.Configurable), PropertyFlags),
  71. ["toReversed"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toReversed", prototype.ToReversed, 0, PropertyFlag.Configurable), PropertyFlags),
  72. ["toSorted"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toSorted", prototype.ToSorted, 1, PropertyFlag.Configurable), PropertyFlags),
  73. ["toSpliced"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toSpliced", prototype.ToSpliced, 2, PropertyFlag.Configurable), PropertyFlags),
  74. ["toString"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toString", prototype.ToString, 0, PropertyFlag.Configurable), PropertyFlags),
  75. ["unshift"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "unshift", prototype.Unshift, 1, PropertyFlag.Configurable), PropertyFlags),
  76. ["values"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "values", prototype.Values, 0, PropertyFlag.Configurable), PropertyFlags),
  77. ["with"] = new LazyPropertyDescriptor<ArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "with", prototype.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>(_engine, static engine =>
  85. {
  86. var unscopables = new JsObject(engine)
  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 (!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. // only prepare for larger if we cannot rely on default growth algorithm
  891. if (len + argCount > 2 * len)
  892. {
  893. o.EnsureCapacity(len + argCount);
  894. }
  895. var minIndex = o.GetSmallestIndex(len);
  896. for (var k = len; k > minIndex; k--)
  897. {
  898. var from = k - 1;
  899. var to = k + argCount - 1;
  900. if (o.TryGetValue(from, out var fromValue))
  901. {
  902. o.Set(to, fromValue, updateLength: false);
  903. }
  904. else
  905. {
  906. o.DeletePropertyOrThrow(to);
  907. }
  908. }
  909. for (uint j = 0; j < argCount; j++)
  910. {
  911. o.Set(j, arguments[j], updateLength: false);
  912. }
  913. o.SetLength(len + argCount);
  914. return len + argCount;
  915. }
  916. /// <summary>
  917. /// https://tc39.es/ecma262/#sec-array.prototype.sort
  918. /// </summary>
  919. private JsValue Sort(JsValue thisObject, JsValue[] arguments)
  920. {
  921. var obj = ArrayOperations.For(_realm, thisObject, forWrite: true);
  922. var compareFn = GetCompareFunction(arguments.At(0));
  923. var len = obj.GetLength();
  924. if (len <= 1)
  925. {
  926. return obj.Target;
  927. }
  928. var items = new List<JsValue>((int) System.Math.Min(10_000, obj.GetLength()));
  929. for (ulong k = 0; k < len; ++k)
  930. {
  931. if (obj.TryGetValue(k, out var kValue))
  932. {
  933. items.Add(kValue);
  934. }
  935. }
  936. var itemCount = items.Count;
  937. // don't eat inner exceptions
  938. try
  939. {
  940. var array = items.OrderBy(x => x, ArrayComparer.WithFunction(_engine, compareFn!)).ToArray();
  941. uint j;
  942. for (j = 0; j < itemCount; ++j)
  943. {
  944. var updateLength = j == itemCount - 1;
  945. obj.Set(j, array[j], updateLength: updateLength, throwOnError: true);
  946. }
  947. for (; j < len; ++j)
  948. {
  949. obj.DeletePropertyOrThrow(j);
  950. }
  951. }
  952. catch (InvalidOperationException e)
  953. {
  954. throw e.InnerException ?? e;
  955. }
  956. return obj.Target;
  957. }
  958. /// <summary>
  959. /// https://tc39.es/ecma262/#sec-array.prototype.slice
  960. /// </summary>
  961. private JsValue Slice(JsValue thisObject, JsValue[] arguments)
  962. {
  963. var start = arguments.At(0);
  964. var end = arguments.At(1);
  965. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  966. var len = o.GetLongLength();
  967. var relativeStart = TypeConverter.ToInteger(start);
  968. ulong k;
  969. if (relativeStart < 0)
  970. {
  971. k = (ulong) System.Math.Max(len + relativeStart, 0);
  972. }
  973. else
  974. {
  975. k = (ulong) System.Math.Min(TypeConverter.ToInteger(start), len);
  976. }
  977. ulong final;
  978. if (end.IsUndefined())
  979. {
  980. final = (ulong) TypeConverter.ToNumber(len);
  981. }
  982. else
  983. {
  984. double relativeEnd = TypeConverter.ToInteger(end);
  985. if (relativeEnd < 0)
  986. {
  987. final = (ulong) System.Math.Max(len + relativeEnd, 0);
  988. }
  989. else
  990. {
  991. final = (ulong) System.Math.Min(relativeEnd, len);
  992. }
  993. }
  994. if (k < final && final - k > ArrayOperations.MaxArrayLength)
  995. {
  996. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");
  997. }
  998. var length = (uint) System.Math.Max(0, (long) final - (long) k);
  999. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), length);
  1000. if (thisObject is JsArray ai && a is JsArray a2)
  1001. {
  1002. a2.CopyValues(ai, (uint) k, 0, length);
  1003. }
  1004. else
  1005. {
  1006. // slower path
  1007. var operations = ArrayOperations.For(a, forWrite: true);
  1008. for (uint n = 0; k < final; k++, n++)
  1009. {
  1010. if (o.TryGetValue(k, out var kValue))
  1011. {
  1012. operations.CreateDataPropertyOrThrow(n, kValue);
  1013. }
  1014. }
  1015. }
  1016. return a;
  1017. }
  1018. private JsValue Shift(JsValue thisObject, JsValue[] arg2)
  1019. {
  1020. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1021. var len = o.GetLength();
  1022. if (len == 0)
  1023. {
  1024. o.SetLength(0);
  1025. return Undefined;
  1026. }
  1027. var first = o.Get(0);
  1028. for (uint k = 1; k < len; k++)
  1029. {
  1030. var to = k - 1;
  1031. if (o.TryGetValue(k, out var fromVal))
  1032. {
  1033. o.Set(to, fromVal, throwOnError: false);
  1034. }
  1035. else
  1036. {
  1037. o.DeletePropertyOrThrow(to);
  1038. }
  1039. }
  1040. o.DeletePropertyOrThrow(len - 1);
  1041. o.SetLength(len - 1);
  1042. return first;
  1043. }
  1044. /// <summary>
  1045. /// https://tc39.es/ecma262/#sec-array.prototype.reverse
  1046. /// </summary>
  1047. private JsValue Reverse(JsValue thisObject, JsValue[] arguments)
  1048. {
  1049. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1050. var len = o.GetLongLength();
  1051. var middle = (ulong) System.Math.Floor(len / 2.0);
  1052. uint lower = 0;
  1053. while (lower != middle)
  1054. {
  1055. var upper = len - lower - 1;
  1056. var lowerExists = o.HasProperty(lower);
  1057. var lowerValue = lowerExists ? o.Get(lower) : null;
  1058. var upperExists = o.HasProperty(upper);
  1059. var upperValue = upperExists ? o.Get(upper) : null;
  1060. if (lowerExists && upperExists)
  1061. {
  1062. o.Set(lower, upperValue!, throwOnError: true);
  1063. o.Set(upper, lowerValue!, throwOnError: true);
  1064. }
  1065. if (!lowerExists && upperExists)
  1066. {
  1067. o.Set(lower, upperValue!, throwOnError: true);
  1068. o.DeletePropertyOrThrow(upper);
  1069. }
  1070. if (lowerExists && !upperExists)
  1071. {
  1072. o.DeletePropertyOrThrow(lower);
  1073. o.Set(upper, lowerValue!, throwOnError: true);
  1074. }
  1075. lower++;
  1076. }
  1077. return o.Target;
  1078. }
  1079. /// <summary>
  1080. /// https://tc39.es/ecma262/#sec-array.prototype.join
  1081. /// </summary>
  1082. private JsValue Join(JsValue thisObject, JsValue[] arguments)
  1083. {
  1084. var separator = arguments.At(0);
  1085. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1086. var len = o.GetLength();
  1087. var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator);
  1088. // as per the spec, this has to be called after ToString(separator)
  1089. if (len == 0)
  1090. {
  1091. return JsString.Empty;
  1092. }
  1093. static string StringFromJsValue(JsValue value)
  1094. {
  1095. return value.IsNullOrUndefined()
  1096. ? ""
  1097. : TypeConverter.ToString(value);
  1098. }
  1099. var s = StringFromJsValue(o.Get(0));
  1100. if (len == 1)
  1101. {
  1102. return s;
  1103. }
  1104. using var sb = new ValueStringBuilder();
  1105. sb.Append(s);
  1106. for (uint k = 1; k < len; k++)
  1107. {
  1108. if (sep != "")
  1109. {
  1110. sb.Append(sep);
  1111. }
  1112. sb.Append(StringFromJsValue(o.Get(k)));
  1113. }
  1114. return sb.ToString();
  1115. }
  1116. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1117. {
  1118. var array = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1119. var len = array.GetLength();
  1120. const string Separator = ",";
  1121. if (len == 0)
  1122. {
  1123. return JsString.Empty;
  1124. }
  1125. JsValue r;
  1126. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1127. {
  1128. r = JsString.Empty;
  1129. }
  1130. else
  1131. {
  1132. r = Invoke(firstElement, "toLocaleString", System.Array.Empty<JsValue>());
  1133. }
  1134. for (uint k = 1; k < len; k++)
  1135. {
  1136. var s = r + Separator;
  1137. if (!array.TryGetValue(k, out var nextElement) || nextElement.IsNull())
  1138. {
  1139. r = JsString.Empty;
  1140. }
  1141. else
  1142. {
  1143. r = Invoke(nextElement, "toLocaleString", System.Array.Empty<JsValue>());
  1144. }
  1145. r = s + r;
  1146. }
  1147. return r;
  1148. }
  1149. /// <summary>
  1150. /// https://tc39.es/ecma262/#sec-array.prototype.concat
  1151. /// </summary>
  1152. private JsValue Concat(JsValue thisObject, JsValue[] arguments)
  1153. {
  1154. var o = TypeConverter.ToObject(_realm, thisObject);
  1155. var items = new List<JsValue>(arguments.Length + 1) { o };
  1156. items.AddRange(arguments);
  1157. uint n = 0;
  1158. var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), 0);
  1159. var aOperations = ArrayOperations.For(a, forWrite: true);
  1160. for (var i = 0; i < items.Count; i++)
  1161. {
  1162. var e = items[i];
  1163. if (e is ObjectInstance { IsConcatSpreadable: true } oi)
  1164. {
  1165. if (e is JsArray eArray && a is JsArray a2)
  1166. {
  1167. a2.CopyValues(eArray, 0, n, eArray.GetLength());
  1168. n += eArray.GetLength();
  1169. }
  1170. else
  1171. {
  1172. var operations = ArrayOperations.For(oi, forWrite: false);
  1173. var len = operations.GetLongLength();
  1174. if (n + len > ArrayOperations.MaxArrayLikeLength)
  1175. {
  1176. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1177. }
  1178. for (uint k = 0; k < len; k++)
  1179. {
  1180. operations.TryGetValue(k, out var subElement);
  1181. aOperations.CreateDataPropertyOrThrow(n, subElement);
  1182. n++;
  1183. }
  1184. }
  1185. }
  1186. else
  1187. {
  1188. aOperations.CreateDataPropertyOrThrow(n, e);
  1189. n++;
  1190. }
  1191. }
  1192. // this is not in the specs, but is necessary in case the last element of the last
  1193. // array doesn't exist, and thus the length would not be incremented
  1194. a.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(n, PropertyFlag.OnlyWritable));
  1195. return a;
  1196. }
  1197. internal JsValue ToString(JsValue thisObject, JsValue[] arguments)
  1198. {
  1199. var array = TypeConverter.ToObject(_realm, thisObject);
  1200. Func<JsValue, JsValue[], JsValue> func;
  1201. if (array.Get("join") is ICallable joinFunc)
  1202. {
  1203. func = joinFunc.Call;
  1204. }
  1205. else
  1206. {
  1207. func = _realm.Intrinsics.Object.PrototypeObject.ToObjectString;
  1208. }
  1209. return func(array, Arguments.Empty);
  1210. }
  1211. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1212. {
  1213. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1214. var len = o.GetLongLength();
  1215. if (len == 0)
  1216. {
  1217. return new JsArray(_engine);
  1218. }
  1219. var a = CreateBackingArray(len);
  1220. ulong k = 0;
  1221. while (k < len)
  1222. {
  1223. var from = len - k - 1;
  1224. a[k++] = o.Get(from);
  1225. }
  1226. return new JsArray(_engine, a);
  1227. }
  1228. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1229. {
  1230. var o = ArrayOperations.For(_realm, thisObject, forWrite: false);
  1231. var compareFn = GetCompareFunction(arguments.At(0));
  1232. var len = o.GetLongLength();
  1233. ValidateArrayLength(len);
  1234. if (len == 0)
  1235. {
  1236. return new JsArray(_engine);
  1237. }
  1238. var array = o.GetAll(skipHoles: true);
  1239. array = SortArray(array, compareFn);
  1240. return new JsArray(_engine, array);
  1241. }
  1242. private JsValue ToSpliced(JsValue thisObject, JsValue[] arguments)
  1243. {
  1244. var start = arguments.At(0);
  1245. var deleteCount = arguments.At(1);
  1246. var o = ArrayOperations.For(_realm, TypeConverter.ToObject(_realm, thisObject), forWrite: false);
  1247. var len = o.GetLongLength();
  1248. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1249. ulong actualStart;
  1250. if (double.IsNegativeInfinity(relativeStart))
  1251. {
  1252. actualStart = 0;
  1253. }
  1254. else if (relativeStart < 0)
  1255. {
  1256. actualStart = (ulong) System.Math.Max(len + relativeStart, 0);
  1257. }
  1258. else
  1259. {
  1260. actualStart = (ulong) System.Math.Min(relativeStart, len);
  1261. }
  1262. var items = System.Array.Empty<JsValue>();
  1263. ulong insertCount;
  1264. ulong actualDeleteCount;
  1265. if (arguments.Length == 0)
  1266. {
  1267. insertCount = 0;
  1268. actualDeleteCount = 0;
  1269. }
  1270. else if (arguments.Length == 1)
  1271. {
  1272. insertCount = 0;
  1273. actualDeleteCount = len - actualStart;
  1274. }
  1275. else
  1276. {
  1277. insertCount = (ulong) (arguments.Length - 2);
  1278. var dc = TypeConverter.ToIntegerOrInfinity(deleteCount);
  1279. actualDeleteCount = (ulong) System.Math.Min(System.Math.Max(dc, 0), len - actualStart);
  1280. items = System.Array.Empty<JsValue>();
  1281. if (arguments.Length > 2)
  1282. {
  1283. items = new JsValue[arguments.Length - 2];
  1284. System.Array.Copy(arguments, 2, items, 0, items.Length);
  1285. }
  1286. }
  1287. var newLen = len + insertCount - actualDeleteCount;
  1288. if (newLen > ArrayOperations.MaxArrayLikeLength)
  1289. {
  1290. ExceptionHelper.ThrowTypeError(_realm, "Invalid input length");
  1291. }
  1292. ValidateArrayLength(newLen);
  1293. var r = actualStart + actualDeleteCount;
  1294. var a = new JsArray(_engine, (uint) newLen);
  1295. uint i = 0;
  1296. while (i < actualStart)
  1297. {
  1298. a.SetIndexValue(i, o.Get(i), updateLength: false);
  1299. i++;
  1300. }
  1301. a.SetLength((uint) actualStart);
  1302. foreach (var item in items)
  1303. {
  1304. a.SetIndexValue(i++, item, updateLength: false);
  1305. }
  1306. while (i < newLen)
  1307. {
  1308. var fromValue = o.Get(r);
  1309. a.SetIndexValue(i, fromValue, updateLength: false);
  1310. i++;
  1311. r++;
  1312. }
  1313. a.SetLength(i);
  1314. return a;
  1315. }
  1316. private JsValue[] SortArray(IEnumerable<JsValue> array, ICallable? compareFn)
  1317. {
  1318. var comparer = ArrayComparer.WithFunction(_engine, compareFn);
  1319. try
  1320. {
  1321. return array.OrderBy(x => x, comparer).ToArray();
  1322. }
  1323. catch (InvalidOperationException e)
  1324. {
  1325. throw e.InnerException ?? e;
  1326. }
  1327. }
  1328. private ICallable? GetCompareFunction(JsValue compareArg)
  1329. {
  1330. ICallable? compareFn = null;
  1331. if (!compareArg.IsUndefined())
  1332. {
  1333. if (compareArg is not ICallable callable)
  1334. {
  1335. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1336. return null;
  1337. }
  1338. compareFn = callable;
  1339. }
  1340. return compareFn;
  1341. }
  1342. /// <summary>
  1343. /// https://tc39.es/ecma262/#sec-array.prototype.reduceright
  1344. /// </summary>
  1345. private JsValue ReduceRight(JsValue thisObject, JsValue[] arguments)
  1346. {
  1347. var callbackfn = arguments.At(0);
  1348. var initialValue = arguments.At(1);
  1349. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1350. var len = o.GetLongLength();
  1351. var callable = GetCallable(callbackfn);
  1352. if (len == 0 && arguments.Length < 2)
  1353. {
  1354. ExceptionHelper.ThrowTypeError(_realm);
  1355. }
  1356. long k = (long) (len - 1);
  1357. JsValue accumulator = Undefined;
  1358. if (arguments.Length > 1)
  1359. {
  1360. accumulator = initialValue;
  1361. }
  1362. else
  1363. {
  1364. var kPresent = false;
  1365. while (kPresent == false && k >= 0)
  1366. {
  1367. if ((kPresent = o.TryGetValue((ulong) k, out var temp)))
  1368. {
  1369. accumulator = temp;
  1370. }
  1371. k--;
  1372. }
  1373. if (kPresent == false)
  1374. {
  1375. ExceptionHelper.ThrowTypeError(_realm);
  1376. }
  1377. }
  1378. var jsValues = new JsValue[4];
  1379. jsValues[3] = o.Target;
  1380. for (; k >= 0; k--)
  1381. {
  1382. if (o.TryGetValue((ulong) k, out var kvalue))
  1383. {
  1384. jsValues[0] = accumulator;
  1385. jsValues[1] = kvalue;
  1386. jsValues[2] = k;
  1387. accumulator = callable.Call(Undefined, jsValues);
  1388. }
  1389. }
  1390. return accumulator;
  1391. }
  1392. /// <summary>
  1393. /// https://tc39.es/ecma262/#sec-array.prototype.push
  1394. /// </summary>
  1395. public JsValue Push(JsValue thisObject, JsValue[] arguments)
  1396. {
  1397. if (thisObject is JsArray { CanUseFastAccess: true } arrayInstance)
  1398. {
  1399. return arrayInstance.Push(arguments);
  1400. }
  1401. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1402. var n = o.GetLongLength();
  1403. if (n + (ulong) arguments.Length > ArrayOperations.MaxArrayLikeLength)
  1404. {
  1405. ExceptionHelper.ThrowTypeError(_realm, "Invalid array length");
  1406. }
  1407. foreach (var a in arguments)
  1408. {
  1409. o.Set(n, a, true);
  1410. n++;
  1411. }
  1412. o.SetLength(n);
  1413. return n;
  1414. }
  1415. public JsValue Pop(JsValue thisObject, JsValue[] arguments)
  1416. {
  1417. if (thisObject is JsArray { CanUseFastAccess: true } array)
  1418. {
  1419. return array.Pop();
  1420. }
  1421. var o = ArrayOperations.For(_realm, thisObject, forWrite: true);
  1422. ulong len = o.GetLongLength();
  1423. if (len == 0)
  1424. {
  1425. o.SetLength(0);
  1426. return Undefined;
  1427. }
  1428. len -= 1;
  1429. JsValue element = o.Get(len);
  1430. o.DeletePropertyOrThrow(len);
  1431. o.SetLength(len);
  1432. return element;
  1433. }
  1434. private JsValue[] CreateBackingArray(ulong length)
  1435. {
  1436. ValidateArrayLength(length);
  1437. return new JsValue[length];
  1438. }
  1439. private void ValidateArrayLength(ulong length)
  1440. {
  1441. if (length > ArrayOperations.MaxArrayLength)
  1442. {
  1443. ExceptionHelper.ThrowRangeError(_engine.Realm, "Invalid array length " + length);
  1444. }
  1445. }
  1446. internal sealed class ArrayComparer : IComparer<JsValue>
  1447. {
  1448. /// <summary>
  1449. /// Default instance without any compare function.
  1450. /// </summary>
  1451. public static readonly ArrayComparer Default = new(null, null);
  1452. public static ArrayComparer WithFunction(Engine engine, ICallable? compare)
  1453. {
  1454. return compare is null ? Default : new ArrayComparer(engine, compare);
  1455. }
  1456. private readonly Engine? _engine;
  1457. private readonly ICallable? _compare;
  1458. private readonly JsValue[] _comparableArray = new JsValue[2];
  1459. private ArrayComparer(Engine? engine, ICallable? compare)
  1460. {
  1461. _engine = engine;
  1462. _compare = compare;
  1463. }
  1464. public int Compare(JsValue? x, JsValue? y)
  1465. {
  1466. var xIsNull = x is null;
  1467. var yIsNull = y is null;
  1468. if (xIsNull)
  1469. {
  1470. if (yIsNull)
  1471. {
  1472. return 0;
  1473. }
  1474. return 1;
  1475. }
  1476. else
  1477. {
  1478. if (yIsNull)
  1479. {
  1480. return -1;
  1481. }
  1482. }
  1483. var xUndefined = x!.IsUndefined();
  1484. var yUndefined = y!.IsUndefined();
  1485. if (xUndefined && yUndefined)
  1486. {
  1487. return 0;
  1488. }
  1489. if (xUndefined)
  1490. {
  1491. return 1;
  1492. }
  1493. if (yUndefined)
  1494. {
  1495. return -1;
  1496. }
  1497. if (_compare != null)
  1498. {
  1499. _engine!.RunBeforeExecuteStatementChecks(null);
  1500. _comparableArray[0] = x!;
  1501. _comparableArray[1] = y!;
  1502. var s = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1503. if (s < 0)
  1504. {
  1505. return -1;
  1506. }
  1507. if (s > 0)
  1508. {
  1509. return 1;
  1510. }
  1511. return 0;
  1512. }
  1513. var xString = TypeConverter.ToString(x!);
  1514. var yString = TypeConverter.ToString(y!);
  1515. return string.CompareOrdinal(xString, yString);
  1516. }
  1517. }
  1518. }
  1519. }