ArrayInstance.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. using System.Collections;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Runtime.CompilerServices;
  4. using Jint.Native.Object;
  5. using Jint.Native.Symbol;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Descriptors;
  8. namespace Jint.Native.Array
  9. {
  10. public class ArrayInstance : ObjectInstance, IEnumerable<JsValue>
  11. {
  12. internal PropertyDescriptor? _length;
  13. private const int MaxDenseArrayLength = 10_000_000;
  14. // we have dense and sparse, we usually can start with dense and fall back to sparse when necessary
  15. // entries are lazy and can be either of type PropertyDescriptor or plain JsValue while there is no need for extra info
  16. internal object?[]? _dense;
  17. private Dictionary<uint, object?>? _sparse;
  18. private ObjectChangeFlags _objectChangeFlags;
  19. private bool _isObjectArray = true;
  20. private protected ArrayInstance(Engine engine, InternalTypes type) : base(engine, type: type)
  21. {
  22. _dense = System.Array.Empty<object?>();
  23. }
  24. private protected ArrayInstance(Engine engine, uint capacity = 0, uint length = 0) : base(engine)
  25. {
  26. _prototype = engine.Realm.Intrinsics.Array.PrototypeObject;
  27. if (capacity > engine.Options.Constraints.MaxArraySize)
  28. {
  29. ThrowMaximumArraySizeReachedException(engine, capacity);
  30. }
  31. if (capacity < MaxDenseArrayLength)
  32. {
  33. _dense = capacity > 0 ? new object?[capacity] : System.Array.Empty<object?>();
  34. }
  35. else
  36. {
  37. _sparse = new Dictionary<uint, object?>(1024);
  38. }
  39. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  40. }
  41. private protected ArrayInstance(Engine engine, JsValue[] items) : base(engine)
  42. {
  43. _prototype = engine.Realm.Intrinsics.Array.PrototypeObject;
  44. _isObjectArray = false;
  45. int length;
  46. if (items == null || items.Length == 0)
  47. {
  48. _dense = System.Array.Empty<object>();
  49. length = 0;
  50. }
  51. else
  52. {
  53. _dense = items;
  54. length = items.Length;
  55. }
  56. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  57. }
  58. private protected ArrayInstance(Engine engine, PropertyDescriptor[] items) : base(engine)
  59. {
  60. _prototype = engine.Realm.Intrinsics.Array.PrototypeObject;
  61. _isObjectArray = false;
  62. int length;
  63. if (items == null || items.Length == 0)
  64. {
  65. _dense = System.Array.Empty<object>();
  66. length = 0;
  67. }
  68. else
  69. {
  70. _dense = items;
  71. length = items.Length;
  72. }
  73. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  74. }
  75. public sealed override bool IsArrayLike => true;
  76. public sealed override bool IsArray() => true;
  77. internal sealed override bool HasOriginalIterator
  78. => ReferenceEquals(Get(GlobalSymbolRegistry.Iterator), _engine.Realm.Intrinsics.Array.PrototypeObject._originalIteratorFunction);
  79. /// <summary>
  80. /// Checks whether there have been changes to object prototype chain which could render fast access patterns impossible.
  81. /// </summary>
  82. internal bool CanUseFastAccess
  83. {
  84. get
  85. {
  86. if ((_objectChangeFlags & ObjectChangeFlags.NonDefaultDataDescriptorUsage) != 0)
  87. {
  88. // could be a mutating property for example, length might change, not safe anymore
  89. return false;
  90. }
  91. if (_prototype is not ArrayPrototype arrayPrototype
  92. || !ReferenceEquals(_prototype, _engine.Realm.Intrinsics.Array.PrototypeObject))
  93. {
  94. // somebody has switched prototype
  95. return false;
  96. }
  97. if ((arrayPrototype._objectChangeFlags & ObjectChangeFlags.ArrayIndex) != 0)
  98. {
  99. // maybe somebody moved integer property to prototype? not safe anymore
  100. return false;
  101. }
  102. if (arrayPrototype.Prototype is not ObjectPrototype arrayPrototypePrototype
  103. || !ReferenceEquals(arrayPrototypePrototype, _engine.Realm.Intrinsics.Array.PrototypeObject.Prototype))
  104. {
  105. return false;
  106. }
  107. return (arrayPrototypePrototype._objectChangeFlags & ObjectChangeFlags.ArrayIndex) == 0;
  108. }
  109. }
  110. public sealed override bool DefineOwnProperty(JsValue property, PropertyDescriptor desc)
  111. {
  112. var isArrayIndex = IsArrayIndex(property, out var index);
  113. TrackChanges(property, desc, isArrayIndex);
  114. if (isArrayIndex)
  115. {
  116. return DefineOwnProperty(index, desc);
  117. }
  118. if (property == CommonProperties.Length)
  119. {
  120. var value = desc.Value;
  121. if (ReferenceEquals(value, null))
  122. {
  123. return base.DefineOwnProperty(CommonProperties.Length, desc);
  124. }
  125. var newLenDesc = new PropertyDescriptor(desc);
  126. uint newLen = TypeConverter.ToUint32(value);
  127. if (newLen != TypeConverter.ToNumber(value))
  128. {
  129. ExceptionHelper.ThrowRangeError(_engine.Realm);
  130. }
  131. var oldLenDesc = _length;
  132. var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc!.Value);
  133. newLenDesc.Value = newLen;
  134. if (newLen >= oldLen)
  135. {
  136. return base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  137. }
  138. if (!oldLenDesc.Writable)
  139. {
  140. return false;
  141. }
  142. bool newWritable;
  143. if (!newLenDesc.WritableSet || newLenDesc.Writable)
  144. {
  145. newWritable = true;
  146. }
  147. else
  148. {
  149. newWritable = false;
  150. newLenDesc.Writable = true;
  151. }
  152. var succeeded = base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  153. if (!succeeded)
  154. {
  155. return false;
  156. }
  157. var count = _dense?.Length ?? _sparse!.Count;
  158. if (count < oldLen - newLen)
  159. {
  160. if (_dense != null)
  161. {
  162. for (uint keyIndex = 0; keyIndex < _dense.Length; ++keyIndex)
  163. {
  164. if (_dense[keyIndex] == null)
  165. {
  166. continue;
  167. }
  168. // is it the index of the array
  169. if (keyIndex >= newLen && keyIndex < oldLen)
  170. {
  171. var deleteSucceeded = Delete(keyIndex);
  172. if (!deleteSucceeded)
  173. {
  174. newLenDesc.Value = keyIndex + 1;
  175. if (!newWritable)
  176. {
  177. newLenDesc.Writable = false;
  178. }
  179. base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  180. return false;
  181. }
  182. }
  183. }
  184. }
  185. else
  186. {
  187. // in the case of sparse arrays, treat each concrete element instead of
  188. // iterating over all indexes
  189. var keys = new List<uint>(_sparse!.Keys);
  190. var keysCount = keys.Count;
  191. for (var i = 0; i < keysCount; i++)
  192. {
  193. var keyIndex = keys[i];
  194. // is it the index of the array
  195. if (keyIndex >= newLen && keyIndex < oldLen)
  196. {
  197. var deleteSucceeded = Delete(TypeConverter.ToString(keyIndex));
  198. if (!deleteSucceeded)
  199. {
  200. newLenDesc.Value = JsNumber.Create(keyIndex + 1);
  201. if (!newWritable)
  202. {
  203. newLenDesc.Writable = false;
  204. }
  205. base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  206. return false;
  207. }
  208. }
  209. }
  210. }
  211. }
  212. else
  213. {
  214. while (newLen < oldLen)
  215. {
  216. // algorithm as per the spec
  217. oldLen--;
  218. var deleteSucceeded = Delete(oldLen);
  219. if (!deleteSucceeded)
  220. {
  221. newLenDesc.Value = oldLen + 1;
  222. if (!newWritable)
  223. {
  224. newLenDesc.Writable = false;
  225. }
  226. base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  227. return false;
  228. }
  229. }
  230. }
  231. if (!newWritable)
  232. {
  233. base.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(value: null, PropertyFlag.WritableSet));
  234. }
  235. return true;
  236. }
  237. return base.DefineOwnProperty(property, desc);
  238. }
  239. private bool DefineOwnProperty(uint index, PropertyDescriptor desc)
  240. {
  241. var oldLenDesc = _length;
  242. var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc!.Value);
  243. if (index >= oldLen && !oldLenDesc.Writable)
  244. {
  245. return false;
  246. }
  247. var succeeded = base.DefineOwnProperty(index, desc);
  248. if (!succeeded)
  249. {
  250. return false;
  251. }
  252. if (index >= oldLen)
  253. {
  254. oldLenDesc.Value = index + 1;
  255. base.DefineOwnProperty(CommonProperties.Length, oldLenDesc);
  256. }
  257. return true;
  258. }
  259. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  260. internal uint GetLength()
  261. {
  262. if (_length is null)
  263. {
  264. return 0;
  265. }
  266. return (uint) ((JsNumber) _length._value!)._value;
  267. }
  268. protected sealed override void AddProperty(JsValue property, PropertyDescriptor descriptor)
  269. {
  270. if (property == CommonProperties.Length)
  271. {
  272. _length = descriptor;
  273. return;
  274. }
  275. base.AddProperty(property, descriptor);
  276. }
  277. protected sealed override bool TryGetProperty(JsValue property, [NotNullWhen(true)] out PropertyDescriptor? descriptor)
  278. {
  279. if (property == CommonProperties.Length)
  280. {
  281. descriptor = _length;
  282. return _length != null;
  283. }
  284. return base.TryGetProperty(property, out descriptor);
  285. }
  286. public sealed override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  287. {
  288. if ((types & Types.String) == 0)
  289. {
  290. return base.GetOwnPropertyKeys(types);
  291. }
  292. var temp = _dense;
  293. var properties = new List<JsValue>(temp?.Length ?? 0 + 1);
  294. if (temp != null)
  295. {
  296. var length = System.Math.Min(temp.Length, GetLength());
  297. for (var i = 0; i < length; i++)
  298. {
  299. if (temp[i] != null)
  300. {
  301. properties.Add(JsString.Create(i));
  302. }
  303. }
  304. }
  305. else
  306. {
  307. foreach (var entry in _sparse!)
  308. {
  309. properties.Add(JsString.Create(entry.Key));
  310. }
  311. }
  312. if (_length != null)
  313. {
  314. properties.Add(CommonProperties.Length);
  315. }
  316. properties.AddRange(base.GetOwnPropertyKeys(types));
  317. return properties;
  318. }
  319. /// <summary>
  320. /// Returns key and value pairs for actual array entries, excludes parent and optionally length.
  321. /// </summary>
  322. /// <param name="includeLength">Whether to return length and it's value.</param>
  323. public IEnumerable<KeyValuePair<string, JsValue>> GetEntries(bool includeLength = false)
  324. {
  325. foreach (var (index, value) in this.Enumerate())
  326. {
  327. yield return new KeyValuePair<string, JsValue>(TypeConverter.ToString(index), value);
  328. }
  329. if (includeLength && _length != null)
  330. {
  331. yield return new KeyValuePair<string, JsValue>(CommonProperties.Length._value, _length.Value);
  332. }
  333. }
  334. public sealed override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  335. {
  336. var temp = _dense;
  337. if (temp != null)
  338. {
  339. var length = System.Math.Min(temp.Length, GetLength());
  340. for (var i = 0; i < length; i++)
  341. {
  342. var value = temp[i];
  343. if (value != null)
  344. {
  345. if (value is not PropertyDescriptor descriptor)
  346. {
  347. temp[i] = descriptor = new PropertyDescriptor((JsValue) value, PropertyFlag.ConfigurableEnumerableWritable);
  348. }
  349. yield return new KeyValuePair<JsValue, PropertyDescriptor>(TypeConverter.ToString(i), descriptor);
  350. }
  351. }
  352. }
  353. else
  354. {
  355. foreach (var entry in _sparse!)
  356. {
  357. var value = entry.Value;
  358. if (value is not null)
  359. {
  360. if (value is not PropertyDescriptor descriptor)
  361. {
  362. _sparse[entry.Key] = descriptor = new PropertyDescriptor((JsValue) value, PropertyFlag.ConfigurableEnumerableWritable);
  363. }
  364. yield return new KeyValuePair<JsValue, PropertyDescriptor>(TypeConverter.ToString(entry.Key), descriptor);
  365. }
  366. }
  367. }
  368. if (_length != null)
  369. {
  370. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length);
  371. }
  372. foreach (var entry in base.GetOwnProperties())
  373. {
  374. yield return entry;
  375. }
  376. }
  377. public sealed override PropertyDescriptor GetOwnProperty(JsValue property)
  378. {
  379. if (property == CommonProperties.Length)
  380. {
  381. return _length ?? PropertyDescriptor.Undefined;
  382. }
  383. if (IsArrayIndex(property, out var index))
  384. {
  385. if (TryGetDescriptor(index, out var result))
  386. {
  387. return result;
  388. }
  389. return PropertyDescriptor.Undefined;
  390. }
  391. return base.GetOwnProperty(property);
  392. }
  393. internal JsValue Get(uint index)
  394. {
  395. if (!TryGetValue(index, out var value))
  396. {
  397. value = UnwrapJsValue(Prototype?.GetProperty(JsString.Create(index)) ?? PropertyDescriptor.Undefined);
  398. }
  399. return value;
  400. }
  401. public sealed override JsValue Get(JsValue property, JsValue receiver)
  402. {
  403. if (IsSafeSelfTarget(receiver) && IsArrayIndex(property, out var index) && TryGetValue(index, out var value))
  404. {
  405. return value;
  406. }
  407. if (property == CommonProperties.Length)
  408. {
  409. var length = _length?._value;
  410. if (length is not null)
  411. {
  412. return length;
  413. }
  414. }
  415. return base.Get(property, receiver);
  416. }
  417. public sealed override bool Set(JsValue property, JsValue value, JsValue receiver)
  418. {
  419. var isSafeSelfTarget = IsSafeSelfTarget(receiver);
  420. if (isSafeSelfTarget && IsArrayIndex(property, out var index))
  421. {
  422. var temp = _dense;
  423. if (temp is not null && CanUseFastAccess)
  424. {
  425. var current = index < temp.Length ? temp[index] : null;
  426. if (current is not PropertyDescriptor p || p.IsDefaultArrayValueDescriptor())
  427. {
  428. SetIndexValue(index, value, true);
  429. return true;
  430. }
  431. }
  432. // slower and more allocating
  433. if (TryGetDescriptor(index, out var descriptor))
  434. {
  435. if (descriptor.IsDefaultArrayValueDescriptor())
  436. {
  437. // fast path with direct write without allocations
  438. descriptor.Value = value;
  439. return true;
  440. }
  441. }
  442. else if (CanUseFastAccess)
  443. {
  444. // we know it's to be written to own array backing field as new value
  445. SetIndexValue(index, value, true);
  446. return true;
  447. }
  448. }
  449. // slow path
  450. return base.Set(property, value, receiver);
  451. }
  452. private bool IsSafeSelfTarget(JsValue receiver) => ReferenceEquals(receiver, this) && Extensible;
  453. public sealed override bool HasProperty(JsValue property)
  454. {
  455. if (IsArrayIndex(property, out var index) && GetValue(index, unwrapFromNonDataDescriptor: false) is not null)
  456. {
  457. return true;
  458. }
  459. return base.HasProperty(property);
  460. }
  461. protected internal sealed override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  462. {
  463. var isArrayIndex = IsArrayIndex(property, out var index);
  464. TrackChanges(property, desc, isArrayIndex);
  465. if (isArrayIndex)
  466. {
  467. WriteArrayValue(index, desc);
  468. }
  469. else if (property == CommonProperties.Length)
  470. {
  471. _length = desc;
  472. }
  473. else
  474. {
  475. base.SetOwnProperty(property, desc);
  476. }
  477. }
  478. private void TrackChanges(JsValue property, PropertyDescriptor desc, bool isArrayIndex)
  479. {
  480. EnsureInitialized();
  481. if (isArrayIndex)
  482. {
  483. if (!desc.IsDefaultArrayValueDescriptor())
  484. {
  485. _objectChangeFlags |= ObjectChangeFlags.NonDefaultDataDescriptorUsage;
  486. }
  487. _objectChangeFlags |= ObjectChangeFlags.ArrayIndex;
  488. }
  489. else
  490. {
  491. _objectChangeFlags |= property.IsSymbol() ? ObjectChangeFlags.Symbol : ObjectChangeFlags.Property;
  492. }
  493. }
  494. public sealed override void RemoveOwnProperty(JsValue p)
  495. {
  496. if (IsArrayIndex(p, out var index))
  497. {
  498. Delete(index);
  499. }
  500. if (p == CommonProperties.Length)
  501. {
  502. _length = null;
  503. }
  504. base.RemoveOwnProperty(p);
  505. }
  506. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  507. internal static bool IsArrayIndex(JsValue p, out uint index)
  508. {
  509. if (p is JsNumber number)
  510. {
  511. var value = number._value;
  512. var intValue = (uint) value;
  513. index = intValue;
  514. return value == intValue && intValue != uint.MaxValue;
  515. }
  516. index = ParseArrayIndex(p.ToString());
  517. return index != uint.MaxValue;
  518. // 15.4 - Use an optimized version of the specification
  519. // return TypeConverter.ToString(index) == TypeConverter.ToString(p) && index != uint.MaxValue;
  520. }
  521. internal static uint ParseArrayIndex(string p)
  522. {
  523. if (p.Length == 0)
  524. {
  525. return uint.MaxValue;
  526. }
  527. if (p.Length > 1 && p[0] == '0')
  528. {
  529. // If p is a number that start with '0' and is not '0' then
  530. // its ToString representation can't be the same a p. This is
  531. // not a valid array index. '01' !== ToString(ToUInt32('01'))
  532. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  533. return uint.MaxValue;
  534. }
  535. if (!uint.TryParse(p, out var d))
  536. {
  537. return uint.MaxValue;
  538. }
  539. return d;
  540. }
  541. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  542. internal void SetIndexValue(uint index, JsValue? value, bool updateLength)
  543. {
  544. if (updateLength)
  545. {
  546. EnsureCorrectLength(index);
  547. }
  548. WriteArrayValue(index, value);
  549. }
  550. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  551. private void EnsureCorrectLength(uint index)
  552. {
  553. var length = GetLength();
  554. if (index >= length)
  555. {
  556. SetLength(index + 1);
  557. }
  558. }
  559. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  560. internal void SetLength(ulong length)
  561. {
  562. var number = JsNumber.Create(length);
  563. if (Extensible && _length!._flags == PropertyFlag.OnlyWritable)
  564. {
  565. _length!.Value = number;
  566. }
  567. else
  568. {
  569. // slow path
  570. Set(CommonProperties.Length, number, true);
  571. }
  572. }
  573. internal uint GetSmallestIndex()
  574. {
  575. if (_dense != null)
  576. {
  577. return 0;
  578. }
  579. uint smallest = 0;
  580. // only try to help if collection reasonable small
  581. if (_sparse!.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0))
  582. {
  583. smallest = uint.MaxValue;
  584. foreach (var key in _sparse.Keys)
  585. {
  586. smallest = System.Math.Min(key, smallest);
  587. }
  588. }
  589. return smallest;
  590. }
  591. internal bool DeletePropertyOrThrow(uint index)
  592. {
  593. if (!Delete(index))
  594. {
  595. ExceptionHelper.ThrowTypeError(_engine.Realm);
  596. }
  597. return true;
  598. }
  599. internal bool Delete(uint index)
  600. {
  601. // check fast path
  602. var temp = _dense;
  603. if (temp != null)
  604. {
  605. if (index < (uint) temp.Length)
  606. {
  607. var value = temp[index];
  608. if (value is JsValue || value is PropertyDescriptor { Configurable: true })
  609. {
  610. temp[index] = null;
  611. return true;
  612. }
  613. }
  614. }
  615. if (!TryGetDescriptor(index, out var desc))
  616. {
  617. return true;
  618. }
  619. if (desc.Configurable)
  620. {
  621. DeleteAt(index);
  622. return true;
  623. }
  624. return false;
  625. }
  626. internal bool DeleteAt(uint index)
  627. {
  628. var temp = _dense;
  629. if (temp != null)
  630. {
  631. if (index < (uint) temp.Length)
  632. {
  633. temp[index] = null;
  634. return true;
  635. }
  636. }
  637. else
  638. {
  639. return _sparse!.Remove(index);
  640. }
  641. return false;
  642. }
  643. private bool TryGetDescriptor(uint index, [NotNullWhen(true)] out PropertyDescriptor? descriptor)
  644. {
  645. descriptor = null;
  646. var temp = _dense;
  647. if (temp != null)
  648. {
  649. if (index < (uint) temp.Length)
  650. {
  651. var value = temp[index];
  652. if (value is JsValue jsValue)
  653. {
  654. if (EnsureCompatibleDense(typeof(PropertyDescriptor)))
  655. {
  656. temp = _dense!;
  657. }
  658. temp[index] = descriptor = new PropertyDescriptor(jsValue, PropertyFlag.ConfigurableEnumerableWritable);
  659. }
  660. else if (value is PropertyDescriptor propertyDescriptor)
  661. {
  662. descriptor = propertyDescriptor;
  663. }
  664. }
  665. return descriptor != null;
  666. }
  667. if (_sparse!.TryGetValue(index, out var sparseValue))
  668. {
  669. if (sparseValue is JsValue jsValue)
  670. {
  671. _sparse[index] = descriptor = new PropertyDescriptor(jsValue, PropertyFlag.ConfigurableEnumerableWritable);
  672. }
  673. else if (sparseValue is PropertyDescriptor propertyDescriptor)
  674. {
  675. descriptor = propertyDescriptor;
  676. }
  677. }
  678. return descriptor is not null;
  679. }
  680. internal bool TryGetValue(uint index, out JsValue value)
  681. {
  682. value = GetValue(index, unwrapFromNonDataDescriptor: true)!;
  683. if (value is not null)
  684. {
  685. return true;
  686. }
  687. if (!CanUseFastAccess)
  688. {
  689. // slow path must be checked for prototype
  690. var prototype = Prototype;
  691. JsValue key = index;
  692. while (prototype is not null)
  693. {
  694. var desc = prototype.GetOwnProperty(key);
  695. if (desc != PropertyDescriptor.Undefined)
  696. {
  697. value = UnwrapJsValue(desc);
  698. return true;
  699. }
  700. prototype = prototype.Prototype;
  701. }
  702. }
  703. value = Undefined;
  704. return false;
  705. }
  706. private JsValue? GetValue(uint index, bool unwrapFromNonDataDescriptor)
  707. {
  708. object? value = null;
  709. var temp = _dense;
  710. if (temp != null)
  711. {
  712. if (index < (uint) temp.Length)
  713. {
  714. value = temp[index];
  715. }
  716. }
  717. else
  718. {
  719. _sparse!.TryGetValue(index, out value);
  720. }
  721. if (value is JsValue jsValue)
  722. {
  723. return jsValue;
  724. }
  725. if (value is PropertyDescriptor propertyDescriptor)
  726. {
  727. return propertyDescriptor.IsDataDescriptor() || unwrapFromNonDataDescriptor ? UnwrapJsValue(propertyDescriptor) : null;
  728. }
  729. return null;
  730. }
  731. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  732. private void WriteArrayValue(uint index, object? value)
  733. {
  734. var dense = _dense;
  735. if (dense != null && index < (uint) dense.Length)
  736. {
  737. if (value is not null && !_isObjectArray && EnsureCompatibleDense(value is JsValue ? typeof(JsValue) : typeof(PropertyDescriptor)))
  738. {
  739. dense = _dense;
  740. }
  741. dense![index] = value;
  742. }
  743. else
  744. {
  745. WriteArrayValueUnlikely(index, value);
  746. }
  747. }
  748. private void WriteArrayValueUnlikely(uint index, object? value)
  749. {
  750. // calculate eagerly so we know if we outgrow
  751. var dense = _dense;
  752. var newSize = dense != null && index >= (uint) dense.Length
  753. ? System.Math.Max(index, System.Math.Max(dense.Length, 2)) * 2
  754. : 0;
  755. var canUseDense = dense != null
  756. && index < MaxDenseArrayLength
  757. && newSize < MaxDenseArrayLength
  758. && index < dense.Length + 50; // looks sparse
  759. if (canUseDense)
  760. {
  761. EnsureCapacity((uint) newSize);
  762. _dense![index] = value;
  763. }
  764. else
  765. {
  766. if (dense != null)
  767. {
  768. ConvertToSparse();
  769. }
  770. _sparse![index] = value;
  771. }
  772. }
  773. /// <summary>
  774. /// Converts to object array when needed. Returns true if conversion was made.
  775. /// </summary>
  776. private bool EnsureCompatibleDense(Type expectedElementType)
  777. {
  778. if (!_isObjectArray)
  779. {
  780. return CheckConversionUnlikely(expectedElementType);
  781. }
  782. return false;
  783. }
  784. private bool CheckConversionUnlikely(Type expectedElementType)
  785. {
  786. var currentElementType = _dense!.GetType().GetElementType();
  787. if (currentElementType != typeof(object) && !expectedElementType.IsAssignableFrom(currentElementType))
  788. {
  789. // triggers conversion for array
  790. EnsureCapacity((uint) _dense.Length, force: true);
  791. return true;
  792. }
  793. return false;
  794. }
  795. private void ConvertToSparse()
  796. {
  797. _sparse = new Dictionary<uint, object?>(_dense!.Length <= 1024 ? _dense.Length : 0);
  798. // need to move data
  799. for (uint i = 0; i < (uint) _dense.Length; ++i)
  800. {
  801. if (_dense[i] != null)
  802. {
  803. _sparse[i] = _dense[i];
  804. }
  805. }
  806. _dense = null;
  807. }
  808. internal void EnsureCapacity(uint capacity, bool force = false)
  809. {
  810. if (!force && (capacity > MaxDenseArrayLength || _dense is null || capacity <= (uint) _dense.Length))
  811. {
  812. return;
  813. }
  814. if (capacity > _engine.Options.Constraints.MaxArraySize)
  815. {
  816. ThrowMaximumArraySizeReachedException(_engine, capacity);
  817. }
  818. // need to grow
  819. var newArray = new object[capacity];
  820. System.Array.Copy(_dense, newArray, _dense!.Length);
  821. _dense = newArray;
  822. _isObjectArray = true;
  823. }
  824. public JsValue[] ToArray()
  825. {
  826. var length = GetLength();
  827. var array = new JsValue[length];
  828. for (uint i = 0; i < length; i++)
  829. {
  830. TryGetValue(i, out var outValue);
  831. array[i] = outValue;
  832. }
  833. return array;
  834. }
  835. IEnumerator IEnumerable.GetEnumerator()
  836. {
  837. return GetEnumerator();
  838. }
  839. public IEnumerator<JsValue> GetEnumerator()
  840. {
  841. foreach (var (_, value) in this.Enumerate())
  842. {
  843. yield return value;
  844. }
  845. }
  846. private readonly record struct IndexedEntry(int Index, JsValue Value);
  847. private IEnumerable<IndexedEntry> Enumerate()
  848. {
  849. if (!CanUseFastAccess)
  850. {
  851. // slow path where prototype is also checked
  852. var length = GetLength();
  853. for (uint i = 0; i < length; i++)
  854. {
  855. TryGetValue(i, out var outValue);
  856. yield return new IndexedEntry((int) i, outValue);
  857. }
  858. yield break;
  859. }
  860. var temp = _dense;
  861. if (temp != null)
  862. {
  863. var length = System.Math.Min(temp.Length, GetLength());
  864. for (var i = 0; i < length; i++)
  865. {
  866. var value = temp[i];
  867. if (value != null)
  868. {
  869. if (value is not PropertyDescriptor descriptor)
  870. {
  871. yield return new IndexedEntry(i, (JsValue) value);
  872. }
  873. else
  874. {
  875. yield return new IndexedEntry(i, descriptor.Value);
  876. }
  877. }
  878. }
  879. }
  880. else
  881. {
  882. foreach (var entry in _sparse!)
  883. {
  884. var value = entry.Value;
  885. if (value is not null)
  886. {
  887. if (value is not PropertyDescriptor descriptor)
  888. {
  889. yield return new IndexedEntry((int) entry.Key, (JsValue) value);
  890. }
  891. else
  892. {
  893. yield return new IndexedEntry((int) entry.Key, descriptor.Value);
  894. }
  895. }
  896. }
  897. }
  898. }
  899. /// <summary>
  900. /// Pushes the value to the end of the array instance.
  901. /// </summary>
  902. public void Push(JsValue value)
  903. {
  904. var initialLength = GetLength();
  905. var newLength = initialLength + 1;
  906. var temp = _dense;
  907. var canUseDirectIndexSet = temp != null && newLength <= temp.Length;
  908. double n = initialLength;
  909. if (canUseDirectIndexSet)
  910. {
  911. temp![(uint) n] = value;
  912. }
  913. else
  914. {
  915. WriteValueSlow(n, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable));
  916. }
  917. // check if we can set length fast without breaking ECMA specification
  918. if (n < uint.MaxValue && CanSetLength())
  919. {
  920. _length!.Value = newLength;
  921. }
  922. else
  923. {
  924. if (!Set(CommonProperties.Length, newLength))
  925. {
  926. ExceptionHelper.ThrowTypeError(_engine.Realm);
  927. }
  928. }
  929. }
  930. /// <summary>
  931. /// Pushes the given values to the end of the array.
  932. /// </summary>
  933. public uint Push(JsValue[] values)
  934. {
  935. var initialLength = GetLength();
  936. var newLength = initialLength + values.Length;
  937. // if we see that we are bringing more than normal growth algorithm handles, ensure capacity eagerly
  938. if (_dense != null
  939. && initialLength != 0
  940. && values.Length > initialLength * 2
  941. && newLength <= MaxDenseArrayLength)
  942. {
  943. EnsureCapacity((uint) newLength);
  944. }
  945. var temp = _dense;
  946. ulong n = initialLength;
  947. foreach (var argument in values)
  948. {
  949. if (n < ArrayOperations.MaxArrayLength)
  950. {
  951. WriteArrayValue((uint) n, argument);
  952. }
  953. else
  954. {
  955. DefineOwnProperty(n, new PropertyDescriptor(argument, PropertyFlag.ConfigurableEnumerableWritable));
  956. }
  957. n++;
  958. }
  959. // check if we can set length fast without breaking ECMA specification
  960. if (n < ArrayOperations.MaxArrayLength && CanSetLength())
  961. {
  962. _length!.Value = n;
  963. }
  964. else
  965. {
  966. if (!Set(CommonProperties.Length, newLength))
  967. {
  968. ExceptionHelper.ThrowTypeError(_engine.Realm);
  969. }
  970. }
  971. return (uint) n;
  972. }
  973. private bool CanSetLength()
  974. {
  975. if (!_length!.IsAccessorDescriptor())
  976. {
  977. return _length.Writable;
  978. }
  979. var set = _length.Set;
  980. return set is not null && !set.IsUndefined();
  981. }
  982. [MethodImpl(MethodImplOptions.NoInlining)]
  983. private void WriteValueSlow(double n, PropertyDescriptor desc)
  984. {
  985. if (n < uint.MaxValue)
  986. {
  987. WriteArrayValue((uint) n, desc);
  988. }
  989. else
  990. {
  991. DefinePropertyOrThrow((uint) n, desc);
  992. }
  993. }
  994. internal JsArray Map(JsValue[] arguments)
  995. {
  996. var callbackfn = arguments.At(0);
  997. var thisArg = arguments.At(1);
  998. var len = GetLength();
  999. var callable = GetCallable(callbackfn);
  1000. var a = Engine.Realm.Intrinsics.Array.ArrayCreate(len);
  1001. var args = _engine._jsValueArrayPool.RentArray(3);
  1002. args[2] = this;
  1003. for (uint k = 0; k < len; k++)
  1004. {
  1005. if (TryGetValue(k, out var kvalue))
  1006. {
  1007. args[0] = kvalue;
  1008. args[1] = k;
  1009. var mappedValue = callable.Call(thisArg, args);
  1010. if (a._dense != null && k < (uint) a._dense.Length)
  1011. {
  1012. a._dense[k] = mappedValue;
  1013. }
  1014. else
  1015. {
  1016. a.WriteArrayValue(k, mappedValue);
  1017. }
  1018. }
  1019. }
  1020. _engine._jsValueArrayPool.ReturnArray(args);
  1021. return a;
  1022. }
  1023. /// <inheritdoc />
  1024. internal sealed override bool FindWithCallback(
  1025. JsValue[] arguments,
  1026. out uint index,
  1027. out JsValue value,
  1028. bool visitUnassigned,
  1029. bool fromEnd = false)
  1030. {
  1031. var thisArg = arguments.At(1);
  1032. var callbackfn = arguments.At(0);
  1033. var callable = GetCallable(callbackfn);
  1034. var len = GetLength();
  1035. if (len == 0)
  1036. {
  1037. index = 0;
  1038. value = Undefined;
  1039. return false;
  1040. }
  1041. var args = _engine._jsValueArrayPool.RentArray(3);
  1042. args[2] = this;
  1043. if (!fromEnd)
  1044. {
  1045. for (uint k = 0; k < len; k++)
  1046. {
  1047. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  1048. {
  1049. kvalue ??= Undefined;
  1050. args[0] = kvalue;
  1051. args[1] = k;
  1052. var testResult = callable.Call(thisArg, args);
  1053. if (TypeConverter.ToBoolean(testResult))
  1054. {
  1055. index = k;
  1056. value = kvalue;
  1057. return true;
  1058. }
  1059. }
  1060. }
  1061. }
  1062. else
  1063. {
  1064. for (long k = len - 1; k >= 0; k--)
  1065. {
  1066. var idx = (uint) k;
  1067. if (TryGetValue(idx, out var kvalue) || visitUnassigned)
  1068. {
  1069. kvalue ??= Undefined;
  1070. args[0] = kvalue;
  1071. args[1] = idx;
  1072. var testResult = callable.Call(thisArg, args);
  1073. if (TypeConverter.ToBoolean(testResult))
  1074. {
  1075. index = idx;
  1076. value = kvalue;
  1077. return true;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. _engine._jsValueArrayPool.ReturnArray(args);
  1083. index = 0;
  1084. value = Undefined;
  1085. return false;
  1086. }
  1087. public sealed override uint Length => GetLength();
  1088. internal sealed override bool IsIntegerIndexedArray => true;
  1089. public JsValue this[uint index]
  1090. {
  1091. get
  1092. {
  1093. TryGetValue(index, out var kValue);
  1094. return kValue;
  1095. }
  1096. set
  1097. {
  1098. SetIndexValue(index, value, updateLength: true);
  1099. }
  1100. }
  1101. public JsValue this[int index]
  1102. {
  1103. get
  1104. {
  1105. JsValue? kValue;
  1106. if (index >= 0)
  1107. {
  1108. TryGetValue((uint) index, out kValue);
  1109. }
  1110. else
  1111. {
  1112. // slow path
  1113. TryGetValue(JsNumber.Create(index), out kValue);
  1114. }
  1115. return kValue;
  1116. }
  1117. set
  1118. {
  1119. if (index >= 0)
  1120. {
  1121. SetIndexValue((uint) index, value, updateLength: true);
  1122. }
  1123. else
  1124. {
  1125. Set(index, value);
  1126. }
  1127. }
  1128. }
  1129. /// <summary>
  1130. /// Fast path for concatenating sane-sized arrays, we assume size has been calculated.
  1131. /// </summary>
  1132. internal void CopyValues(JsArray source, uint sourceStartIndex, uint targetStartIndex, uint length)
  1133. {
  1134. if (length == 0)
  1135. {
  1136. return;
  1137. }
  1138. var sourceDense = source._dense;
  1139. if (sourceDense is not null)
  1140. {
  1141. EnsureCapacity((uint) (targetStartIndex + sourceDense.LongLength));
  1142. }
  1143. var dense = _dense;
  1144. if (dense != null && sourceDense != null
  1145. && (uint) dense.Length >= targetStartIndex + length
  1146. && dense[targetStartIndex] is null)
  1147. {
  1148. uint j = 0;
  1149. for (var i = sourceStartIndex; i < sourceStartIndex + length; ++i, j++)
  1150. {
  1151. object? sourceValue;
  1152. if (i < (uint) sourceDense.Length && sourceDense[i] != null)
  1153. {
  1154. sourceValue = sourceDense[i];
  1155. if (sourceValue is PropertyDescriptor propertyDescriptor)
  1156. {
  1157. sourceValue = UnwrapJsValue(propertyDescriptor);
  1158. }
  1159. }
  1160. else
  1161. {
  1162. if (!source.TryGetValue(i, out var temp))
  1163. {
  1164. sourceValue = source.Prototype?.Get(JsString.Create(i));
  1165. }
  1166. else
  1167. {
  1168. sourceValue = temp;
  1169. }
  1170. }
  1171. dense[targetStartIndex + j] = sourceValue;
  1172. }
  1173. }
  1174. else
  1175. {
  1176. // slower version
  1177. for (uint k = sourceStartIndex; k < length; k++)
  1178. {
  1179. if (source.TryGetValue(k, out var subElement))
  1180. {
  1181. SetIndexValue(targetStartIndex, subElement, updateLength: false);
  1182. }
  1183. targetStartIndex++;
  1184. }
  1185. }
  1186. }
  1187. public sealed override string ToString()
  1188. {
  1189. // debugger can make things hard when evaluates computed values
  1190. return "(" + (_length?._value!.AsNumber() ?? 0) + ")[]";
  1191. }
  1192. private static void ThrowMaximumArraySizeReachedException(Engine engine, uint capacity)
  1193. {
  1194. ExceptionHelper.ThrowMemoryLimitExceededException(
  1195. $"The array size {capacity} is larger than maximum allowed ({engine.Options.Constraints.MaxArraySize})"
  1196. );
  1197. }
  1198. }
  1199. internal static class ArrayPropertyDescriptorExtensions
  1200. {
  1201. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1202. internal static bool IsDefaultArrayValueDescriptor(this PropertyDescriptor propertyDescriptor)
  1203. => propertyDescriptor.Flags == PropertyFlag.ConfigurableEnumerableWritable && propertyDescriptor.IsDataDescriptor();
  1204. }
  1205. }