SymbolPrototype.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using Jint.Native.Object;
  2. using Jint.Runtime;
  3. using Jint.Runtime.Descriptors;
  4. using Jint.Runtime.Interop;
  5. namespace Jint.Native.Symbol
  6. {
  7. /// <summary>
  8. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4
  9. /// </summary>
  10. public sealed class SymbolPrototype : ObjectInstance
  11. {
  12. private SymbolPrototype(Engine engine)
  13. : base(engine)
  14. {
  15. }
  16. public static SymbolPrototype CreatePrototypeObject(Engine engine, SymbolConstructor symbolConstructor)
  17. {
  18. var obj = new SymbolPrototype(engine);
  19. obj.Prototype = engine.Object.PrototypeObject;
  20. obj.Extensible = true;
  21. obj.SetOwnProperty("length", new PropertyDescriptor(0, PropertyFlag.AllForbidden));
  22. obj.FastAddProperty("constructor", symbolConstructor, true, false, true);
  23. return obj;
  24. }
  25. public void Configure()
  26. {
  27. FastAddProperty("toString", new ClrFunctionInstance(Engine, "toString", ToSymbolString), true, false, true);
  28. FastAddProperty("valueOf", new ClrFunctionInstance(Engine, "valueOf", ValueOf), true, false, true);
  29. FastAddProperty("toStringTag", new JsString("Symbol"), false, false, true);
  30. FastAddProperty(GlobalSymbolRegistry.ToPrimitive._value, new ClrFunctionInstance(Engine, "toPrimitive", ToPrimitive), false, false, true);
  31. FastAddProperty(GlobalSymbolRegistry.ToStringTag._value, new JsString("Symbol"), false, false, true);
  32. }
  33. public string SymbolDescriptiveString(JsSymbol sym)
  34. {
  35. return $"Symbol({sym.AsSymbol()})";
  36. }
  37. private JsValue ToSymbolString(JsValue thisObject, JsValue[] arguments)
  38. {
  39. if (!thisObject.IsSymbol())
  40. {
  41. ExceptionHelper.ThrowTypeError(Engine);
  42. }
  43. return SymbolDescriptiveString((JsSymbol)thisObject);
  44. }
  45. private JsValue ValueOf(JsValue thisObject, JsValue[] arguments)
  46. {
  47. var sym = thisObject.TryCast<SymbolInstance>();
  48. if (ReferenceEquals(sym, null))
  49. {
  50. ExceptionHelper.ThrowTypeError(Engine);
  51. }
  52. return sym.SymbolData;
  53. }
  54. private JsValue ToPrimitive(JsValue thisObject, JsValue[] arguments)
  55. {
  56. if (thisObject.IsSymbol())
  57. {
  58. return thisObject;
  59. }
  60. // Steps 3. and 4.
  61. var o = thisObject.AsInstance<SymbolInstance>();
  62. if (ReferenceEquals(o, null))
  63. {
  64. ExceptionHelper.ThrowTypeError(Engine);
  65. }
  66. return o.SymbolData;
  67. }
  68. }
  69. }