ArrayInstance.cs 39 KB

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