ArrayConstructor.cs 16 KB

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