ArrayConstructor.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. for (uint k = 0; k < arguments.Length; k++)
  188. {
  189. var kValue = arguments[k];
  190. var key = JsString.Create(k);
  191. a.CreateDataPropertyOrThrow(key, kValue);
  192. }
  193. a.Set(CommonProperties.Length, len, true);
  194. }
  195. else
  196. {
  197. // faster for real arrays
  198. ArrayInstance ai;
  199. a = ai = _realm.Intrinsics.Array.Construct(len);
  200. for (uint k = 0; k < arguments.Length; k++)
  201. {
  202. var kValue = arguments[k];
  203. ai.SetIndexValue(k, kValue, updateLength: false);
  204. }
  205. ai.SetLength((uint) arguments.Length);
  206. }
  207. return a;
  208. }
  209. private static JsValue Species(JsValue thisObject, JsValue[] arguments)
  210. {
  211. return thisObject;
  212. }
  213. private static JsValue IsArray(JsValue thisObj, JsValue[] arguments)
  214. {
  215. var o = arguments.At(0);
  216. return IsArray(o);
  217. }
  218. private static JsValue IsArray(JsValue o)
  219. {
  220. if (!(o is ObjectInstance oi))
  221. {
  222. return JsBoolean.False;
  223. }
  224. return oi.IsArray();
  225. }
  226. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  227. {
  228. return Construct(arguments, thisObject);
  229. }
  230. public ObjectInstance Construct(JsValue[] arguments)
  231. {
  232. return Construct(arguments, this);
  233. }
  234. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) => Construct(arguments, newTarget);
  235. internal ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  236. {
  237. if (newTarget.IsUndefined())
  238. {
  239. newTarget = this;
  240. }
  241. var proto = _realm.Intrinsics.Function.GetPrototypeFromConstructor(
  242. newTarget,
  243. static intrinsics => intrinsics.Array.PrototypeObject);
  244. // check if we can figure out good size
  245. var capacity = arguments.Length > 0 ? (ulong) arguments.Length : 0;
  246. if (arguments.Length == 1 && arguments[0].IsNumber())
  247. {
  248. var number = ((JsNumber) arguments[0])._value;
  249. ValidateLength(number);
  250. capacity = (ulong) number;
  251. }
  252. return Construct(arguments, capacity, proto);
  253. }
  254. public ArrayInstance Construct(int capacity)
  255. {
  256. return Construct(System.Array.Empty<JsValue>(), (uint) capacity);
  257. }
  258. public ArrayInstance Construct(uint capacity)
  259. {
  260. return Construct(System.Array.Empty<JsValue>(), capacity);
  261. }
  262. public ArrayInstance Construct(JsValue[] arguments, uint capacity)
  263. {
  264. return Construct(arguments, capacity, PrototypeObject);
  265. }
  266. private ArrayInstance Construct(JsValue[] arguments, ulong capacity, ObjectInstance prototypeObject)
  267. {
  268. var instance = ArrayCreate(capacity, prototypeObject);
  269. if (arguments.Length == 1 && arguments.At(0).IsNumber())
  270. {
  271. var length = TypeConverter.ToNumber(arguments.At(0));
  272. ValidateLength(length);
  273. instance._length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  274. }
  275. else if (arguments.Length == 1 && arguments[0] is IObjectWrapper objectWrapper)
  276. {
  277. if (objectWrapper.Target is IEnumerable enumerable)
  278. {
  279. return ConstructArrayFromIEnumerable(enumerable);
  280. }
  281. }
  282. else if (arguments.Length == 1 && arguments[0] is ArrayInstance arrayInstance)
  283. {
  284. // direct copy
  285. return (ArrayInstance) ConstructArrayFromArrayLike(Undefined, arrayInstance, null, this);
  286. }
  287. else
  288. {
  289. instance._length = new PropertyDescriptor(0, PropertyFlag.OnlyWritable);
  290. if (arguments.Length > 0)
  291. {
  292. PrototypeObject.Push(instance, arguments);
  293. }
  294. }
  295. return instance;
  296. }
  297. /// <summary>
  298. /// https://tc39.es/ecma262/#sec-arraycreate
  299. /// </summary>
  300. internal ArrayInstance ArrayCreate(ulong length, ObjectInstance proto = null)
  301. {
  302. if (length > ArrayOperations.MaxArrayLength)
  303. {
  304. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length " + length);
  305. }
  306. proto ??= PrototypeObject;
  307. var instance = new ArrayInstance(Engine, (uint) length)
  308. {
  309. _prototype = proto,
  310. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable)
  311. };
  312. return instance;
  313. }
  314. private ArrayInstance ConstructArrayFromIEnumerable(IEnumerable enumerable)
  315. {
  316. var jsArray = (ArrayInstance) Construct(Arguments.Empty);
  317. var tempArray = _engine._jsValueArrayPool.RentArray(1);
  318. foreach (var item in enumerable)
  319. {
  320. var jsItem = FromObject(Engine, item);
  321. tempArray[0] = jsItem;
  322. _realm.Intrinsics.Array.PrototypeObject.Push(jsArray, tempArray);
  323. }
  324. _engine._jsValueArrayPool.ReturnArray(tempArray);
  325. return jsArray;
  326. }
  327. public ArrayInstance ConstructFast(JsValue[] contents)
  328. {
  329. var instance = ArrayCreate((ulong) contents.Length);
  330. for (var i = 0; i < contents.Length; i++)
  331. {
  332. instance.SetIndexValue((uint) i, contents[i], updateLength: false);
  333. }
  334. return instance;
  335. }
  336. internal ArrayInstance ConstructFast(List<JsValue> contents)
  337. {
  338. var instance = ArrayCreate((ulong) contents.Count);
  339. for (var i = 0; i < contents.Count; i++)
  340. {
  341. instance.SetIndexValue((uint) i, contents[i], updateLength: false);
  342. }
  343. return instance;
  344. }
  345. /// <summary>
  346. /// https://tc39.es/ecma262/#sec-arrayspeciescreate
  347. /// </summary>
  348. public ObjectInstance ArraySpeciesCreate(ObjectInstance originalArray, ulong length)
  349. {
  350. var isArray = originalArray.IsArray();
  351. if (!isArray)
  352. {
  353. return ArrayCreate(length);
  354. }
  355. var c = originalArray.Get(CommonProperties.Constructor);
  356. if (c.IsConstructor)
  357. {
  358. var thisRealm = _engine.ExecutionContext.Realm;
  359. var realmC = GetFunctionRealm(c);
  360. if (!ReferenceEquals(thisRealm, realmC))
  361. {
  362. if (ReferenceEquals(c, realmC.Intrinsics.Array))
  363. {
  364. c = Undefined;
  365. }
  366. }
  367. }
  368. if (c.IsObject())
  369. {
  370. c = c.Get(GlobalSymbolRegistry.Species);
  371. if (c.IsNull())
  372. {
  373. c = Undefined;
  374. }
  375. }
  376. if (c.IsUndefined())
  377. {
  378. return ArrayCreate(length);
  379. }
  380. if (!c.IsConstructor)
  381. {
  382. ExceptionHelper.ThrowTypeError(_realm, $"{c} is not a constructor");
  383. }
  384. return ((IConstructor) c).Construct(new JsValue[] { JsNumber.Create(length) }, c);
  385. }
  386. internal JsValue CreateArrayFromList(List<JsValue> values)
  387. {
  388. var jsArray = ArrayCreate((uint) values.Count);
  389. var index = 0;
  390. for (; index < values.Count; index++)
  391. {
  392. var item = values[index];
  393. jsArray.SetIndexValue((uint) index, item, false);
  394. }
  395. jsArray.SetLength((uint) index);
  396. return jsArray;
  397. }
  398. private void ValidateLength(double length)
  399. {
  400. if (length < 0 || length > ArrayOperations.MaxArrayLikeLength || ((long) length) != length)
  401. {
  402. ExceptionHelper.ThrowRangeError(_realm, "Invalid array length");
  403. }
  404. }
  405. }
  406. }