ArrayConstructor.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Jint.Collections;
  4. using Jint.Native.Function;
  5. using Jint.Native.Iterator;
  6. using Jint.Native.Object;
  7. using Jint.Native.Symbol;
  8. using Jint.Runtime;
  9. using Jint.Runtime.Descriptors;
  10. using Jint.Runtime.Interop;
  11. namespace Jint.Native.Array
  12. {
  13. public sealed class ArrayConstructor : FunctionInstance, IConstructor
  14. {
  15. private static readonly JsString _functionName = new JsString("Array");
  16. internal ArrayConstructor(
  17. Engine engine,
  18. Realm realm,
  19. FunctionPrototype functionPrototype,
  20. ObjectPrototype objectPrototype)
  21. : base(engine, realm, _functionName)
  22. {
  23. _prototype = functionPrototype;
  24. PrototypeObject = new ArrayPrototype(engine, realm, this, objectPrototype);
  25. _length = new PropertyDescriptor(1, PropertyFlag.Configurable);
  26. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  27. }
  28. public ArrayPrototype PrototypeObject { get; }
  29. protected override void Initialize()
  30. {
  31. var properties = new PropertyDictionary(3, checkExistingKeys: false)
  32. {
  33. ["from"] = new PropertyDescriptor(new PropertyDescriptor(new ClrFunctionInstance(Engine, "from", From, 1, PropertyFlag.Configurable), PropertyFlag.NonEnumerable)),
  34. ["isArray"] = new PropertyDescriptor(new PropertyDescriptor(new ClrFunctionInstance(Engine, "isArray", IsArray, 1), PropertyFlag.NonEnumerable)),
  35. ["of"] = new PropertyDescriptor(new PropertyDescriptor(new ClrFunctionInstance(Engine, "of", Of, 0, PropertyFlag.Configurable), PropertyFlag.NonEnumerable))
  36. };
  37. SetProperties(properties);
  38. var symbols = new SymbolDictionary(1)
  39. {
  40. [GlobalSymbolRegistry.Species] = new GetSetPropertyDescriptor(get: new ClrFunctionInstance(Engine, "get [Symbol.species]", Species, 0, PropertyFlag.Configurable), set: Undefined,PropertyFlag.Configurable),
  41. };
  42. SetSymbols(symbols);
  43. }
  44. private JsValue From(JsValue thisObj, JsValue[] arguments)
  45. {
  46. var source = arguments.At(0);
  47. var mapFunction = arguments.At(1);
  48. var callable = !mapFunction.IsUndefined() ? GetCallable(mapFunction) : null;
  49. var thisArg = arguments.At(2);
  50. if (source.IsNullOrUndefined())
  51. {
  52. ExceptionHelper.ThrowTypeError(_realm, "Cannot convert undefined or null to object");
  53. }
  54. if (source is JsString jsString)
  55. {
  56. var a = _realm.Intrinsics.Array.ArrayCreate((uint) jsString.Length);
  57. for (int i = 0; i < jsString._value.Length; i++)
  58. {
  59. a.SetIndexValue((uint) i, JsString.Create(jsString._value[i]), updateLength: false);
  60. }
  61. return a;
  62. }
  63. if (thisObj.IsNull() || source is not ObjectInstance objectInstance)
  64. {
  65. return _realm.Intrinsics.Array.ArrayCreate(0);
  66. }
  67. if (objectInstance is IObjectWrapper wrapper && wrapper.Target is IEnumerable enumerable)
  68. {
  69. return ConstructArrayFromIEnumerable(enumerable);
  70. }
  71. if (objectInstance.IsArrayLike)
  72. {
  73. return ConstructArrayFromArrayLike(thisObj, objectInstance, callable, thisArg);
  74. }
  75. ObjectInstance instance;
  76. if (thisObj is IConstructor constructor)
  77. {
  78. instance = constructor.Construct(System.Array.Empty<JsValue>(), thisObj);
  79. }
  80. else
  81. {
  82. instance = _realm.Intrinsics.Array.ArrayCreate(0);
  83. }
  84. if (objectInstance.TryGetIterator(_realm, out var iterator))
  85. {
  86. var protocol = new ArrayProtocol(_engine, thisArg, instance, iterator, callable);
  87. protocol.Execute();
  88. }
  89. return instance;
  90. }
  91. private ObjectInstance ConstructArrayFromArrayLike(
  92. JsValue thisObj,
  93. ObjectInstance objectInstance,
  94. ICallable callable,
  95. JsValue thisArg)
  96. {
  97. var source = ArrayOperations.For(objectInstance);
  98. var length = source.GetLength();
  99. ObjectInstance a;
  100. if (thisObj is IConstructor constructor)
  101. {
  102. var argumentsList = objectInstance.Get(GlobalSymbolRegistry.Iterator).IsNullOrUndefined()
  103. ? new JsValue[] { length }
  104. : null;
  105. a = Construct(constructor, argumentsList);
  106. }
  107. else
  108. {
  109. a = _realm.Intrinsics.Array.ArrayCreate(length);
  110. }
  111. var args = !ReferenceEquals(callable, null)
  112. ? _engine._jsValueArrayPool.RentArray(2)
  113. : null;
  114. var target = ArrayOperations.For(a);
  115. uint n = 0;
  116. for (uint i = 0; i < length; i++)
  117. {
  118. JsValue jsValue;
  119. source.TryGetValue(i, out var value);
  120. if (!ReferenceEquals(callable, null))
  121. {
  122. args[0] = value;
  123. args[1] = i;
  124. jsValue = callable.Call(thisArg, args);
  125. // function can alter data
  126. length = source.GetLength();
  127. }
  128. else
  129. {
  130. jsValue = value;
  131. }
  132. target.CreateDataPropertyOrThrow(i, jsValue);
  133. n++;
  134. }
  135. if (!ReferenceEquals(callable, null))
  136. {
  137. _engine._jsValueArrayPool.ReturnArray(args);
  138. }
  139. target.SetLength(length);
  140. return a;
  141. }
  142. private sealed class ArrayProtocol : IteratorProtocol
  143. {
  144. private readonly JsValue _thisArg;
  145. private readonly ArrayOperations _instance;
  146. private readonly ICallable _callable;
  147. private long _index = -1;
  148. public ArrayProtocol(
  149. Engine engine,
  150. JsValue thisArg,
  151. ObjectInstance instance,
  152. IteratorInstance iterator,
  153. ICallable callable) : base(engine, iterator, 2)
  154. {
  155. _thisArg = thisArg;
  156. _instance = ArrayOperations.For(instance);
  157. _callable = callable;
  158. }
  159. protected override void ProcessItem(JsValue[] args, JsValue currentValue)
  160. {
  161. _index++;
  162. JsValue jsValue;
  163. if (!ReferenceEquals(_callable, null))
  164. {
  165. args[0] = currentValue;
  166. args[1] = _index;
  167. jsValue = _callable.Call(_thisArg, args);
  168. }
  169. else
  170. {
  171. jsValue = currentValue;
  172. }
  173. _instance.CreateDataPropertyOrThrow((ulong) _index, jsValue);
  174. }
  175. protected override void IterationEnd()
  176. {
  177. _instance.SetLength((ulong) (_index + 1));
  178. }
  179. }
  180. private JsValue Of(JsValue thisObj, JsValue[] arguments)
  181. {
  182. var len = arguments.Length;
  183. ObjectInstance a;
  184. if (thisObj.IsConstructor)
  185. {
  186. a = ((IConstructor) thisObj).Construct(new JsValue[] { len }, thisObj);
  187. }
  188. else
  189. {
  190. a = _realm.Intrinsics.Array.Construct(len);
  191. }
  192. if (a is ArrayInstance ai)
  193. {
  194. // faster for real arrays
  195. for (uint k = 0; k < arguments.Length; k++)
  196. {
  197. var kValue = arguments[k];
  198. ai.SetIndexValue(k, kValue, updateLength: k == arguments.Length - 1);
  199. }
  200. }
  201. else
  202. {
  203. // slower version
  204. for (uint k = 0; k < arguments.Length; k++)
  205. {
  206. var kValue = arguments[k];
  207. var key = JsString.Create(k);
  208. a.CreateDataPropertyOrThrow(key, kValue);
  209. }
  210. a.Set(CommonProperties.Length, len, true);
  211. }
  212. return a;
  213. }
  214. private static JsValue Species(JsValue thisObject, JsValue[] arguments)
  215. {
  216. return thisObject;
  217. }
  218. private static JsValue IsArray(JsValue thisObj, JsValue[] arguments)
  219. {
  220. var o = arguments.At(0);
  221. return IsArray(o);
  222. }
  223. private static JsValue IsArray(JsValue o)
  224. {
  225. if (!(o is ObjectInstance oi))
  226. {
  227. return JsBoolean.False;
  228. }
  229. return oi.IsArray();
  230. }
  231. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
  232. {
  233. return Construct(arguments, thisObject);
  234. }
  235. public ObjectInstance Construct(JsValue[] arguments)
  236. {
  237. return Construct(arguments, this);
  238. }
  239. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) => Construct(arguments, newTarget);
  240. internal ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  241. {
  242. if (newTarget.IsUndefined())
  243. {
  244. newTarget = this;
  245. }
  246. var proto = _realm.Intrinsics.Function.GetPrototypeFromConstructor(
  247. newTarget,
  248. static intrinsics => intrinsics.Array.PrototypeObject);
  249. // check if we can figure out good size
  250. var capacity = arguments.Length > 0 ? (ulong) arguments.Length : 0;
  251. if (arguments.Length == 1 && arguments[0].IsNumber())
  252. {
  253. var number = ((JsNumber) arguments[0])._value;
  254. ValidateLength(number);
  255. capacity = (ulong) number;
  256. }
  257. return Construct(arguments, capacity, proto);
  258. }
  259. public ArrayInstance Construct(int capacity)
  260. {
  261. return Construct(System.Array.Empty<JsValue>(), (uint) capacity);
  262. }
  263. public ArrayInstance Construct(uint capacity)
  264. {
  265. return Construct(System.Array.Empty<JsValue>(), capacity);
  266. }
  267. public ArrayInstance Construct(JsValue[] arguments, uint capacity)
  268. {
  269. return Construct(arguments, capacity, PrototypeObject);
  270. }
  271. private ArrayInstance Construct(JsValue[] arguments, ulong capacity, ObjectInstance prototypeObject)
  272. {
  273. var instance = ArrayCreate(capacity, prototypeObject);
  274. if (arguments.Length == 1 && arguments.At(0).IsNumber())
  275. {
  276. var length = TypeConverter.ToNumber(arguments.At(0));
  277. ValidateLength(length);
  278. instance._length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  279. }
  280. else if (arguments.Length == 1 && arguments[0] is IObjectWrapper objectWrapper)
  281. {
  282. if (objectWrapper.Target is IEnumerable enumerable)
  283. {
  284. return ConstructArrayFromIEnumerable(enumerable);
  285. }
  286. }
  287. else if (arguments.Length == 1 && arguments[0] is ArrayInstance arrayInstance)
  288. {
  289. // direct copy
  290. return (ArrayInstance) ConstructArrayFromArrayLike(Undefined, arrayInstance, null, this);
  291. }
  292. else
  293. {
  294. instance._length = new PropertyDescriptor(0, PropertyFlag.OnlyWritable);
  295. if (arguments.Length > 0)
  296. {
  297. PrototypeObject.Push(instance, arguments);
  298. }
  299. }
  300. return instance;
  301. }
  302. /// <summary>
  303. /// https://tc39.es/ecma262/#sec-arraycreate
  304. /// </summary>
  305. internal ArrayInstance ArrayCreate(ulong length, ObjectInstance proto = null)
  306. {
  307. if (length > ArrayOperations.MaxArrayLength)
  308. {
  309. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length " + length);
  310. }
  311. proto ??= PrototypeObject;
  312. var instance = new ArrayInstance(Engine, (uint) length)
  313. {
  314. _prototype = proto,
  315. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable)
  316. };
  317. return instance;
  318. }
  319. private ArrayInstance ConstructArrayFromIEnumerable(IEnumerable enumerable)
  320. {
  321. var jsArray = (ArrayInstance) Construct(Arguments.Empty);
  322. var tempArray = _engine._jsValueArrayPool.RentArray(1);
  323. foreach (var item in enumerable)
  324. {
  325. var jsItem = FromObject(Engine, item);
  326. tempArray[0] = jsItem;
  327. _realm.Intrinsics.Array.PrototypeObject.Push(jsArray, tempArray);
  328. }
  329. _engine._jsValueArrayPool.ReturnArray(tempArray);
  330. return jsArray;
  331. }
  332. public ArrayInstance ConstructFast(JsValue[] contents)
  333. {
  334. var instance = ArrayCreate((ulong) contents.Length);
  335. for (var i = 0; i < contents.Length; i++)
  336. {
  337. instance.SetIndexValue((uint) i, contents[i], updateLength: false);
  338. }
  339. return instance;
  340. }
  341. internal ArrayInstance ConstructFast(List<JsValue> contents)
  342. {
  343. var instance = ArrayCreate((ulong) contents.Count);
  344. for (var i = 0; i < contents.Count; i++)
  345. {
  346. instance.SetIndexValue((uint) i, contents[i], updateLength: false);
  347. }
  348. return instance;
  349. }
  350. /// <summary>
  351. /// https://tc39.es/ecma262/#sec-arrayspeciescreate
  352. /// </summary>
  353. public ObjectInstance ArraySpeciesCreate(ObjectInstance originalArray, ulong length)
  354. {
  355. var isArray = originalArray.IsArray();
  356. if (!isArray)
  357. {
  358. return ArrayCreate(length);
  359. }
  360. var c = originalArray.Get(CommonProperties.Constructor);
  361. if (c.IsConstructor)
  362. {
  363. var thisRealm = _engine.ExecutionContext.Realm;
  364. var realmC = GetFunctionRealm(c);
  365. if (!ReferenceEquals(thisRealm, realmC))
  366. {
  367. if (ReferenceEquals(c, realmC.Intrinsics.Array))
  368. {
  369. c = Undefined;
  370. }
  371. }
  372. }
  373. if (c.IsObject())
  374. {
  375. c = c.Get(GlobalSymbolRegistry.Species);
  376. if (c.IsNull())
  377. {
  378. c = Undefined;
  379. }
  380. }
  381. if (c.IsUndefined())
  382. {
  383. return ArrayCreate(length);
  384. }
  385. if (!c.IsConstructor)
  386. {
  387. ExceptionHelper.ThrowTypeError(_realm, $"{c} is not a constructor");
  388. }
  389. return ((IConstructor) c).Construct(new JsValue[] { JsNumber.Create(length) }, c);
  390. }
  391. internal JsValue CreateArrayFromList(List<JsValue> values)
  392. {
  393. var jsArray = ArrayCreate((uint) values.Count);
  394. var index = 0;
  395. for (; index < values.Count; index++)
  396. {
  397. var item = values[index];
  398. jsArray.SetIndexValue((uint) index, item, false);
  399. }
  400. jsArray.SetLength((uint) index);
  401. return jsArray;
  402. }
  403. private void ValidateLength(double length)
  404. {
  405. if (length < 0 || length > ArrayOperations.MaxArrayLikeLength || ((long) length) != length)
  406. {
  407. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");
  408. }
  409. }
  410. }
  411. }