ArrayInstance.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Jint.Native.Object;
  5. using Jint.Runtime;
  6. using Jint.Runtime.Descriptors;
  7. using PropertyDescriptor = Jint.Runtime.Descriptors.PropertyDescriptor;
  8. using TypeConverter = Jint.Runtime.TypeConverter;
  9. namespace Jint.Native.Array
  10. {
  11. public class ArrayInstance : ObjectInstance, IEnumerable<JsValue>
  12. {
  13. private const string PropertyNameLength = "length";
  14. private const int PropertyNameLengthLength = 6;
  15. internal PropertyDescriptor _length;
  16. private const int MaxDenseArrayLength = 1024 * 10;
  17. // we have dense and sparse, we usually can start with dense and fall back to sparse when necessary
  18. private PropertyDescriptor[] _dense;
  19. private Dictionary<uint, PropertyDescriptor> _sparse;
  20. public ArrayInstance(Engine engine, uint capacity = 0) : base(engine, objectClass: "Array")
  21. {
  22. if (capacity < MaxDenseArrayLength)
  23. {
  24. _dense = capacity > 0 ? new PropertyDescriptor[capacity] : System.Array.Empty<PropertyDescriptor>();
  25. }
  26. else
  27. {
  28. _sparse = new Dictionary<uint, PropertyDescriptor>((int) (capacity <= 1024 ? capacity : 1024));
  29. }
  30. }
  31. public ArrayInstance(Engine engine, PropertyDescriptor[] items) : base(engine, objectClass: "Array")
  32. {
  33. int length = 0;
  34. if (items == null || items.Length == 0)
  35. {
  36. _dense = System.Array.Empty<PropertyDescriptor>();
  37. length = 0;
  38. }
  39. else
  40. {
  41. _dense = items;
  42. length = items.Length;
  43. }
  44. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  45. }
  46. public ArrayInstance(Engine engine, Dictionary<uint, PropertyDescriptor> items) : base(engine, objectClass: "Array")
  47. {
  48. _sparse = items;
  49. var length = items?.Count ?? 0;
  50. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  51. }
  52. /// Implementation from ObjectInstance official specs as the one
  53. /// in ObjectInstance is optimized for the general case and wouldn't work
  54. /// for arrays
  55. public override void Put(string propertyName, JsValue value, bool throwOnError)
  56. {
  57. if (!CanPut(propertyName))
  58. {
  59. if (throwOnError)
  60. {
  61. ExceptionHelper.ThrowTypeError(Engine);
  62. }
  63. return;
  64. }
  65. var ownDesc = GetOwnProperty(propertyName);
  66. if (ownDesc.IsDataDescriptor())
  67. {
  68. var valueDesc = new PropertyDescriptor(value, PropertyFlag.None);
  69. DefineOwnProperty(propertyName, valueDesc, throwOnError);
  70. return;
  71. }
  72. // property is an accessor or inherited
  73. var desc = GetProperty(propertyName);
  74. if (desc.IsAccessorDescriptor())
  75. {
  76. var setter = desc.Set.TryCast<ICallable>();
  77. setter.Call(this, new[] {value});
  78. }
  79. else
  80. {
  81. var newDesc = new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable);
  82. DefineOwnProperty(propertyName, newDesc, throwOnError);
  83. }
  84. }
  85. public override bool DefineOwnProperty(string propertyName, PropertyDescriptor desc, bool throwOnError)
  86. {
  87. var oldLenDesc = _length;
  88. var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value);
  89. if (propertyName.Length == 6 && propertyName == "length")
  90. {
  91. var value = desc.Value;
  92. if (ReferenceEquals(value, null))
  93. {
  94. return base.DefineOwnProperty("length", desc, throwOnError);
  95. }
  96. var newLenDesc = new PropertyDescriptor(desc);
  97. uint newLen = TypeConverter.ToUint32(value);
  98. if (newLen != TypeConverter.ToNumber(value))
  99. {
  100. ExceptionHelper.ThrowRangeError(_engine);
  101. }
  102. newLenDesc.Value = newLen;
  103. if (newLen >= oldLen)
  104. {
  105. return base.DefineOwnProperty("length", newLenDesc, throwOnError);
  106. }
  107. if (!oldLenDesc.Writable)
  108. {
  109. if (throwOnError)
  110. {
  111. ExceptionHelper.ThrowTypeError(_engine);
  112. }
  113. return false;
  114. }
  115. bool newWritable;
  116. if (!newLenDesc.WritableSet || newLenDesc.Writable)
  117. {
  118. newWritable = true;
  119. }
  120. else
  121. {
  122. newWritable = false;
  123. newLenDesc.Writable = true;
  124. }
  125. var succeeded = base.DefineOwnProperty("length", newLenDesc, throwOnError);
  126. if (!succeeded)
  127. {
  128. return false;
  129. }
  130. var count = _dense?.Length ?? _sparse.Count;
  131. if (count < oldLen - newLen)
  132. {
  133. if (_dense != null)
  134. {
  135. for (uint keyIndex = 0; keyIndex < _dense.Length; ++keyIndex)
  136. {
  137. if (_dense[keyIndex] == null)
  138. {
  139. continue;
  140. }
  141. // is it the index of the array
  142. if (keyIndex >= newLen && keyIndex < oldLen)
  143. {
  144. var deleteSucceeded = DeleteAt(keyIndex);
  145. if (!deleteSucceeded)
  146. {
  147. newLenDesc.Value = keyIndex + 1;
  148. if (!newWritable)
  149. {
  150. newLenDesc.Writable = false;
  151. }
  152. base.DefineOwnProperty("length", newLenDesc, false);
  153. if (throwOnError)
  154. {
  155. ExceptionHelper.ThrowTypeError(_engine);
  156. }
  157. return false;
  158. }
  159. }
  160. }
  161. }
  162. else
  163. {
  164. // in the case of sparse arrays, treat each concrete element instead of
  165. // iterating over all indexes
  166. var keys = new List<uint>(_sparse.Keys);
  167. var keysCount = keys.Count;
  168. for (var i = 0; i < keysCount; i++)
  169. {
  170. var keyIndex = keys[i];
  171. // is it the index of the array
  172. if (keyIndex >= newLen && keyIndex < oldLen)
  173. {
  174. var deleteSucceeded = Delete(TypeConverter.ToString(keyIndex), false);
  175. if (!deleteSucceeded)
  176. {
  177. newLenDesc.Value = JsNumber.Create(keyIndex + 1);
  178. if (!newWritable)
  179. {
  180. newLenDesc.Writable = false;
  181. }
  182. base.DefineOwnProperty("length", newLenDesc, false);
  183. if (throwOnError)
  184. {
  185. ExceptionHelper.ThrowTypeError(_engine);
  186. }
  187. return false;
  188. }
  189. }
  190. }
  191. }
  192. }
  193. else
  194. {
  195. while (newLen < oldLen)
  196. {
  197. // algorithm as per the spec
  198. oldLen--;
  199. var deleteSucceeded = Delete(TypeConverter.ToString(oldLen), false);
  200. if (!deleteSucceeded)
  201. {
  202. newLenDesc.Value = oldLen + 1;
  203. if (!newWritable)
  204. {
  205. newLenDesc.Writable = false;
  206. }
  207. base.DefineOwnProperty("length", newLenDesc, false);
  208. if (throwOnError)
  209. {
  210. ExceptionHelper.ThrowTypeError(_engine);
  211. }
  212. return false;
  213. }
  214. }
  215. }
  216. if (!newWritable)
  217. {
  218. DefineOwnProperty("length", new PropertyDescriptor(value: null, PropertyFlag.WritableSet), false);
  219. }
  220. return true;
  221. }
  222. else if (IsArrayIndex(propertyName, out var index))
  223. {
  224. if (index >= oldLen && !oldLenDesc.Writable)
  225. {
  226. if (throwOnError)
  227. {
  228. ExceptionHelper.ThrowTypeError(_engine);
  229. }
  230. return false;
  231. }
  232. var succeeded = base.DefineOwnProperty(propertyName, desc, false);
  233. if (!succeeded)
  234. {
  235. if (throwOnError)
  236. {
  237. ExceptionHelper.ThrowTypeError(_engine);
  238. }
  239. return false;
  240. }
  241. if (index >= oldLen)
  242. {
  243. oldLenDesc.Value = index + 1;
  244. base.DefineOwnProperty("length", oldLenDesc, false);
  245. }
  246. return true;
  247. }
  248. return base.DefineOwnProperty(propertyName, desc, throwOnError);
  249. }
  250. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  251. public uint GetLength()
  252. {
  253. return (uint) ((JsNumber) _length._value)._value;
  254. }
  255. protected override void AddProperty(string propertyName, PropertyDescriptor descriptor)
  256. {
  257. if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  258. {
  259. _length = descriptor;
  260. return;
  261. }
  262. base.AddProperty(propertyName, descriptor);
  263. }
  264. protected override bool TryGetProperty(string propertyName, out PropertyDescriptor descriptor)
  265. {
  266. if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  267. {
  268. descriptor = _length;
  269. return _length != null;
  270. }
  271. return base.TryGetProperty(propertyName, out descriptor);
  272. }
  273. public override IEnumerable<KeyValuePair<string, PropertyDescriptor>> GetOwnProperties()
  274. {
  275. if (_length != null)
  276. {
  277. yield return new KeyValuePair<string, PropertyDescriptor>(PropertyNameLength, _length);
  278. }
  279. if (_dense != null)
  280. {
  281. var length = System.Math.Min(_dense.Length, GetLength());
  282. for (var i = 0; i < length; i++)
  283. {
  284. if (_dense[i] != null)
  285. {
  286. yield return new KeyValuePair<string, PropertyDescriptor>(TypeConverter.ToString(i), _dense[i]);
  287. }
  288. }
  289. }
  290. else
  291. {
  292. foreach (var entry in _sparse)
  293. {
  294. yield return new KeyValuePair<string, PropertyDescriptor>(TypeConverter.ToString(entry.Key), entry.Value);
  295. }
  296. }
  297. foreach (var entry in base.GetOwnProperties())
  298. {
  299. yield return entry;
  300. }
  301. }
  302. public override PropertyDescriptor GetOwnProperty(string propertyName)
  303. {
  304. if (IsArrayIndex(propertyName, out var index))
  305. {
  306. if (TryGetDescriptor(index, out var result))
  307. {
  308. return result;
  309. }
  310. return PropertyDescriptor.Undefined;
  311. }
  312. if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  313. {
  314. return _length ?? PropertyDescriptor.Undefined;
  315. }
  316. return base.GetOwnProperty(propertyName);
  317. }
  318. protected internal override void SetOwnProperty(string propertyName, PropertyDescriptor desc)
  319. {
  320. if (IsArrayIndex(propertyName, out var index))
  321. {
  322. WriteArrayValue(index, desc);
  323. }
  324. else if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  325. {
  326. _length = desc;
  327. }
  328. else
  329. {
  330. base.SetOwnProperty(propertyName, desc);
  331. }
  332. }
  333. public override bool HasOwnProperty(string p)
  334. {
  335. if (IsArrayIndex(p, out var index))
  336. {
  337. return index < GetLength()
  338. && (_sparse == null || _sparse.ContainsKey(index))
  339. && (_dense == null || (index < (uint) _dense.Length && _dense[index] != null));
  340. }
  341. if (p == PropertyNameLength)
  342. {
  343. return _length != null;
  344. }
  345. return base.HasOwnProperty(p);
  346. }
  347. public override void RemoveOwnProperty(string p)
  348. {
  349. if (IsArrayIndex(p, out var index))
  350. {
  351. DeleteAt(index);
  352. }
  353. if (p == PropertyNameLength)
  354. {
  355. _length = null;
  356. }
  357. base.RemoveOwnProperty(p);
  358. }
  359. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  360. private static bool IsArrayIndex(string p, out uint index)
  361. {
  362. index = ParseArrayIndex(p);
  363. return index != uint.MaxValue;
  364. // 15.4 - Use an optimized version of the specification
  365. // return TypeConverter.ToString(index) == TypeConverter.ToString(p) && index != uint.MaxValue;
  366. }
  367. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  368. private static uint ParseArrayIndex(string p)
  369. {
  370. int d = p[0] - '0';
  371. if (d < 0 || d > 9)
  372. {
  373. return uint.MaxValue;
  374. }
  375. if (d == 0 && p.Length > 1)
  376. {
  377. // If p is a number that start with '0' and is not '0' then
  378. // its ToString representation can't be the same a p. This is
  379. // not a valid array index. '01' !== ToString(ToUInt32('01'))
  380. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  381. return uint.MaxValue;
  382. }
  383. if (p.Length > 1)
  384. {
  385. return StringAsIndex(d, p);
  386. }
  387. return (uint) d;
  388. }
  389. private static uint StringAsIndex(int d, string p)
  390. {
  391. ulong result = (uint) d;
  392. for (int i = 1; i < p.Length; i++)
  393. {
  394. d = p[i] - '0';
  395. if (d < 0 || d > 9)
  396. {
  397. return uint.MaxValue;
  398. }
  399. result = result * 10 + (uint) d;
  400. if (result >= uint.MaxValue)
  401. {
  402. return uint.MaxValue;
  403. }
  404. }
  405. return (uint) result;
  406. }
  407. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  408. internal void SetIndexValue(uint index, JsValue value, bool updateLength)
  409. {
  410. if (updateLength)
  411. {
  412. var length = GetLength();
  413. if (index >= length)
  414. {
  415. SetLength(index + 1);
  416. }
  417. }
  418. WriteArrayValue(index, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable));
  419. }
  420. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  421. internal void SetLength(uint length)
  422. {
  423. _length.Value = length;
  424. }
  425. internal uint GetSmallestIndex()
  426. {
  427. if (_dense != null)
  428. {
  429. return 0;
  430. }
  431. uint smallest = 0;
  432. // only try to help if collection reasonable small
  433. if (_sparse.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0))
  434. {
  435. smallest = uint.MaxValue;
  436. foreach (var key in _sparse.Keys)
  437. {
  438. smallest = System.Math.Min(key, smallest);
  439. }
  440. }
  441. return smallest;
  442. }
  443. public bool TryGetValue(uint index, out JsValue value)
  444. {
  445. value = Undefined;
  446. TryGetDescriptor(index, out var desc);
  447. desc = desc ?? GetProperty(TypeConverter.ToString(index)) ?? PropertyDescriptor.Undefined;
  448. return desc.TryGetValue(this, out value);
  449. }
  450. internal bool DeleteAt(uint index)
  451. {
  452. if (_dense != null)
  453. {
  454. if (index < (uint) _dense.Length)
  455. {
  456. _dense[index] = null;
  457. return true;
  458. }
  459. }
  460. else
  461. {
  462. return _sparse.Remove(index);
  463. }
  464. return false;
  465. }
  466. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  467. private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor)
  468. {
  469. if (_dense != null)
  470. {
  471. descriptor = null;
  472. if (index < (uint) _dense.Length)
  473. {
  474. descriptor = _dense[index];
  475. }
  476. return descriptor != null;
  477. }
  478. return _sparse.TryGetValue(index, out descriptor);
  479. }
  480. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  481. internal void WriteArrayValue(uint index, PropertyDescriptor desc)
  482. {
  483. // calculate eagerly so we know if we outgrow
  484. var newSize = _dense != null && index >= (uint) _dense.Length
  485. ? System.Math.Max(index, System.Math.Max(_dense.Length, 2)) * 2
  486. : 0;
  487. bool canUseDense = _dense != null
  488. && index < MaxDenseArrayLength
  489. && newSize < MaxDenseArrayLength
  490. && index < _dense.Length + 50; // looks sparse
  491. if (canUseDense)
  492. {
  493. var temp = _dense;
  494. if (index >= (uint) temp.Length)
  495. {
  496. EnsureCapacity((uint) newSize);
  497. }
  498. _dense[index] = desc;
  499. }
  500. else
  501. {
  502. if (_dense != null)
  503. {
  504. ConvertToSparse();
  505. }
  506. _sparse[index] = desc;
  507. }
  508. }
  509. private void ConvertToSparse()
  510. {
  511. _sparse = new Dictionary<uint, PropertyDescriptor>(_dense.Length <= 1024 ? _dense.Length : 0);
  512. // need to move data
  513. for (uint i = 0; i < (uint) _dense.Length; ++i)
  514. {
  515. if (_dense[i] != null)
  516. {
  517. _sparse[i] = _dense[i];
  518. }
  519. }
  520. _dense = null;
  521. }
  522. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  523. internal void EnsureCapacity(uint capacity)
  524. {
  525. if (capacity > (uint) _dense.Length)
  526. {
  527. // need to grow
  528. var newArray = new PropertyDescriptor[capacity];
  529. System.Array.Copy(_dense, newArray, _dense.Length);
  530. _dense = newArray;
  531. }
  532. }
  533. public IEnumerator<JsValue> GetEnumerator()
  534. {
  535. var length = GetLength();
  536. for (uint i = 0; i < length; i++)
  537. {
  538. if (TryGetValue(i, out JsValue outValue))
  539. {
  540. yield return outValue;
  541. }
  542. };
  543. }
  544. IEnumerator IEnumerable.GetEnumerator()
  545. {
  546. return GetEnumerator();
  547. }
  548. internal uint Push(JsValue[] arguments)
  549. {
  550. var initialLength = GetLength();
  551. var newLength = initialLength + arguments.Length;
  552. // if we see that we are bringing more than normal growth algorithm handles, ensure capacity eagerly
  553. if (_dense != null
  554. && initialLength != 0
  555. && arguments.Length > initialLength * 2
  556. && newLength <= MaxDenseArrayLength)
  557. {
  558. EnsureCapacity((uint) newLength);
  559. }
  560. double n = initialLength;
  561. for (var i = 0; i < arguments.Length; i++)
  562. {
  563. var desc = new PropertyDescriptor(arguments[i], PropertyFlag.ConfigurableEnumerableWritable);
  564. if (_dense != null && n < _dense.Length)
  565. {
  566. _dense[(int) n] = desc;
  567. }
  568. else if (n < uint.MaxValue)
  569. {
  570. WriteArrayValue((uint) n, desc);
  571. }
  572. else
  573. {
  574. DefineOwnProperty(TypeConverter.ToString((uint) n), desc, true);
  575. }
  576. n++;
  577. }
  578. // check if we can set length fast without breaking ECMA specification
  579. if (n < uint.MaxValue && CanPut(PropertyNameLength))
  580. {
  581. _length.Value = (uint) n;
  582. }
  583. else
  584. {
  585. Put(PropertyNameLength, newLength, true);
  586. }
  587. return (uint) n;
  588. }
  589. internal ArrayInstance Map(JsValue[] arguments)
  590. {
  591. var callbackfn = arguments.At(0);
  592. var thisArg = arguments.At(1);
  593. var len = GetLength();
  594. var callable = GetCallable(callbackfn);
  595. var a = Engine.Array.ConstructFast(len);
  596. var args = _engine._jsValueArrayPool.RentArray(3);
  597. args[2] = this;
  598. for (uint k = 0; k < len; k++)
  599. {
  600. if (TryGetValue(k, out var kvalue))
  601. {
  602. args[0] = kvalue;
  603. args[1] = k;
  604. var mappedValue = callable.Call(thisArg, args);
  605. var desc = new PropertyDescriptor(mappedValue, PropertyFlag.ConfigurableEnumerableWritable);
  606. if (a._dense != null && k < (uint) a._dense.Length)
  607. {
  608. a._dense[k] = desc;
  609. }
  610. else
  611. {
  612. a.WriteArrayValue(k, desc);
  613. }
  614. }
  615. }
  616. _engine._jsValueArrayPool.ReturnArray(args);
  617. return a;
  618. }
  619. /// <inheritdoc />
  620. internal override bool FindWithCallback(
  621. JsValue[] arguments,
  622. out uint index,
  623. out JsValue value)
  624. {
  625. var len = GetLength();
  626. if (len == 0)
  627. {
  628. index = 0;
  629. value = Undefined;
  630. return false;
  631. }
  632. var callbackfn = arguments.At(0);
  633. var thisArg = arguments.At(1);
  634. var callable = GetCallable(callbackfn);
  635. var args = _engine._jsValueArrayPool.RentArray(3);
  636. args[2] = this;
  637. for (uint k = 0; k < len; k++)
  638. {
  639. if (TryGetValue(k, out var kvalue))
  640. {
  641. args[0] = kvalue;
  642. args[1] = k;
  643. var testResult = callable.Call(thisArg, args);
  644. if (TypeConverter.ToBoolean(testResult))
  645. {
  646. index = k;
  647. value = kvalue;
  648. return true;
  649. }
  650. }
  651. }
  652. _engine._jsValueArrayPool.ReturnArray(args);
  653. index = 0;
  654. value = Undefined;
  655. return false;
  656. }
  657. }
  658. }