ArrayConstructor.cs 16 KB

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