ArrayInstance.cs 19 KB

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