WeakSetPrototype.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Jint.Collections;
  2. using Jint.Native.Object;
  3. using Jint.Native.Symbol;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Descriptors;
  6. using Jint.Runtime.Interop;
  7. namespace Jint.Native.WeakSet
  8. {
  9. /// <summary>
  10. /// https://tc39.es/ecma262/#sec-weakset-objects
  11. /// </summary>
  12. internal sealed class WeakSetPrototype : Prototype
  13. {
  14. private readonly WeakSetConstructor _constructor;
  15. internal ClrFunctionInstance _originalAddFunction = null!;
  16. internal WeakSetPrototype(
  17. Engine engine,
  18. Realm realm,
  19. WeakSetConstructor constructor,
  20. ObjectPrototype prototype) : base(engine, realm)
  21. {
  22. _prototype = prototype;
  23. _constructor = constructor;
  24. }
  25. protected override void Initialize()
  26. {
  27. _originalAddFunction = new ClrFunctionInstance(Engine, "add", Add, 1, PropertyFlag.Configurable);
  28. const PropertyFlag PropertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable;
  29. var properties = new PropertyDictionary(5, checkExistingKeys: false)
  30. {
  31. ["length"] = new(0, PropertyFlag.Configurable),
  32. ["constructor"] = new(_constructor, PropertyFlag.NonEnumerable),
  33. ["delete"] = new(new ClrFunctionInstance(Engine, "delete", Delete, 1, PropertyFlag.Configurable), PropertyFlags),
  34. ["add"] = new(_originalAddFunction, PropertyFlags),
  35. ["has"] = new(new ClrFunctionInstance(Engine, "has", Has, 1, PropertyFlag.Configurable), PropertyFlags),
  36. };
  37. SetProperties(properties);
  38. var symbols = new SymbolDictionary(1)
  39. {
  40. [GlobalSymbolRegistry.ToStringTag] = new("WeakSet", false, false, true)
  41. };
  42. SetSymbols(symbols);
  43. }
  44. private JsValue Add(JsValue thisObj, JsValue[] arguments)
  45. {
  46. var set = AssertWeakSetInstance(thisObj);
  47. set.WeakSetAdd(arguments.At(0));
  48. return thisObj;
  49. }
  50. private JsValue Delete(JsValue thisObj, JsValue[] arguments)
  51. {
  52. var set = AssertWeakSetInstance(thisObj);
  53. return set.WeakSetDelete(arguments.At(0)) ? JsBoolean.True : JsBoolean.False;
  54. }
  55. private JsValue Has(JsValue thisObj, JsValue[] arguments)
  56. {
  57. var set = AssertWeakSetInstance(thisObj);
  58. return set.WeakSetHas(arguments.At(0)) ? JsBoolean.True : JsBoolean.False;
  59. }
  60. private WeakSetInstance AssertWeakSetInstance(JsValue thisObj)
  61. {
  62. var set = thisObj as WeakSetInstance;
  63. if (set is null)
  64. {
  65. ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakSet");
  66. }
  67. return set;
  68. }
  69. }
  70. }