BooleanConstructor.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. internal sealed class BooleanConstructor : Constructor
  8. {
  9. private static readonly JsString _functionName = new JsString("Boolean");
  10. internal BooleanConstructor(
  11. Engine engine,
  12. Realm realm,
  13. FunctionPrototype functionPrototype,
  14. ObjectPrototype objectPrototype)
  15. : base(engine, realm, _functionName)
  16. {
  17. _prototype = functionPrototype;
  18. PrototypeObject = new BooleanPrototype(engine, realm, this, objectPrototype);
  19. _length = new PropertyDescriptor(JsNumber.PositiveOne, PropertyFlag.Configurable);
  20. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  21. }
  22. public BooleanPrototype PrototypeObject { get; }
  23. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
  24. {
  25. if (arguments.Length == 0)
  26. {
  27. return false;
  28. }
  29. return TypeConverter.ToBoolean(arguments[0]);
  30. }
  31. /// <summary>
  32. /// https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  33. /// </summary>
  34. public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  35. {
  36. var b = TypeConverter.ToBoolean(arguments.At(0))
  37. ? JsBoolean.True
  38. : JsBoolean.False;
  39. if (newTarget.IsUndefined())
  40. {
  41. return Construct(b);
  42. }
  43. var o = OrdinaryCreateFromConstructor(
  44. newTarget,
  45. static intrinsics => intrinsics.Boolean.PrototypeObject,
  46. static (engine, realm, state) => new BooleanInstance(engine, state!), b);
  47. return o;
  48. }
  49. public BooleanInstance Construct(JsBoolean value)
  50. {
  51. var instance = new BooleanInstance(Engine, value)
  52. {
  53. _prototype = PrototypeObject
  54. };
  55. return instance;
  56. }
  57. }
  58. }