ArrayConstructor.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using System.Collections;
  2. using System.Runtime.CompilerServices;
  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.Descriptors.Specialized;
  11. using Jint.Runtime.Interop;
  12. namespace Jint.Native.Array
  13. {
  14. public sealed class ArrayConstructor : FunctionInstance, IConstructor
  15. {
  16. private static readonly JsString _functionName = new JsString("Array");
  17. private ArrayConstructor(Engine engine) : base(engine, _functionName, false)
  18. {
  19. }
  20. public ArrayPrototype PrototypeObject { get; private set; }
  21. public static ArrayConstructor CreateArrayConstructor(Engine engine)
  22. {
  23. var obj = new ArrayConstructor(engine)
  24. {
  25. Extensible = true,
  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._prototype = new PropertyDescriptor(obj.PrototypeObject, PropertyFlag.AllForbidden);
  33. return obj;
  34. }
  35. protected override void Initialize()
  36. {
  37. _properties = new StringDictionarySlim<PropertyDescriptor>(5)
  38. {
  39. [GlobalSymbolRegistry.Species._value] = new GetSetPropertyDescriptor(get: new ClrFunctionInstance(Engine, "get [Symbol.species]", Species, 0, PropertyFlag.Configurable), set: Undefined,PropertyFlag.Configurable),
  40. ["from"] = new PropertyDescriptor(new PropertyDescriptor(new ClrFunctionInstance(Engine, "from", From, 1, PropertyFlag.Configurable), PropertyFlag.NonEnumerable)),
  41. ["isArray"] = new PropertyDescriptor(new PropertyDescriptor(new ClrFunctionInstance(Engine, "isArray", IsArray, 1), PropertyFlag.NonEnumerable)),
  42. ["of"] = new PropertyDescriptor(new PropertyDescriptor(new ClrFunctionInstance(Engine, "of", Of, 0, PropertyFlag.Configurable), PropertyFlag.NonEnumerable))
  43. };
  44. }
  45. private JsValue From(JsValue thisObj, JsValue[] arguments)
  46. {
  47. var source = 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 (source.IsNullOrUndefined())
  52. {
  53. ExceptionHelper.ThrowTypeError(_engine, "Cannot convert undefined or null to object");
  54. }
  55. if (source is JsString jsString)
  56. {
  57. var a = _engine.Array.ConstructFast((uint) jsString.Length);
  58. for (int i = 0; i < jsString._value.Length; i++)
  59. {
  60. a.SetIndexValue((uint) i, JsString.Create(jsString._value[i]), updateLength: false);
  61. }
  62. return a;
  63. }
  64. if (thisObj.IsNull() || !(source is ObjectInstance objectInstance))
  65. {
  66. return _engine.Array.ConstructFast(0);
  67. }
  68. if (objectInstance.IsArrayLike)
  69. {
  70. return ConstructArrayFromArrayLike(objectInstance, callable, thisArg);
  71. }
  72. if (objectInstance is IObjectWrapper wrapper && wrapper.Target is IEnumerable enumerable)
  73. {
  74. return ConstructArrayFromIEnumerable(enumerable);
  75. }
  76. var instance = _engine.Array.ConstructFast(0);
  77. if (objectInstance.TryGetIterator(_engine, out var iterator))
  78. {
  79. var protocol = new ArrayProtocol(_engine, thisArg, instance, iterator, callable);
  80. protocol.Execute();
  81. }
  82. return instance;
  83. }
  84. private ArrayInstance ConstructArrayFromArrayLike(
  85. ObjectInstance objectInstance,
  86. ICallable callable,
  87. JsValue thisArg)
  88. {
  89. var operations = ArrayPrototype.ArrayOperations.For(objectInstance);
  90. var length = operations.GetLength();
  91. var a = _engine.Array.ConstructFast(length);
  92. var args = !ReferenceEquals(callable, null)
  93. ? _engine._jsValueArrayPool.RentArray(2)
  94. : null;
  95. uint n = 0;
  96. for (uint i = 0; i < length; i++)
  97. {
  98. JsValue jsValue;
  99. operations.TryGetValue(i, out var value);
  100. if (!ReferenceEquals(callable, null))
  101. {
  102. args[0] = value;
  103. args[1] = i;
  104. jsValue = callable.Call(thisArg, args);
  105. // function can alter data
  106. length = operations.GetLength();
  107. }
  108. else
  109. {
  110. jsValue = value;
  111. }
  112. a.SetIndexValue(i, jsValue, updateLength: false);
  113. n++;
  114. }
  115. if (!ReferenceEquals(callable, null))
  116. {
  117. _engine._jsValueArrayPool.ReturnArray(args);
  118. }
  119. a.SetLength(length);
  120. return a;
  121. }
  122. internal sealed class ArrayProtocol : IteratorProtocol
  123. {
  124. private readonly JsValue _thisArg;
  125. private readonly ArrayInstance _instance;
  126. private readonly ICallable _callable;
  127. private long _index = -1;
  128. public ArrayProtocol(
  129. Engine engine,
  130. JsValue thisArg,
  131. ArrayInstance instance,
  132. IIterator iterator,
  133. ICallable callable) : base(engine, iterator, 2)
  134. {
  135. _thisArg = thisArg;
  136. _instance = instance;
  137. _callable = callable;
  138. }
  139. protected override void ProcessItem(JsValue[] args, JsValue currentValue)
  140. {
  141. _index++;
  142. var sourceValue = ExtractValueFromIteratorInstance(currentValue);
  143. JsValue jsValue;
  144. if (!ReferenceEquals(_callable, null))
  145. {
  146. args[0] = sourceValue;
  147. args[1] = _index;
  148. jsValue = _callable.Call(_thisArg, args);
  149. }
  150. else
  151. {
  152. jsValue = sourceValue;
  153. }
  154. _instance.SetIndexValue((uint) _index, jsValue, updateLength: false);
  155. }
  156. protected override void IterationEnd()
  157. {
  158. _instance.SetLength((uint) (_index + 1));
  159. }
  160. }
  161. private JsValue Of(JsValue thisObj, JsValue[] arguments)
  162. {
  163. return _engine.Array.Construct(arguments);
  164. }
  165. private static JsValue Species(JsValue thisObject, JsValue[] arguments)
  166. {
  167. return thisObject;
  168. }
  169. private static JsValue IsArray(JsValue thisObj, JsValue[] arguments)
  170. {
  171. if (arguments.Length == 0)
  172. {
  173. return false;
  174. }
  175. var o = arguments.At(0);
  176. return o.IsObject() && o.AsObject().Class == "Array";
  177. }
  178. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  179. {
  180. return Construct(arguments);
  181. }
  182. public ObjectInstance Construct(JsValue[] arguments)
  183. {
  184. // check if we can figure out good size
  185. var capacity = arguments.Length > 0 ? (uint) arguments.Length : 0;
  186. if (arguments.Length == 1 && arguments[0].Type == Types.Number)
  187. {
  188. var number = ((JsNumber) arguments[0])._value;
  189. if (number > 0)
  190. {
  191. capacity = (uint) number;
  192. }
  193. }
  194. return Construct(arguments, capacity);
  195. }
  196. public ArrayInstance Construct(int capacity)
  197. {
  198. if (capacity < 0)
  199. {
  200. ExceptionHelper.ThrowArgumentException("invalid array length", nameof(capacity));
  201. }
  202. return Construct(System.ArrayExt.Empty<JsValue>(), (uint) capacity);
  203. }
  204. public ArrayInstance Construct(uint capacity)
  205. {
  206. return Construct(System.ArrayExt.Empty<JsValue>(), capacity);
  207. }
  208. public ArrayInstance Construct(JsValue[] arguments, uint capacity)
  209. {
  210. var instance = new ArrayInstance(Engine, capacity);
  211. instance.Prototype = PrototypeObject;
  212. instance.Extensible = true;
  213. if (arguments.Length == 1 && arguments.At(0).IsNumber())
  214. {
  215. var length = TypeConverter.ToUint32(arguments.At(0));
  216. if (((JsNumber) arguments[0])._value != length)
  217. {
  218. ExceptionHelper.ThrowRangeError(_engine, "Invalid array length");
  219. }
  220. instance._length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  221. }
  222. else if (arguments.Length == 1 && arguments[0] is IObjectWrapper objectWrapper)
  223. {
  224. if (objectWrapper.Target is IEnumerable enumerable)
  225. {
  226. return ConstructArrayFromIEnumerable(enumerable);
  227. }
  228. }
  229. else if (arguments.Length == 1 && arguments[0] is ArrayInstance arrayInstance)
  230. {
  231. // direct copy
  232. return ConstructArrayFromArrayLike(arrayInstance, null, this);
  233. }
  234. else
  235. {
  236. instance._length = new PropertyDescriptor(0, PropertyFlag.OnlyWritable);
  237. if (arguments.Length > 0)
  238. {
  239. PrototypeObject.Push(instance, arguments);
  240. }
  241. }
  242. return instance;
  243. }
  244. private ArrayInstance ConstructArrayFromIEnumerable(IEnumerable enumerable)
  245. {
  246. var jsArray = (ArrayInstance) Engine.Array.Construct(Arguments.Empty);
  247. var tempArray = _engine._jsValueArrayPool.RentArray(1);
  248. foreach (var item in enumerable)
  249. {
  250. var jsItem = FromObject(Engine, item);
  251. tempArray[0] = jsItem;
  252. Engine.Array.PrototypeObject.Push(jsArray, tempArray);
  253. }
  254. _engine._jsValueArrayPool.ReturnArray(tempArray);
  255. return jsArray;
  256. }
  257. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  258. internal ArrayInstance ConstructFast(uint length)
  259. {
  260. var instance = new ArrayInstance(Engine, length)
  261. {
  262. Prototype = PrototypeObject,
  263. Extensible = true,
  264. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable)
  265. };
  266. return instance;
  267. }
  268. }
  269. }