WeakSetConstructor.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 : Constructor
  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. public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  24. {
  25. if (newTarget.IsUndefined())
  26. {
  27. ExceptionHelper.ThrowTypeError(_realm);
  28. }
  29. var set = OrdinaryCreateFromConstructor(
  30. newTarget,
  31. static intrinsics => intrinsics.WeakSet.PrototypeObject,
  32. static (Engine engine, Realm _, object? _) => new JsWeakSet(engine));
  33. var arg1 = arguments.At(0);
  34. if (!arg1.IsNullOrUndefined())
  35. {
  36. var adder = set.Get("add") as ICallable;
  37. // check fast path
  38. if (arg1 is JsArray array && ReferenceEquals(adder, _engine.Realm.Intrinsics.WeakSet.PrototypeObject._originalAddFunction))
  39. {
  40. foreach (var value in array)
  41. {
  42. set.WeakSetAdd(value);
  43. }
  44. return set;
  45. }
  46. if (adder is null)
  47. {
  48. ExceptionHelper.ThrowTypeError(_realm, "add must be callable");
  49. }
  50. var iterable = arguments.At(0).GetIterator(_realm);
  51. try
  52. {
  53. var args = new JsValue[1];
  54. do
  55. {
  56. if (!iterable.TryIteratorStep(out var next))
  57. {
  58. return set;
  59. }
  60. var nextValue = next.Get(CommonProperties.Value);
  61. args[0] = nextValue;
  62. adder.Call(set, args);
  63. } while (true);
  64. }
  65. catch
  66. {
  67. iterable.Close(CompletionType.Throw);
  68. throw;
  69. }
  70. }
  71. return set;
  72. }
  73. }
  74. }