ArrayConstructor.cs 15 KB

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