WeakSetConstructor.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Native.WeakSet
  6. {
  7. public sealed class WeakSetConstructor : FunctionInstance, IConstructor
  8. {
  9. private static readonly JsString _functionName = new JsString("WeakSet");
  10. internal WeakSetConstructor(
  11. Engine engine,
  12. Realm realm,
  13. FunctionPrototype functionPrototype,
  14. ObjectPrototype objectPrototype)
  15. : base(engine, realm, _functionName)
  16. {
  17. _prototype = functionPrototype;
  18. PrototypeObject = new WeakSetPrototype(engine, realm, this, objectPrototype);
  19. _length = new PropertyDescriptor(0, PropertyFlag.Configurable);
  20. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  21. }
  22. public WeakSetPrototype PrototypeObject { get; }
  23. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  24. {
  25. ExceptionHelper.ThrowTypeError(_realm, "Constructor WeakSet requires 'new'");
  26. return null;
  27. }
  28. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget)
  29. {
  30. if (newTarget.IsUndefined())
  31. {
  32. ExceptionHelper.ThrowTypeError(_realm);
  33. }
  34. var set = OrdinaryCreateFromConstructor(
  35. newTarget,
  36. static intrinsics => intrinsics.WeakSet.PrototypeObject,
  37. static (engine, realm, _) => new WeakSetInstance(engine));
  38. if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined())
  39. {
  40. var adder = set.Get("add") as ICallable;
  41. if (adder is null)
  42. {
  43. ExceptionHelper.ThrowTypeError(_realm, "add must be callable");
  44. }
  45. var iterable = arguments.At(0).GetIterator(_realm);
  46. try
  47. {
  48. var args = new JsValue[1];
  49. do
  50. {
  51. if (!iterable.TryIteratorStep(out var next))
  52. {
  53. return set;
  54. }
  55. next.TryGetValue(CommonProperties.Value, out var nextValue);
  56. args[0] = nextValue;
  57. adder.Call(set, args);
  58. } while (true);
  59. }
  60. catch
  61. {
  62. iterable.Close(CompletionType.Throw);
  63. throw;
  64. }
  65. }
  66. return set;
  67. }
  68. }
  69. }