SetConstructor.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using Jint.Collections;
  2. using Jint.Native.Function;
  3. using Jint.Native.Object;
  4. using Jint.Native.Symbol;
  5. using Jint.Runtime;
  6. using Jint.Runtime.Descriptors;
  7. using Jint.Runtime.Interop;
  8. namespace Jint.Native.Set;
  9. internal sealed class SetConstructor : Constructor
  10. {
  11. private static readonly JsString _functionName = new("Set");
  12. internal SetConstructor(
  13. Engine engine,
  14. Realm realm,
  15. FunctionPrototype functionPrototype,
  16. ObjectPrototype objectPrototype)
  17. : base(engine, realm, _functionName)
  18. {
  19. _prototype = functionPrototype;
  20. PrototypeObject = new SetPrototype(engine, realm, this, objectPrototype);
  21. _length = new PropertyDescriptor(0, PropertyFlag.Configurable);
  22. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  23. }
  24. internal SetPrototype PrototypeObject { get; }
  25. protected override void Initialize()
  26. {
  27. var symbols = new SymbolDictionary(1)
  28. {
  29. [GlobalSymbolRegistry.Species] = new GetSetPropertyDescriptor(get: new ClrFunction(_engine, "get [Symbol.species]", Species, 0, PropertyFlag.Configurable), set: Undefined, PropertyFlag.Configurable)
  30. };
  31. SetSymbols(symbols);
  32. }
  33. private static JsValue Species(JsValue thisObject, JsValue[] arguments)
  34. {
  35. return thisObject;
  36. }
  37. /// <summary>
  38. /// https://tc39.es/ecma262/#sec-set-iterable
  39. /// </summary>
  40. public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  41. {
  42. if (newTarget.IsUndefined())
  43. {
  44. ExceptionHelper.ThrowTypeError(_engine.Realm);
  45. }
  46. var set = OrdinaryCreateFromConstructor(
  47. newTarget,
  48. static intrinsics => intrinsics.Set.PrototypeObject,
  49. static (Engine engine, Realm _, object? _) => new JsSet(engine));
  50. if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined())
  51. {
  52. var adderValue = set.Get("add");
  53. var adder = adderValue as ICallable;
  54. if (adder is null)
  55. {
  56. ExceptionHelper.ThrowTypeError(_engine.Realm, "add must be callable");
  57. }
  58. var iterable = arguments.At(0).GetIterator(_realm);
  59. try
  60. {
  61. var args = new JsValue[1];
  62. do
  63. {
  64. if (!iterable.TryIteratorStep(out var next))
  65. {
  66. return set;
  67. }
  68. var nextValue = next.Get(CommonProperties.Value);
  69. args[0] = nextValue;
  70. adder.Call(set, args);
  71. } while (true);
  72. }
  73. catch
  74. {
  75. iterable.Close(CompletionType.Throw);
  76. throw;
  77. }
  78. }
  79. return set;
  80. }
  81. }