BooleanPrototype.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 <AK/Function.h>
  8. #include <AK/TypeCasts.h>
  9. #include <LibJS/Runtime/BooleanPrototype.h>
  10. #include <LibJS/Runtime/Error.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. namespace JS {
  13. GC_DEFINE_ALLOCATOR(BooleanPrototype);
  14. BooleanPrototype::BooleanPrototype(Realm& realm)
  15. : BooleanObject(false, realm.intrinsics().object_prototype())
  16. {
  17. }
  18. void BooleanPrototype::initialize(Realm& realm)
  19. {
  20. auto& vm = this->vm();
  21. Base::initialize(realm);
  22. u8 attr = Attribute::Writable | Attribute::Configurable;
  23. define_native_function(realm, vm.names.toString, to_string, 0, attr);
  24. define_native_function(realm, vm.names.valueOf, value_of, 0, attr);
  25. }
  26. // thisBooleanValue ( value ), https://tc39.es/ecma262/#thisbooleanvalue
  27. static ThrowCompletionOr<bool> this_boolean_value(VM& vm, Value value)
  28. {
  29. // 1. If value is a Boolean, return value.
  30. if (value.is_boolean())
  31. return value.as_bool();
  32. // 2. If value is an Object and value has a [[BooleanData]] internal slot, then
  33. if (value.is_object() && is<BooleanObject>(value.as_object())) {
  34. // a. Let b be value.[[BooleanData]].
  35. // b. Assert: b is a Boolean.
  36. // c. Return b.
  37. return static_cast<BooleanObject&>(value.as_object()).boolean();
  38. }
  39. // 3. Throw a TypeError exception.
  40. return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Boolean");
  41. }
  42. // 20.3.3.2 Boolean.prototype.toString ( ), https://tc39.es/ecma262/#sec-boolean.prototype.tostring
  43. JS_DEFINE_NATIVE_FUNCTION(BooleanPrototype::to_string)
  44. {
  45. // 1. Let b be ? thisBooleanValue(this value).
  46. auto b = TRY(this_boolean_value(vm, vm.this_value()));
  47. // 2. If b is true, return "true"; else return "false".
  48. return PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, String::from_utf8(b ? "true"sv : "false"sv)));
  49. }
  50. // 20.3.3.3 Boolean.prototype.valueOf ( ), https://tc39.es/ecma262/#sec-boolean.prototype.valueof
  51. JS_DEFINE_NATIVE_FUNCTION(BooleanPrototype::value_of)
  52. {
  53. // 1. Return ? thisBooleanValue(this value).
  54. return TRY(this_boolean_value(vm, vm.this_value()));
  55. }
  56. }