BooleanConstructor.cs 1.9 KB

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