ArrayPrototype.cs 63 KB

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