ArrayInstance.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. private 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. throw new JavaScriptException(Engine.TypeError);
  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. throw new JavaScriptException(_engine.RangeError);
  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. throw new JavaScriptException(_engine.TypeError);
  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. throw new JavaScriptException(_engine.TypeError);
  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. throw new JavaScriptException(_engine.TypeError);
  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. throw new JavaScriptException(_engine.TypeError);
  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. throw new JavaScriptException(_engine.TypeError);
  229. }
  230. return false;
  231. }
  232. var succeeded = base.DefineOwnProperty(propertyName, desc, false);
  233. if (!succeeded)
  234. {
  235. if (throwOnError)
  236. {
  237. throw new JavaScriptException(_engine.TypeError);
  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 < _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. if (!TryGetDescriptor(index, out var desc)
  447. || desc == null
  448. || desc == PropertyDescriptor.Undefined
  449. || (ReferenceEquals(desc.Value, null) && ReferenceEquals(desc.Get, null)))
  450. {
  451. desc = GetProperty(TypeConverter.ToString(index));
  452. }
  453. if (desc != null && desc != PropertyDescriptor.Undefined)
  454. {
  455. bool success = desc.TryGetValue(this, out value);
  456. return success;
  457. }
  458. return false;
  459. }
  460. internal bool DeleteAt(uint index)
  461. {
  462. if (_dense != null)
  463. {
  464. if (index < _dense.Length)
  465. {
  466. _dense[index] = null;
  467. return true;
  468. }
  469. }
  470. else
  471. {
  472. return _sparse.Remove(index);
  473. }
  474. return false;
  475. }
  476. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  477. private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor)
  478. {
  479. if (_dense != null)
  480. {
  481. if (index >= _dense.Length)
  482. {
  483. descriptor = null;
  484. return false;
  485. }
  486. descriptor = _dense[index];
  487. return descriptor != null;
  488. }
  489. return _sparse.TryGetValue(index, out descriptor);
  490. }
  491. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  492. internal void WriteArrayValue(uint index, PropertyDescriptor desc)
  493. {
  494. // calculate eagerly so we know if we outgrow
  495. var newSize = _dense != null && index >= _dense.Length
  496. ? System.Math.Max(index, System.Math.Max(_dense.Length, 2)) * 2
  497. : 0;
  498. bool canUseDense = _dense != null
  499. && index < MaxDenseArrayLength
  500. && newSize < MaxDenseArrayLength
  501. && index < _dense.Length + 50; // looks sparse
  502. if (canUseDense)
  503. {
  504. if (index >= _dense.Length)
  505. {
  506. EnsureCapacity((uint) newSize);
  507. }
  508. _dense[index] = desc;
  509. }
  510. else
  511. {
  512. if (_dense != null)
  513. {
  514. ConvertToSparse();
  515. }
  516. _sparse[index] = desc;
  517. }
  518. }
  519. private void ConvertToSparse()
  520. {
  521. _sparse = new Dictionary<uint, PropertyDescriptor>(_dense.Length <= 1024 ? _dense.Length : 0);
  522. // need to move data
  523. for (uint i = 0; i < _dense.Length; ++i)
  524. {
  525. if (_dense[i] != null)
  526. {
  527. _sparse[i] = _dense[i];
  528. }
  529. }
  530. _dense = null;
  531. }
  532. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  533. internal void EnsureCapacity(uint capacity)
  534. {
  535. if (capacity > _dense.Length)
  536. {
  537. // need to grow
  538. var newArray = new PropertyDescriptor[capacity];
  539. System.Array.Copy(_dense, newArray, _dense.Length);
  540. _dense = newArray;
  541. }
  542. }
  543. public IEnumerator<JsValue> GetEnumerator()
  544. {
  545. var length = GetLength();
  546. for (uint i = 0; i < length; i++)
  547. {
  548. if (TryGetValue(i, out JsValue outValue))
  549. {
  550. yield return outValue;
  551. }
  552. };
  553. }
  554. IEnumerator IEnumerable.GetEnumerator()
  555. {
  556. return GetEnumerator();
  557. }
  558. internal uint Push(JsValue[] arguments)
  559. {
  560. var initialLength = GetLength();
  561. var newLength = initialLength + arguments.Length;
  562. // if we see that we are bringing more than normal growth algorithm handles, ensure capacity eagerly
  563. if (_dense != null
  564. && initialLength != 0
  565. && arguments.Length > initialLength * 2
  566. && newLength <= MaxDenseArrayLength)
  567. {
  568. EnsureCapacity((uint) newLength);
  569. }
  570. double n = initialLength;
  571. for (var i = 0; i < arguments.Length; i++)
  572. {
  573. var desc = new PropertyDescriptor(arguments[i], PropertyFlag.ConfigurableEnumerableWritable);
  574. if (_dense != null && n < _dense.Length)
  575. {
  576. _dense[(int) n] = desc;
  577. }
  578. else if (n < uint.MaxValue)
  579. {
  580. WriteArrayValue((uint) n, desc);
  581. }
  582. else
  583. {
  584. DefineOwnProperty(TypeConverter.ToString(n), desc, true);
  585. }
  586. n++;
  587. }
  588. // check if we can set length fast without breaking ECMA specification
  589. if (n < uint.MaxValue && CanPut(PropertyNameLength))
  590. {
  591. _length.Value = (uint) n;
  592. }
  593. else
  594. {
  595. Put(PropertyNameLength, newLength, true);
  596. }
  597. return (uint) n;
  598. }
  599. internal ArrayInstance Map(JsValue[] arguments)
  600. {
  601. var callbackfn = arguments.At(0);
  602. var thisArg = arguments.At(1);
  603. var len = GetLength();
  604. var callable = GetCallable(callbackfn);
  605. var a = Engine.Array.ConstructFast(len);
  606. var args = Engine.JsValueArrayPool.RentArray(3);
  607. for (uint k = 0; k < len; k++)
  608. {
  609. if (TryGetValue(k, out var kvalue))
  610. {
  611. args[0] = kvalue;
  612. args[1] = k;
  613. args[2] = this;
  614. var mappedValue = callable.Call(thisArg, args);
  615. var desc = new PropertyDescriptor(mappedValue, PropertyFlag.ConfigurableEnumerableWritable);
  616. if (a._dense != null && k < a._dense.Length)
  617. {
  618. a._dense[k] = desc;
  619. }
  620. else
  621. {
  622. a.WriteArrayValue(k, desc);
  623. }
  624. }
  625. }
  626. Engine.JsValueArrayPool.ReturnArray(args);
  627. return a;
  628. }
  629. /// <inheritdoc />
  630. internal override bool FindWithCallback(
  631. JsValue[] arguments,
  632. out uint index,
  633. out JsValue value)
  634. {
  635. var len = GetLength();
  636. if (len == 0)
  637. {
  638. index = 0;
  639. value = Undefined;
  640. return false;
  641. }
  642. var callbackfn = arguments.At(0);
  643. var thisArg = arguments.At(1);
  644. var callable = GetCallable(callbackfn);
  645. var args = Engine.JsValueArrayPool.RentArray(3);
  646. for (uint k = 0; k < len; k++)
  647. {
  648. if (TryGetValue(k, out var kvalue))
  649. {
  650. args[0] = kvalue;
  651. args[1] = k;
  652. args[2] = this;
  653. var testResult = callable.Call(thisArg, args);
  654. if (TypeConverter.ToBoolean(testResult))
  655. {
  656. index = k;
  657. value = kvalue;
  658. return true;
  659. }
  660. }
  661. }
  662. Engine.JsValueArrayPool.ReturnArray(args);
  663. index = 0;
  664. value = Undefined;
  665. return false;
  666. }
  667. }
  668. }