ArrayInstance.cs 20 KB

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