BooleanConstructor.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2020, Jack Karamanian <karamanian.jack@gmail.com>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/BooleanConstructor.h>
  9. #include <LibJS/Runtime/BooleanObject.h>
  10. #include <LibJS/Runtime/GlobalObject.h>
  11. #include <LibJS/Runtime/ValueInlines.h>
  12. namespace JS {
  13. JS_DEFINE_ALLOCATOR(BooleanConstructor);
  14. BooleanConstructor::BooleanConstructor(Realm& realm)
  15. : NativeFunction(realm.vm().names.Boolean.as_string(), realm.intrinsics().function_prototype())
  16. {
  17. }
  18. void BooleanConstructor::initialize(Realm& realm)
  19. {
  20. auto& vm = this->vm();
  21. Base::initialize(realm);
  22. // 20.3.2.1 Boolean.prototype, https://tc39.es/ecma262/#sec-boolean.prototype
  23. define_direct_property(vm.names.prototype, realm.intrinsics().boolean_prototype(), 0);
  24. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  25. }
  26. // 20.3.1.1 Boolean ( value ), https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  27. ThrowCompletionOr<Value> BooleanConstructor::call()
  28. {
  29. auto& vm = this->vm();
  30. auto value = vm.argument(0);
  31. // 1. Let b be ToBoolean(value).
  32. auto b = value.to_boolean();
  33. // 2. If NewTarget is undefined, return b.
  34. return Value(b);
  35. }
  36. // 20.3.1.1 Boolean ( value ), https://tc39.es/ecma262/#sec-boolean-constructor-boolean-value
  37. ThrowCompletionOr<NonnullGCPtr<Object>> BooleanConstructor::construct(FunctionObject& new_target)
  38. {
  39. auto& vm = this->vm();
  40. auto value = vm.argument(0);
  41. // 1. Let b be ToBoolean(value).
  42. auto b = value.to_boolean();
  43. // 3. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Boolean.prototype%", « [[BooleanData]] »).
  44. // 4. Set O.[[BooleanData]] to b.
  45. // 5. Return O.
  46. return TRY(ordinary_create_from_constructor<BooleanObject>(vm, new_target, &Intrinsics::boolean_prototype, b));
  47. }
  48. }