BigIntConstructor.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/String.h>
  7. #include <LibJS/Runtime/BigInt.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.as_string(), *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_direct_property(vm.names.prototype, global_object.bigint_prototype(), 0);
  24. // TODO: Implement these functions below and uncomment this.
  25. // u8 attr = Attribute::Writable | Attribute::Configurable;
  26. // define_native_function(vm.names.asIntN, as_int_n, 2, attr);
  27. // define_native_function(vm.names.asUintN, as_uint_n, 2, attr);
  28. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  29. }
  30. BigIntConstructor::~BigIntConstructor()
  31. {
  32. }
  33. // 21.2.1.1 BigInt ( value ), https://tc39.es/ecma262/#sec-bigint-constructor-number-value
  34. ThrowCompletionOr<Value> BigIntConstructor::call()
  35. {
  36. auto& vm = this->vm();
  37. auto& global_object = this->global_object();
  38. auto value = vm.argument(0);
  39. // 2. Let prim be ? ToPrimitive(value, number).
  40. auto primitive = TRY(value.to_primitive(global_object, Value::PreferredType::Number));
  41. // 3. If Type(prim) is Number, return ? NumberToBigInt(prim).
  42. if (primitive.is_number())
  43. return TRY(number_to_bigint(global_object, primitive));
  44. // 4. Otherwise, return ? ToBigInt(value).
  45. return TRY(value.to_bigint(global_object));
  46. }
  47. // 21.2.1.1 BigInt ( value ), https://tc39.es/ecma262/#sec-bigint-constructor-number-value
  48. ThrowCompletionOr<Object*> BigIntConstructor::construct(FunctionObject&)
  49. {
  50. return vm().throw_completion<TypeError>(global_object(), ErrorType::NotAConstructor, "BigInt");
  51. }
  52. // 21.2.2.1 BigInt.asIntN ( bits, bigint ), https://tc39.es/ecma262/#sec-bigint.asintn
  53. JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_int_n)
  54. {
  55. TODO();
  56. }
  57. // 21.2.2.2 BigInt.asUintN ( bits, bigint ), https://tc39.es/ecma262/#sec-bigint.asuintn
  58. JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_uint_n)
  59. {
  60. TODO();
  61. }
  62. }