ArrayInstance.cs 45 KB

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