ArrayInstance.cs 24 KB

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