BooleanConstructor.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Native.Boolean
  6. {
  7. public sealed class BooleanConstructor : FunctionInstance, IConstructor
  8. {
  9. private static readonly JsString _functionName = new JsString("Boolean");
  10. private BooleanConstructor(Engine engine)
  11. : base(engine, _functionName)
  12. {
  13. }
  14. public BooleanPrototype PrototypeObject { get; private set; }
  15. public static BooleanConstructor CreateBooleanConstructor(Engine engine)
  16. {
  17. var obj = new BooleanConstructor(engine);
  18. // The value of the [[Prototype]] internal property of the Boolean constructor is the Function prototype object
  19. obj._prototype = engine.Function.PrototypeObject;
  20. obj.PrototypeObject = BooleanPrototype.CreatePrototypeObject(engine, obj);
  21. obj._length = new PropertyDescriptor(JsNumber.One, PropertyFlag.Configurable);
  22. // The initial value of Boolean.prototype is the Boolean prototype object
  23. obj._prototypeDescriptor = new PropertyDescriptor(obj.PrototypeObject, PropertyFlag.AllForbidden);
  24. return obj;
  25. }
  26. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  27. {
  28. if (arguments.Length == 0)
  29. {
  30. return false;
  31. }
  32. return TypeConverter.ToBoolean(arguments[0]);
  33. }
  34. /// <summary>
  35. /// https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  36. /// </summary>
  37. public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  38. {
  39. var b = TypeConverter.ToBoolean(arguments.At(0))
  40. ? JsBoolean.True
  41. : JsBoolean.False;
  42. if (newTarget.IsUndefined())
  43. {
  44. return Construct(b);
  45. }
  46. var o = OrdinaryCreateFromConstructor(newTarget, PrototypeObject, static (engine, state) => new BooleanInstance(engine, (JsBoolean) state), b);
  47. return Construct(b);
  48. }
  49. public BooleanInstance Construct(JsBoolean value)
  50. {
  51. var instance = new BooleanInstance(Engine)
  52. {
  53. _prototype = PrototypeObject,
  54. PrimitiveValue = value,
  55. };
  56. return instance;
  57. }
  58. }
  59. }