MapConstructor.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Jint.Collections;
  2. using Jint.Native.Function;
  3. using Jint.Native.Iterator;
  4. using Jint.Native.Object;
  5. using Jint.Native.Symbol;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Descriptors;
  8. using Jint.Runtime.Interop;
  9. namespace Jint.Native.Map;
  10. public sealed class MapConstructor : FunctionInstance, IConstructor
  11. {
  12. private static readonly JsString _functionName = new("Map");
  13. internal MapConstructor(
  14. Engine engine,
  15. Realm realm,
  16. FunctionPrototype functionPrototype,
  17. ObjectPrototype objectPrototype)
  18. : base(engine, realm, _functionName)
  19. {
  20. _prototype = functionPrototype;
  21. PrototypeObject = new MapPrototype(engine, realm, this, objectPrototype);
  22. _length = new PropertyDescriptor(0, PropertyFlag.Configurable);
  23. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  24. }
  25. private MapPrototype PrototypeObject { get; }
  26. protected override void Initialize()
  27. {
  28. var symbols = new SymbolDictionary(1)
  29. {
  30. [GlobalSymbolRegistry.Species] = new GetSetPropertyDescriptor(get: new ClrFunctionInstance(_engine, "get [Symbol.species]", Species, 0, PropertyFlag.Configurable), set: Undefined, PropertyFlag.Configurable)
  31. };
  32. SetSymbols(symbols);
  33. }
  34. private static JsValue Species(JsValue thisObject, JsValue[] arguments)
  35. {
  36. return thisObject;
  37. }
  38. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
  39. {
  40. ExceptionHelper.ThrowTypeError(_realm, "Constructor Map requires 'new'");
  41. return null;
  42. }
  43. /// <summary>
  44. /// https://tc39.es/ecma262/#sec-map-iterable
  45. /// </summary>
  46. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget)
  47. {
  48. if (newTarget.IsUndefined())
  49. {
  50. ExceptionHelper.ThrowTypeError(_realm);
  51. }
  52. var map = OrdinaryCreateFromConstructor(
  53. newTarget,
  54. static intrinsics => intrinsics.Map.PrototypeObject,
  55. static (Engine engine, Realm realm, object? _) => new MapInstance(engine, realm));
  56. if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined())
  57. {
  58. var adder = map.Get("set");
  59. var iterator = arguments.At(0).GetIterator(_realm);
  60. IteratorProtocol.AddEntriesFromIterable(map, iterator, adder);
  61. }
  62. return map;
  63. }
  64. }