ArrayInstance.cs 19 KB

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