ArrayConstructor.cs 14 KB

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