ArrayInstance.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 override string Class => "Array";
  34. /// Implementation from ObjectInstance official specs as the one
  35. /// in ObjectInstance is optimized for the general case and wouldn't work
  36. /// for arrays
  37. public override void Put(string propertyName, JsValue value, bool throwOnError)
  38. {
  39. if (!CanPut(propertyName))
  40. {
  41. if (throwOnError)
  42. {
  43. throw new JavaScriptException(Engine.TypeError);
  44. }
  45. return;
  46. }
  47. var ownDesc = GetOwnProperty(propertyName);
  48. if (ownDesc.IsDataDescriptor())
  49. {
  50. var valueDesc = new PropertyDescriptor(value, PropertyFlag.None);
  51. DefineOwnProperty(propertyName, valueDesc, throwOnError);
  52. return;
  53. }
  54. // property is an accessor or inherited
  55. var desc = GetProperty(propertyName);
  56. if (desc.IsAccessorDescriptor())
  57. {
  58. var setter = desc.Set.TryCast<ICallable>();
  59. setter.Call(this, new[] {value});
  60. }
  61. else
  62. {
  63. var newDesc = new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable);
  64. DefineOwnProperty(propertyName, newDesc, throwOnError);
  65. }
  66. }
  67. public override bool DefineOwnProperty(string propertyName, PropertyDescriptor desc, bool throwOnError)
  68. {
  69. var oldLenDesc = _length;
  70. var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value);
  71. if (propertyName.Length == 6 && propertyName == "length")
  72. {
  73. if (desc.Value == null)
  74. {
  75. return base.DefineOwnProperty("length", desc, throwOnError);
  76. }
  77. var newLenDesc = new PropertyDescriptor(desc);
  78. uint newLen = TypeConverter.ToUint32(desc.Value);
  79. if (newLen != TypeConverter.ToNumber(desc.Value))
  80. {
  81. throw new JavaScriptException(_engine.RangeError);
  82. }
  83. newLenDesc.Value = newLen;
  84. if (newLen >= oldLen)
  85. {
  86. return base.DefineOwnProperty("length", newLenDesc, throwOnError);
  87. }
  88. if (!oldLenDesc.Writable)
  89. {
  90. if (throwOnError)
  91. {
  92. throw new JavaScriptException(_engine.TypeError);
  93. }
  94. return false;
  95. }
  96. bool newWritable;
  97. if (!newLenDesc.WritableSet || newLenDesc.Writable)
  98. {
  99. newWritable = true;
  100. }
  101. else
  102. {
  103. newWritable = false;
  104. newLenDesc.Writable = true;
  105. }
  106. var succeeded = base.DefineOwnProperty("length", newLenDesc, throwOnError);
  107. if (!succeeded)
  108. {
  109. return false;
  110. }
  111. var count = _dense?.Length ?? _sparse.Count;
  112. if (count < oldLen - newLen)
  113. {
  114. if (_dense != null)
  115. {
  116. for (uint keyIndex = 0; keyIndex < _dense.Length; ++keyIndex)
  117. {
  118. if (_dense[keyIndex] == null)
  119. {
  120. continue;
  121. }
  122. // is it the index of the array
  123. if (keyIndex >= newLen && keyIndex < oldLen)
  124. {
  125. var deleteSucceeded = DeleteAt(keyIndex);
  126. if (!deleteSucceeded)
  127. {
  128. newLenDesc.Value = keyIndex + 1;
  129. if (!newWritable)
  130. {
  131. newLenDesc.Writable = false;
  132. }
  133. base.DefineOwnProperty("length", newLenDesc, false);
  134. if (throwOnError)
  135. {
  136. throw new JavaScriptException(_engine.TypeError);
  137. }
  138. return false;
  139. }
  140. }
  141. }
  142. }
  143. else
  144. {
  145. // in the case of sparse arrays, treat each concrete element instead of
  146. // iterating over all indexes
  147. var keys = new List<uint>(_sparse.Keys);
  148. var keysCount = keys.Count;
  149. for (var i = 0; i < keysCount; i++)
  150. {
  151. var keyIndex = keys[i];
  152. // is it the index of the array
  153. if (keyIndex >= newLen && keyIndex < oldLen)
  154. {
  155. var deleteSucceeded = Delete(TypeConverter.ToString(keyIndex), false);
  156. if (!deleteSucceeded)
  157. {
  158. newLenDesc.Value = JsNumber.Create(keyIndex + 1);
  159. if (!newWritable)
  160. {
  161. newLenDesc.Writable = false;
  162. }
  163. base.DefineOwnProperty("length", newLenDesc, false);
  164. if (throwOnError)
  165. {
  166. throw new JavaScriptException(_engine.TypeError);
  167. }
  168. return false;
  169. }
  170. }
  171. }
  172. }
  173. }
  174. else
  175. {
  176. while (newLen < oldLen)
  177. {
  178. // algorithm as per the spec
  179. oldLen--;
  180. var deleteSucceeded = Delete(TypeConverter.ToString(oldLen), false);
  181. if (!deleteSucceeded)
  182. {
  183. newLenDesc.Value = oldLen + 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. if (!newWritable)
  198. {
  199. DefineOwnProperty("length", new PropertyDescriptor(value: null, writable: false, enumerable: null, configurable: null), false);
  200. }
  201. return true;
  202. }
  203. else if (IsArrayIndex(propertyName, out var index))
  204. {
  205. if (index >= oldLen && !oldLenDesc.Writable)
  206. {
  207. if (throwOnError)
  208. {
  209. throw new JavaScriptException(_engine.TypeError);
  210. }
  211. return false;
  212. }
  213. var succeeded = base.DefineOwnProperty(propertyName, desc, false);
  214. if (!succeeded)
  215. {
  216. if (throwOnError)
  217. {
  218. throw new JavaScriptException(_engine.TypeError);
  219. }
  220. return false;
  221. }
  222. if (index >= oldLen)
  223. {
  224. oldLenDesc.Value = index + 1;
  225. base.DefineOwnProperty("length", oldLenDesc, false);
  226. }
  227. return true;
  228. }
  229. return base.DefineOwnProperty(propertyName, desc, throwOnError);
  230. }
  231. public uint GetLength()
  232. {
  233. return (uint) ((JsNumber) _length.Value)._value;
  234. }
  235. protected override void AddProperty(string propertyName, PropertyDescriptor descriptor)
  236. {
  237. if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  238. {
  239. _length = descriptor;
  240. return;
  241. }
  242. base.AddProperty(propertyName, descriptor);
  243. }
  244. protected override bool TryGetProperty(string propertyName, out PropertyDescriptor descriptor)
  245. {
  246. if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  247. {
  248. descriptor = _length;
  249. return _length != null;
  250. }
  251. return base.TryGetProperty(propertyName, out descriptor);
  252. }
  253. public override IEnumerable<KeyValuePair<string, PropertyDescriptor>> GetOwnProperties()
  254. {
  255. if (_length != null)
  256. {
  257. yield return new KeyValuePair<string, PropertyDescriptor>(PropertyNameLength, _length);
  258. }
  259. if (_dense != null)
  260. {
  261. var length = System.Math.Min(_dense.Length, GetLength());
  262. for (var i = 0; i < length; i++)
  263. {
  264. if (_dense[i] != null)
  265. {
  266. yield return new KeyValuePair<string, PropertyDescriptor>(TypeConverter.ToString(i), _dense[i]);
  267. }
  268. }
  269. }
  270. else
  271. {
  272. foreach (var entry in _sparse)
  273. {
  274. yield return new KeyValuePair<string, PropertyDescriptor>(TypeConverter.ToString(entry.Key), entry.Value);
  275. }
  276. }
  277. foreach (var entry in base.GetOwnProperties())
  278. {
  279. yield return entry;
  280. }
  281. }
  282. public override PropertyDescriptor GetOwnProperty(string propertyName)
  283. {
  284. if (IsArrayIndex(propertyName, out var index))
  285. {
  286. if (TryGetDescriptor(index, out var result))
  287. {
  288. return result;
  289. }
  290. return PropertyDescriptor.Undefined;
  291. }
  292. if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  293. {
  294. return _length ?? PropertyDescriptor.Undefined;
  295. }
  296. return base.GetOwnProperty(propertyName);
  297. }
  298. protected internal override void SetOwnProperty(string propertyName, PropertyDescriptor desc)
  299. {
  300. if (IsArrayIndex(propertyName, out var index))
  301. {
  302. WriteArrayValue(index, desc);
  303. }
  304. else if (propertyName.Length == PropertyNameLengthLength && propertyName == PropertyNameLength)
  305. {
  306. _length = desc;
  307. }
  308. else
  309. {
  310. base.SetOwnProperty(propertyName, desc);
  311. }
  312. }
  313. public override bool HasOwnProperty(string p)
  314. {
  315. if (IsArrayIndex(p, out var index))
  316. {
  317. return index < GetLength()
  318. && (_sparse == null || _sparse.ContainsKey(index))
  319. && (_dense == null || (index < _dense.Length && _dense[index] != null));
  320. }
  321. if (p == PropertyNameLength)
  322. {
  323. return _length != null;
  324. }
  325. return base.HasOwnProperty(p);
  326. }
  327. public override void RemoveOwnProperty(string p)
  328. {
  329. if (IsArrayIndex(p, out var index))
  330. {
  331. DeleteAt(index);
  332. }
  333. if (p == PropertyNameLength)
  334. {
  335. _length = null;
  336. }
  337. base.RemoveOwnProperty(p);
  338. }
  339. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  340. private static bool IsArrayIndex(string p, out uint index)
  341. {
  342. index = ParseArrayIndex(p);
  343. return index != uint.MaxValue;
  344. // 15.4 - Use an optimized version of the specification
  345. // return TypeConverter.ToString(index) == TypeConverter.ToString(p) && index != uint.MaxValue;
  346. }
  347. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  348. private static uint ParseArrayIndex(string p)
  349. {
  350. int d = p[0] - '0';
  351. if (d < 0 || d > 9)
  352. {
  353. return uint.MaxValue;
  354. }
  355. if (d == 0 && p.Length > 1)
  356. {
  357. // If p is a number that start with '0' and is not '0' then
  358. // its ToString representation can't be the same a p. This is
  359. // not a valid array index. '01' !== ToString(ToUInt32('01'))
  360. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  361. return uint.MaxValue;
  362. }
  363. ulong result = (uint) d;
  364. for (int i = 1; i < p.Length; i++)
  365. {
  366. d = p[i] - '0';
  367. if (d < 0 || d > 9)
  368. {
  369. return uint.MaxValue;
  370. }
  371. result = result * 10 + (uint) d;
  372. if (result >= uint.MaxValue)
  373. {
  374. return uint.MaxValue;
  375. }
  376. }
  377. return (uint) result;
  378. }
  379. internal void SetIndexValue(uint index, JsValue value, bool throwOnError)
  380. {
  381. var length = GetLength();
  382. if (index >= length)
  383. {
  384. _length.Value = index + 1;
  385. }
  386. WriteArrayValue(index, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable));
  387. }
  388. internal uint GetSmallestIndex()
  389. {
  390. if (_dense != null)
  391. {
  392. return 0;
  393. }
  394. uint smallest = 0;
  395. // only try to help if collection reasonable small
  396. if (_sparse.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0))
  397. {
  398. smallest = uint.MaxValue;
  399. foreach (var key in _sparse.Keys)
  400. {
  401. smallest = System.Math.Min(key, smallest);
  402. }
  403. }
  404. return smallest;
  405. }
  406. public bool TryGetValue(uint index, out JsValue value)
  407. {
  408. value = Undefined;
  409. if (!TryGetDescriptor(index, out var desc)
  410. || desc == null
  411. || desc == PropertyDescriptor.Undefined
  412. || (desc.Value == null && desc.Get == null))
  413. {
  414. desc = GetProperty(TypeConverter.ToString(index));
  415. }
  416. if (desc != null && desc != PropertyDescriptor.Undefined)
  417. {
  418. bool success = desc.TryGetValue(this, out value);
  419. return success;
  420. }
  421. return false;
  422. }
  423. internal bool DeleteAt(uint index)
  424. {
  425. if (_dense != null)
  426. {
  427. if (index < _dense.Length)
  428. {
  429. _dense[index] = null;
  430. return true;
  431. }
  432. }
  433. else
  434. {
  435. return _sparse.Remove(index);
  436. }
  437. return false;
  438. }
  439. private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor)
  440. {
  441. if (_dense != null)
  442. {
  443. if (index >= _dense.Length)
  444. {
  445. descriptor = null;
  446. return false;
  447. }
  448. descriptor = _dense[index];
  449. return descriptor != null;
  450. }
  451. return _sparse.TryGetValue(index, out descriptor);
  452. }
  453. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  454. internal void WriteArrayValue(uint index, PropertyDescriptor desc)
  455. {
  456. // calculate eagerly so we know if we outgrow
  457. var newSize = _dense != null && index >= _dense.Length
  458. ? System.Math.Max(index, System.Math.Max(_dense.Length, 2)) * 2
  459. : 0;
  460. bool canUseDense = _dense != null
  461. && index < MaxDenseArrayLength
  462. && newSize < MaxDenseArrayLength
  463. && index < _dense.Length + 50; // looks sparse
  464. if (canUseDense)
  465. {
  466. if (index >= _dense.Length)
  467. {
  468. EnsureCapacity((uint) newSize);
  469. }
  470. _dense[index] = desc;
  471. }
  472. else
  473. {
  474. if (_dense != null)
  475. {
  476. ConvertToSparse();
  477. }
  478. _sparse[index] = desc;
  479. }
  480. }
  481. private void ConvertToSparse()
  482. {
  483. _sparse = new Dictionary<uint, PropertyDescriptor>(_dense.Length <= 1024 ? _dense.Length : 0);
  484. // need to move data
  485. for (uint i = 0; i < _dense.Length; ++i)
  486. {
  487. if (_dense[i] != null)
  488. {
  489. _sparse[i] = _dense[i];
  490. }
  491. }
  492. _dense = null;
  493. }
  494. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  495. internal void EnsureCapacity(uint capacity)
  496. {
  497. if (capacity > _dense.Length)
  498. {
  499. // need to grow
  500. var newArray = new PropertyDescriptor[capacity];
  501. System.Array.Copy(_dense, newArray, _dense.Length);
  502. _dense = newArray;
  503. }
  504. }
  505. public IEnumerator<JsValue> GetEnumerator()
  506. {
  507. for (uint i = 0; i < GetLength(); i++)
  508. {
  509. if (TryGetValue(i, out JsValue outValue))
  510. {
  511. yield return outValue;
  512. }
  513. };
  514. }
  515. IEnumerator IEnumerable.GetEnumerator()
  516. {
  517. return GetEnumerator();
  518. }
  519. }
  520. }