2
0

WeakSetConstructor.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. internal sealed class WeakSetConstructor : FunctionInstance, IConstructor
  8. {
  9. private static readonly JsString _functionName = new("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. private WeakSetPrototype PrototypeObject { get; }
  23. protected internal 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 engine, Realm _, object? _) => new WeakSetInstance(engine));
  38. var arg1 = arguments.At(0);
  39. if (!arg1.IsNullOrUndefined())
  40. {
  41. var adder = set.Get("add") as ICallable;
  42. // check fast path
  43. if (arg1 is JsArray array && ReferenceEquals(adder, _engine.Realm.Intrinsics.WeakSet.PrototypeObject._originalAddFunction))
  44. {
  45. foreach (var value in array)
  46. {
  47. set.WeakSetAdd(value);
  48. }
  49. return set;
  50. }
  51. if (adder is null)
  52. {
  53. ExceptionHelper.ThrowTypeError(_realm, "add must be callable");
  54. }
  55. var iterable = arguments.At(0).GetIterator(_realm);
  56. try
  57. {
  58. var args = new JsValue[1];
  59. do
  60. {
  61. if (!iterable.TryIteratorStep(out var next))
  62. {
  63. return set;
  64. }
  65. var nextValue = next.Get(CommonProperties.Value);
  66. args[0] = nextValue;
  67. adder.Call(set, args);
  68. } while (true);
  69. }
  70. catch
  71. {
  72. iterable.Close(CompletionType.Throw);
  73. throw;
  74. }
  75. }
  76. return set;
  77. }
  78. }
  79. }