WeakSetPrototype.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma warning disable CA1859 // Use concrete types when possible for improved performance -- most of prototype methods return JsValue
  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. /// <summary>
  9. /// https://tc39.es/ecma262/#sec-weakset-objects
  10. /// </summary>
  11. internal sealed class WeakSetPrototype : Prototype
  12. {
  13. private readonly WeakSetConstructor _constructor;
  14. internal ClrFunction _originalAddFunction = null!;
  15. internal WeakSetPrototype(
  16. Engine engine,
  17. Realm realm,
  18. WeakSetConstructor constructor,
  19. ObjectPrototype prototype) : base(engine, realm)
  20. {
  21. _prototype = prototype;
  22. _constructor = constructor;
  23. }
  24. protected override void Initialize()
  25. {
  26. _originalAddFunction = new ClrFunction(Engine, "add", Add, 1, PropertyFlag.Configurable);
  27. const PropertyFlag PropertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable;
  28. var properties = new PropertyDictionary(5, checkExistingKeys: false)
  29. {
  30. ["length"] = new(0, PropertyFlag.Configurable),
  31. ["constructor"] = new(_constructor, PropertyFlag.NonEnumerable),
  32. ["delete"] = new(new ClrFunction(Engine, "delete", Delete, 1, PropertyFlag.Configurable), PropertyFlags),
  33. ["add"] = new(_originalAddFunction, PropertyFlags),
  34. ["has"] = new(new ClrFunction(Engine, "has", Has, 1, PropertyFlag.Configurable), PropertyFlags),
  35. };
  36. SetProperties(properties);
  37. var symbols = new SymbolDictionary(1)
  38. {
  39. [GlobalSymbolRegistry.ToStringTag] = new("WeakSet", false, false, true)
  40. };
  41. SetSymbols(symbols);
  42. }
  43. private JsValue Add(JsValue thisObject, JsCallArguments arguments)
  44. {
  45. var set = AssertWeakSetInstance(thisObject);
  46. set.WeakSetAdd(arguments.At(0));
  47. return thisObject;
  48. }
  49. private JsValue Delete(JsValue thisObject, JsCallArguments arguments)
  50. {
  51. var set = AssertWeakSetInstance(thisObject);
  52. return set.WeakSetDelete(arguments.At(0)) ? JsBoolean.True : JsBoolean.False;
  53. }
  54. private JsValue Has(JsValue thisObject, JsCallArguments arguments)
  55. {
  56. var set = AssertWeakSetInstance(thisObject);
  57. return set.WeakSetHas(arguments.At(0)) ? JsBoolean.True : JsBoolean.False;
  58. }
  59. private JsWeakSet AssertWeakSetInstance(JsValue thisObject)
  60. {
  61. if (thisObject is JsWeakSet set)
  62. {
  63. return set;
  64. }
  65. Throw.TypeError(_realm, "object must be a WeakSet");
  66. return default;
  67. }
  68. }