ArrayConstructor.cs 14 KB

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