2
0

ArrayConstructor.cs 16 KB

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