ArrayInstance.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.CompilerServices;
  5. using Jint.Native.Object;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Descriptors;
  8. using PropertyDescriptor = Jint.Runtime.Descriptors.PropertyDescriptor;
  9. using TypeConverter = Jint.Runtime.TypeConverter;
  10. namespace Jint.Native.Array
  11. {
  12. public class ArrayInstance : ObjectInstance, IEnumerable<JsValue>
  13. {
  14. private readonly Engine _engine;
  15. private const string PropertyNameLength = "length";
  16. private const int PropertyNameLengthLength = 6;
  17. private PropertyDescriptor _length;
  18. private const int MaxDenseArrayLength = 1024 * 10;
  19. // we have dense and sparse, we usually can start with dense and fall back to sparse when necessary
  20. private PropertyDescriptor[] _dense;
  21. private Dictionary<uint, PropertyDescriptor> _sparse;
  22. public ArrayInstance(Engine engine, uint capacity = 0) : base(engine)
  23. {
  24. _engine = engine;
  25. if (capacity < MaxDenseArrayLength)
  26. {
  27. _dense = capacity > 0 ? new PropertyDescriptor[capacity] : System.Array.Empty<PropertyDescriptor>();
  28. }
  29. else
  30. {
  31. _sparse = new Dictionary<uint, PropertyDescriptor>((int) (capacity <= 1024 ? capacity : 1024));
  32. }
  33. }
  34. public ArrayInstance(Engine engine, PropertyDescriptor[] items) : base(engine)
  35. {
  36. _engine = engine;
  37. int length = 0;
  38. if (items == null || items.Length == 0)
  39. {
  40. _dense = System.Array.Empty<PropertyDescriptor>();
  41. length = 0;
  42. }
  43. else
  44. {
  45. _dense = items;
  46. length = items.Length;
  47. }
  48. SetOwnProperty(PropertyNameLength, new PropertyDescriptor(length, PropertyFlag.OnlyWritable));
  49. }
  50. public ArrayInstance(Engine engine, Dictionary<uint, PropertyDescriptor> items) : base(engine)
  51. {
  52. _engine = engine;
  53. _sparse = items;
  54. var length = items?.Count ?? 0;
  55. SetOwnProperty(PropertyNameLength, new PropertyDescriptor(length, PropertyFlag.OnlyWritable));
  56. }
  57. public override string Class => "Array";
  58. /// Implementation from ObjectInstance official specs as the one
  59. /// in ObjectInstance is optimized for the general case and wouldn't work
  60. /// for arrays
  61. public override void Put(string propertyName, JsValue value, bool throwOnError)
  62. {
  63. if (!CanPut(propertyName))
  64. {
  65. if (throwOnError)
  66. {
  67. throw new JavaScriptException(Engine.TypeError);
  68. }
  69. return;
  70. }
  71. var ownDesc = GetOwnProperty(propertyName);
  72. if (ownDesc.IsDataDescriptor())
  73. {
  74. var valueDesc = new PropertyDescriptor(value, PropertyFlag.None);
  75. DefineOwnProperty(propertyName, valueDesc, throwOnError);
  76. return;
  77. }
  78. // property is an accessor or inherited
  79. var desc = GetProperty(propertyName);
  80. if (desc.IsAccessorDescriptor())
  81. {
  82. var setter = desc.Set.TryCast<ICallable>();
  83. setter.Call(this, new[] {value});
  84. }
  85. else
  86. {
  87. var newDesc = new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable);
  88. DefineOwnProperty(propertyName, newDesc, throwOnError);
  89. }
  90. }
  91. public override bool DefineOwnProperty(string propertyName, PropertyDescriptor desc, bool throwOnError)
  92. {
  93. var oldLenDesc = _length;
  94. var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value);
  95. if (propertyName.Length == 6 && propertyName == "length")
  96. {
  97. var value = desc.Value;
  98. if (ReferenceEquals(value, null))
  99. {
  100. return base.DefineOwnProperty("length", desc, throwOnError);
  101. }
  102. var newLenDesc = new PropertyDescriptor(desc);
  103. uint newLen = TypeConverter.ToUint32(value);
  104. if (newLen != TypeConverter.ToNumber(value))
  105. {
  106. throw new JavaScriptException(_engine.RangeError);
  107. }
  108. newLenDesc.Value = newLen;
  109. if (newLen >= oldLen)
  110. {
  111. return base.DefineOwnProperty("length", newLenDesc, throwOnError);
  112. }
  113. if (!oldLenDesc.Writable)
  114. {
  115. if (throwOnError)
  116. {
  117. throw new JavaScriptException(_engine.TypeError);
  118. }
  119. return false;
  120. }
  121. bool newWritable;
  122. if (!newLenDesc.WritableSet || newLenDesc.Writable)
  123. {
  124. newWritable = true;
  125. }
  126. else
  127. {
  128. newWritable = false;
  129. newLenDesc.Writable = true;
  130. }
  131. var succeeded = base.DefineOwnProperty("length", newLenDesc, throwOnError);
  132. if (!succeeded)
  133. {
  134. return false;
  135. }
  136. var count = _dense?.Length ?? _sparse.Count;
  137. if (count < oldLen - newLen)
  138. {
  139. if (_dense != null)
  140. {
  141. for (uint keyIndex = 0; keyIndex < _dense.Length; ++keyIndex)
  142. {
  143. if (_dense[keyIndex] == null)
  144. {
  145. continue;
  146. }
  147. // is it the index of the array
  148. if (keyIndex >= newLen && keyIndex < oldLen)
  149. {
  150. var deleteSucceeded = DeleteAt(keyIndex);
  151. if (!deleteSucceeded)
  152. {
  153. newLenDesc.Value = keyIndex + 1;
  154. if (!newWritable)
  155. {
  156. newLenDesc.Writable = false;
  157. }
  158. base.DefineOwnProperty("length", newLenDesc, false);
  159. if (throwOnError)
  160. {
  161. throw new JavaScriptException(_engine.TypeError);
  162. }
  163. return false;
  164. }
  165. }
  166. }
  167. }
  168. else
  169. {
  170. // in the case of sparse arrays, treat each concrete element instead of
  171. // iterating over all indexes
  172. var keys = new List<uint>(_sparse.Keys);
  173. var keysCount = keys.Count;
  174. for (var i = 0; i < keysCount; i++)
  175. {
  176. var keyIndex = keys[i];
  177. // is it the index of the array
  178. if (keyIndex >= newLen && keyIndex < oldLen)
  179. {
  180. var deleteSucceeded = Delete(TypeConverter.ToString(keyIndex), false);
  181. if (!deleteSucceeded)
  182. {
  183. newLenDesc.Value = JsNumber.Create(keyIndex + 1);
  184. if (!newWritable)
  185. {
  186. newLenDesc.Writable = false;
  187. }
  188. base.DefineOwnProperty("length", newLenDesc, false);
  189. if (throwOnError)
  190. {
  191. throw new JavaScriptException(_engine.TypeError);
  192. }
  193. return false;
  194. }
  195. }
  196. }
  197. }
  198. }
  199. else
  200. {
  201. while (newLen < oldLen)
  202. {
  203. // algorithm as per the spec
  204. oldLen--;
  205. var deleteSucceeded = Delete(TypeConverter.ToString(oldLen), false);
  206. if (!deleteSucceeded)
  207. {
  208. newLenDesc.Value = oldLen + 1;
  209. if (!newWritable)
  210. {
  211. newLenDesc.Writable = false;
  212. }
  213. base.DefineOwnProperty("length", newLenDesc, false);
  214. if (throwOnError)
  215. {
  216. throw new JavaScriptException(_engine.TypeError);
  217. }
  218. return false;
  219. }
  220. }
  221. }
  222. if (!newWritable)
  223. {
  224. DefineOwnProperty("length", new PropertyDescriptor(value: null, PropertyFlag.WritableSet), false);
  225. }
  226. return true;
  227. }
  228. else if (IsArrayIndex(propertyName, out var index))
  229. {
  230. if (index >= oldLen && !oldLenDesc.Writable)
  231. {
  232. if (throwOnError)
  233. {
  234. throw new JavaScriptException(_engine.TypeError);
  235. }
  236. return false;
  237. }
  238. var succeeded = base.DefineOwnProperty(propertyName, desc, false);
  239. if (!succeeded)
  240. {
  241. if (throwOnError)
  242. {
  243. throw new JavaScriptException(_engine.TypeError);
  244. }
  245. return false;
  246. }
  247. if (index >= oldLen)
  248. {
  249. oldLenDesc.Value = index + 1;
  250. base.DefineOwnProperty("length", oldLenDesc, false);
  251. }
  252. return true;
  253. }
  254. return base.DefineOwnProperty(propertyName, desc, throwOnError);
  255. }
  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. internal void SetIndexValue(uint index, JsValue value, bool throwOnError)
  405. {
  406. var length = GetLength();
  407. if (index >= length)
  408. {
  409. _length.Value = index + 1;
  410. }
  411. WriteArrayValue(index, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable));
  412. }
  413. internal uint GetSmallestIndex()
  414. {
  415. if (_dense != null)
  416. {
  417. return 0;
  418. }
  419. uint smallest = 0;
  420. // only try to help if collection reasonable small
  421. if (_sparse.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0))
  422. {
  423. smallest = uint.MaxValue;
  424. foreach (var key in _sparse.Keys)
  425. {
  426. smallest = System.Math.Min(key, smallest);
  427. }
  428. }
  429. return smallest;
  430. }
  431. public bool TryGetValue(uint index, out JsValue value)
  432. {
  433. value = Undefined;
  434. if (!TryGetDescriptor(index, out var desc)
  435. || desc == null
  436. || desc == PropertyDescriptor.Undefined
  437. || (ReferenceEquals(desc.Value, null) && ReferenceEquals(desc.Get, null)))
  438. {
  439. desc = GetProperty(TypeConverter.ToString(index));
  440. }
  441. if (desc != null && desc != PropertyDescriptor.Undefined)
  442. {
  443. bool success = desc.TryGetValue(this, out value);
  444. return success;
  445. }
  446. return false;
  447. }
  448. internal bool DeleteAt(uint index)
  449. {
  450. if (_dense != null)
  451. {
  452. if (index < _dense.Length)
  453. {
  454. _dense[index] = null;
  455. return true;
  456. }
  457. }
  458. else
  459. {
  460. return _sparse.Remove(index);
  461. }
  462. return false;
  463. }
  464. private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor)
  465. {
  466. if (_dense != null)
  467. {
  468. if (index >= _dense.Length)
  469. {
  470. descriptor = null;
  471. return false;
  472. }
  473. descriptor = _dense[index];
  474. return descriptor != null;
  475. }
  476. return _sparse.TryGetValue(index, out descriptor);
  477. }
  478. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  479. internal void WriteArrayValue(uint index, PropertyDescriptor desc)
  480. {
  481. // calculate eagerly so we know if we outgrow
  482. var newSize = _dense != null && index >= _dense.Length
  483. ? System.Math.Max(index, System.Math.Max(_dense.Length, 2)) * 2
  484. : 0;
  485. bool canUseDense = _dense != null
  486. && index < MaxDenseArrayLength
  487. && newSize < MaxDenseArrayLength
  488. && index < _dense.Length + 50; // looks sparse
  489. if (canUseDense)
  490. {
  491. if (index >= _dense.Length)
  492. {
  493. EnsureCapacity((uint) newSize);
  494. }
  495. _dense[index] = desc;
  496. }
  497. else
  498. {
  499. if (_dense != null)
  500. {
  501. ConvertToSparse();
  502. }
  503. _sparse[index] = desc;
  504. }
  505. }
  506. private void ConvertToSparse()
  507. {
  508. _sparse = new Dictionary<uint, PropertyDescriptor>(_dense.Length <= 1024 ? _dense.Length : 0);
  509. // need to move data
  510. for (uint i = 0; i < _dense.Length; ++i)
  511. {
  512. if (_dense[i] != null)
  513. {
  514. _sparse[i] = _dense[i];
  515. }
  516. }
  517. _dense = null;
  518. }
  519. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  520. internal void EnsureCapacity(uint capacity)
  521. {
  522. if (capacity > _dense.Length)
  523. {
  524. // need to grow
  525. var newArray = new PropertyDescriptor[capacity];
  526. System.Array.Copy(_dense, newArray, _dense.Length);
  527. _dense = newArray;
  528. }
  529. }
  530. public IEnumerator<JsValue> GetEnumerator()
  531. {
  532. for (uint i = 0; i < GetLength(); i++)
  533. {
  534. if (TryGetValue(i, out JsValue outValue))
  535. {
  536. yield return outValue;
  537. }
  538. };
  539. }
  540. IEnumerator IEnumerable.GetEnumerator()
  541. {
  542. return GetEnumerator();
  543. }
  544. }
  545. }