ArrayPrototype.cs 53 KB

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