ArrayInstance.cs 19 KB

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