ArrayInstance.cs 25 KB

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