ArrayInstance.cs 18 KB

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