ArrayInstance.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  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 = System.Array.Empty<JsValue?>();
  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] : System.Array.Empty<JsValue?>();
  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. ExceptionHelper.ThrowRangeError(_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. ExceptionHelper.ThrowTypeError(_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. var newArray = new JsValue[capacity];
  815. System.Array.Copy(dense, newArray, dense.Length);
  816. _dense = newArray;
  817. }
  818. public JsValue[] ToArray()
  819. {
  820. var length = GetLength();
  821. var array = new JsValue[length];
  822. for (uint i = 0; i < length; i++)
  823. {
  824. TryGetValue(i, out var outValue);
  825. array[i] = outValue;
  826. }
  827. return array;
  828. }
  829. IEnumerator IEnumerable.GetEnumerator()
  830. {
  831. return GetEnumerator();
  832. }
  833. public IEnumerator<JsValue> GetEnumerator()
  834. {
  835. foreach (var (_, value) in this.Enumerate())
  836. {
  837. yield return value;
  838. }
  839. }
  840. private readonly record struct IndexedEntry(int Index, JsValue Value);
  841. private IEnumerable<IndexedEntry> Enumerate()
  842. {
  843. if (!CanUseFastAccess)
  844. {
  845. // slow path where prototype is also checked
  846. var length = GetLength();
  847. for (uint i = 0; i < length; i++)
  848. {
  849. TryGetValue(i, out var outValue);
  850. yield return new IndexedEntry((int) i, outValue);
  851. }
  852. yield break;
  853. }
  854. var temp = _dense;
  855. if (temp != null)
  856. {
  857. var length = System.Math.Min(temp.Length, GetLength());
  858. for (var i = 0; i < length; i++)
  859. {
  860. var value = temp[i];
  861. if (value is not null)
  862. {
  863. yield return new IndexedEntry(i, value);
  864. }
  865. }
  866. }
  867. else
  868. {
  869. foreach (var entry in _sparse!)
  870. {
  871. var descriptor = entry.Value;
  872. if (descriptor is not null)
  873. {
  874. yield return new IndexedEntry((int) entry.Key, descriptor.Value);
  875. }
  876. }
  877. }
  878. }
  879. /// <summary>
  880. /// Pushes the value to the end of the array instance.
  881. /// </summary>
  882. public void Push(JsValue value)
  883. {
  884. var initialLength = GetLength();
  885. var newLength = initialLength + 1;
  886. var temp = _dense;
  887. var canUseDirectIndexSet = temp != null && newLength <= temp.Length;
  888. double n = initialLength;
  889. if (canUseDirectIndexSet)
  890. {
  891. temp![(uint) n] = value;
  892. }
  893. else
  894. {
  895. WriteValueSlow(n, value);
  896. }
  897. // check if we can set length fast without breaking ECMA specification
  898. if (n < uint.MaxValue && CanSetLength())
  899. {
  900. _length!.Value = newLength;
  901. }
  902. else
  903. {
  904. if (!Set(CommonProperties.Length, newLength))
  905. {
  906. ExceptionHelper.ThrowTypeError(_engine.Realm);
  907. }
  908. }
  909. }
  910. /// <summary>
  911. /// Pushes the given values to the end of the array.
  912. /// </summary>
  913. public uint Push(JsValue[] values)
  914. {
  915. var initialLength = GetLength();
  916. var newLength = initialLength + values.Length;
  917. // if we see that we are bringing more than normal growth algorithm handles, ensure capacity eagerly
  918. if (_dense != null
  919. && initialLength != 0
  920. && values.Length > initialLength * 2
  921. && newLength <= MaxDenseArrayLength)
  922. {
  923. EnsureCapacity((uint) newLength);
  924. }
  925. var temp = _dense;
  926. ulong n = initialLength;
  927. foreach (var argument in values)
  928. {
  929. if (n < ArrayOperations.MaxArrayLength)
  930. {
  931. WriteArrayValue((uint) n, argument);
  932. }
  933. else
  934. {
  935. DefineOwnProperty(n, new PropertyDescriptor(argument, PropertyFlag.ConfigurableEnumerableWritable));
  936. }
  937. n++;
  938. }
  939. // check if we can set length fast without breaking ECMA specification
  940. if (n < ArrayOperations.MaxArrayLength && CanSetLength())
  941. {
  942. _length!.Value = n;
  943. }
  944. else
  945. {
  946. if (!Set(CommonProperties.Length, newLength))
  947. {
  948. ExceptionHelper.ThrowTypeError(_engine.Realm);
  949. }
  950. }
  951. return (uint) n;
  952. }
  953. public JsValue Pop()
  954. {
  955. var len = GetJsNumberLength();
  956. if (JsNumber.PositiveZero.Equals(len))
  957. {
  958. SetLength(len);
  959. return Undefined;
  960. }
  961. var newLength = (uint) len._value - 1;
  962. if (!Delete(newLength, unwrapFromNonDataDescriptor: true, out var element))
  963. {
  964. ExceptionHelper.ThrowTypeError(_engine.Realm);
  965. }
  966. SetLength(newLength);
  967. return element ?? Undefined;
  968. }
  969. private bool CanSetLength()
  970. {
  971. if (!_length!.IsAccessorDescriptor())
  972. {
  973. return _length.Writable;
  974. }
  975. var set = _length.Set;
  976. return set is not null && !set.IsUndefined();
  977. }
  978. [MethodImpl(MethodImplOptions.NoInlining)]
  979. private void WriteValueSlow(double n, JsValue value)
  980. {
  981. if (n < ArrayOperations.MaxArrayLength)
  982. {
  983. WriteArrayValue((uint) n, value);
  984. }
  985. else
  986. {
  987. DefinePropertyOrThrow((uint) n, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable));
  988. }
  989. }
  990. internal JsArray Map(JsValue[] arguments)
  991. {
  992. var callbackfn = arguments.At(0);
  993. var thisArg = arguments.At(1);
  994. var len = GetLength();
  995. var callable = GetCallable(callbackfn);
  996. var a = _engine.Realm.Intrinsics.Array.ArrayCreate(len);
  997. var args = _engine._jsValueArrayPool.RentArray(3);
  998. args[2] = this;
  999. for (uint k = 0; k < len; k++)
  1000. {
  1001. if (TryGetValue(k, out var kvalue))
  1002. {
  1003. args[0] = kvalue;
  1004. args[1] = k;
  1005. var mappedValue = callable.Call(thisArg, args);
  1006. if (a._dense != null && k < (uint) a._dense.Length)
  1007. {
  1008. a._dense[k] = mappedValue;
  1009. }
  1010. else
  1011. {
  1012. a.WriteArrayValue(k, mappedValue);
  1013. }
  1014. }
  1015. }
  1016. _engine._jsValueArrayPool.ReturnArray(args);
  1017. return a;
  1018. }
  1019. /// <inheritdoc />
  1020. internal sealed override bool FindWithCallback(
  1021. JsValue[] arguments,
  1022. out ulong index,
  1023. out JsValue value,
  1024. bool visitUnassigned,
  1025. bool fromEnd = false)
  1026. {
  1027. var thisArg = arguments.At(1);
  1028. var callbackfn = arguments.At(0);
  1029. var callable = GetCallable(callbackfn);
  1030. var len = GetLength();
  1031. if (len == 0)
  1032. {
  1033. index = 0;
  1034. value = Undefined;
  1035. return false;
  1036. }
  1037. var args = _engine._jsValueArrayPool.RentArray(3);
  1038. args[2] = this;
  1039. if (!fromEnd)
  1040. {
  1041. for (uint k = 0; k < len; k++)
  1042. {
  1043. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  1044. {
  1045. kvalue ??= Undefined;
  1046. args[0] = kvalue;
  1047. args[1] = k;
  1048. var testResult = callable.Call(thisArg, args);
  1049. if (TypeConverter.ToBoolean(testResult))
  1050. {
  1051. index = k;
  1052. value = kvalue;
  1053. return true;
  1054. }
  1055. }
  1056. }
  1057. }
  1058. else
  1059. {
  1060. for (long k = len - 1; k >= 0; k--)
  1061. {
  1062. var idx = (uint) k;
  1063. if (TryGetValue(idx, out var kvalue) || visitUnassigned)
  1064. {
  1065. kvalue ??= Undefined;
  1066. args[0] = kvalue;
  1067. args[1] = idx;
  1068. var testResult = callable.Call(thisArg, args);
  1069. if (TypeConverter.ToBoolean(testResult))
  1070. {
  1071. index = idx;
  1072. value = kvalue;
  1073. return true;
  1074. }
  1075. }
  1076. }
  1077. }
  1078. _engine._jsValueArrayPool.ReturnArray(args);
  1079. index = 0;
  1080. value = Undefined;
  1081. return false;
  1082. }
  1083. internal sealed override bool IsIntegerIndexedArray => true;
  1084. public JsValue this[uint index]
  1085. {
  1086. get
  1087. {
  1088. TryGetValue(index, out var kValue);
  1089. return kValue;
  1090. }
  1091. set
  1092. {
  1093. SetIndexValue(index, value, updateLength: true);
  1094. }
  1095. }
  1096. public JsValue this[int index]
  1097. {
  1098. get
  1099. {
  1100. JsValue? kValue;
  1101. if (index >= 0)
  1102. {
  1103. TryGetValue((uint) index, out kValue);
  1104. }
  1105. else
  1106. {
  1107. // slow path
  1108. TryGetValue(JsNumber.Create(index), out kValue);
  1109. }
  1110. return kValue;
  1111. }
  1112. set
  1113. {
  1114. if (index >= 0)
  1115. {
  1116. SetIndexValue((uint) index, value, updateLength: true);
  1117. }
  1118. else
  1119. {
  1120. Set(index, value);
  1121. }
  1122. }
  1123. }
  1124. /// <summary>
  1125. /// Fast path for concatenating sane-sized arrays, we assume size has been calculated.
  1126. /// </summary>
  1127. internal void CopyValues(JsArray source, uint sourceStartIndex, uint targetStartIndex, uint length)
  1128. {
  1129. if (length == 0)
  1130. {
  1131. return;
  1132. }
  1133. var sourceDense = source._dense;
  1134. if (sourceDense is not null)
  1135. {
  1136. EnsureCapacity((uint) (targetStartIndex + sourceDense.LongLength));
  1137. }
  1138. var dense = _dense;
  1139. if (dense != null
  1140. && sourceDense != null
  1141. && (uint) dense.Length >= targetStartIndex + length
  1142. && dense[targetStartIndex] is null)
  1143. {
  1144. uint j = 0;
  1145. for (var i = sourceStartIndex; i < sourceStartIndex + length; ++i, j++)
  1146. {
  1147. JsValue? sourceValue;
  1148. if (i < (uint) sourceDense.Length)
  1149. {
  1150. sourceValue = sourceDense[i];
  1151. }
  1152. else
  1153. {
  1154. source.TryGetValue(i, out sourceValue);
  1155. }
  1156. dense[targetStartIndex + j] = sourceValue;
  1157. }
  1158. }
  1159. else
  1160. {
  1161. // slower version
  1162. for (uint k = sourceStartIndex; k < length; k++)
  1163. {
  1164. if (source.TryGetValue(k, out var subElement))
  1165. {
  1166. SetIndexValue(targetStartIndex, subElement, updateLength: false);
  1167. }
  1168. targetStartIndex++;
  1169. }
  1170. }
  1171. }
  1172. public sealed override string ToString()
  1173. {
  1174. // debugger can make things hard when evaluates computed values
  1175. return "(" + (_length?._value!.AsNumber() ?? 0) + ")[]";
  1176. }
  1177. private static void ThrowMaximumArraySizeReachedException(Engine engine, uint capacity)
  1178. {
  1179. ExceptionHelper.ThrowMemoryLimitExceededException(
  1180. $"The array size {capacity} is larger than maximum allowed ({engine.Options.Constraints.MaxArraySize})"
  1181. );
  1182. }
  1183. }
  1184. internal static class ArrayPropertyDescriptorExtensions
  1185. {
  1186. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1187. internal static bool IsDefaultArrayValueDescriptor(this PropertyDescriptor propertyDescriptor)
  1188. => propertyDescriptor.Flags == PropertyFlag.ConfigurableEnumerableWritable && propertyDescriptor.IsDataDescriptor();
  1189. }