BigIntConstructor.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/String.h>
  7. #include <LibCrypto/BigInt/SignedBigInteger.h>
  8. #include <LibJS/Runtime/BigIntConstructor.h>
  9. #include <LibJS/Runtime/BigIntObject.h>
  10. #include <LibJS/Runtime/Error.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/VM.h>
  13. namespace JS {
  14. BigIntConstructor::BigIntConstructor(GlobalObject& global_object)
  15. : NativeFunction(vm().names.BigInt, *global_object.function_prototype())
  16. {
  17. }
  18. void BigIntConstructor::initialize(GlobalObject& global_object)
  19. {
  20. auto& vm = this->vm();
  21. NativeFunction::initialize(global_object);
  22. // 21.2.2.3 BigInt.prototype, https://tc39.es/ecma262/#sec-bigint.prototype
  23. define_property(vm.names.prototype, global_object.bigint_prototype(), 0);
  24. define_property(vm.names.length, Value(1), Attribute::Configurable);
  25. // TODO: Implement these functions below and uncomment this.
  26. // u8 attr = Attribute::Writable | Attribute::Configurable;
  27. // define_native_function(vm.names.asIntN, as_int_n, 2, attr);
  28. // define_native_function(vm.names.asUintN, as_uint_n, 2, attr);
  29. }
  30. BigIntConstructor::~BigIntConstructor()
  31. {
  32. }
  33. // 21.2.1.1 BigInt ( value ), https://tc39.es/ecma262/#sec-bigint-constructor-number-value
  34. Value BigIntConstructor::call()
  35. {
  36. auto primitive = vm().argument(0).to_primitive(global_object(), Value::PreferredType::Number);
  37. if (vm().exception())
  38. return {};
  39. if (primitive.is_number()) {
  40. if (!primitive.is_integral_number()) {
  41. vm().throw_exception<RangeError>(global_object(), ErrorType::BigIntIntArgument);
  42. return {};
  43. }
  44. return js_bigint(heap(), Crypto::SignedBigInteger { primitive.as_i32() });
  45. }
  46. auto* bigint = vm().argument(0).to_bigint(global_object());
  47. if (vm().exception())
  48. return {};
  49. return bigint;
  50. }
  51. // 21.2.1.1 BigInt ( value ), https://tc39.es/ecma262/#sec-bigint-constructor-number-value
  52. Value BigIntConstructor::construct(Function&)
  53. {
  54. vm().throw_exception<TypeError>(global_object(), ErrorType::NotAConstructor, "BigInt");
  55. return {};
  56. }
  57. // 21.2.2.1 BigInt.asIntN ( bits, bigint ), https://tc39.es/ecma262/#sec-bigint.asintn
  58. JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_int_n)
  59. {
  60. TODO();
  61. }
  62. // 21.2.2.2 BigInt.asUintN ( bits, bigint ), https://tc39.es/ecma262/#sec-bigint.asuintn
  63. JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_uint_n)
  64. {
  65. TODO();
  66. }
  67. }