BigIntConstructor.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. define_property(vm.names.prototype, global_object.bigint_prototype(), 0);
  23. define_property(vm.names.length, Value(1), Attribute::Configurable);
  24. u8 attr = Attribute::Writable | Attribute::Configurable;
  25. define_native_function(vm.names.asIntN, as_int_n, 2, attr);
  26. define_native_function(vm.names.asUintN, as_uint_n, 2, attr);
  27. }
  28. BigIntConstructor::~BigIntConstructor()
  29. {
  30. }
  31. Value BigIntConstructor::call()
  32. {
  33. auto primitive = vm().argument(0).to_primitive(global_object(), Value::PreferredType::Number);
  34. if (vm().exception())
  35. return {};
  36. if (primitive.is_number()) {
  37. if (!primitive.is_integer()) {
  38. vm().throw_exception<RangeError>(global_object(), ErrorType::BigIntIntArgument);
  39. return {};
  40. }
  41. return js_bigint(heap(), Crypto::SignedBigInteger { primitive.as_i32() });
  42. }
  43. auto* bigint = vm().argument(0).to_bigint(global_object());
  44. if (vm().exception())
  45. return {};
  46. return bigint;
  47. }
  48. Value BigIntConstructor::construct(Function&)
  49. {
  50. vm().throw_exception<TypeError>(global_object(), ErrorType::NotAConstructor, "BigInt");
  51. return {};
  52. }
  53. JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_int_n)
  54. {
  55. TODO();
  56. }
  57. JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_uint_n)
  58. {
  59. TODO();
  60. }
  61. }