WeakRefConstructor.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2021-2022, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Error.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/WeakRef.h>
  10. #include <LibJS/Runtime/WeakRefConstructor.h>
  11. namespace JS {
  12. JS_DEFINE_ALLOCATOR(WeakRefConstructor);
  13. WeakRefConstructor::WeakRefConstructor(Realm& realm)
  14. : NativeFunction(realm.vm().names.WeakRef.as_string(), realm.intrinsics().function_prototype())
  15. {
  16. }
  17. void WeakRefConstructor::initialize(Realm& realm)
  18. {
  19. auto& vm = this->vm();
  20. Base::initialize(realm);
  21. // 26.1.2.1 WeakRef.prototype, https://tc39.es/ecma262/#sec-weak-ref.prototype
  22. define_direct_property(vm.names.prototype, realm.intrinsics().weak_ref_prototype(), 0);
  23. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  24. }
  25. // 26.1.1.1 WeakRef ( target ), https://tc39.es/ecma262/#sec-weak-ref-target
  26. ThrowCompletionOr<Value> WeakRefConstructor::call()
  27. {
  28. auto& vm = this->vm();
  29. // 1. If NewTarget is undefined, throw a TypeError exception.
  30. return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, vm.names.WeakRef);
  31. }
  32. // 26.1.1.1 WeakRef ( target ), https://tc39.es/ecma262/#sec-weak-ref-target
  33. ThrowCompletionOr<NonnullGCPtr<Object>> WeakRefConstructor::construct(FunctionObject& new_target)
  34. {
  35. auto& vm = this->vm();
  36. auto target = vm.argument(0);
  37. // 2. If CanBeHeldWeakly(target) is false, throw a TypeError exception.
  38. if (!can_be_held_weakly(target))
  39. return vm.throw_completion<TypeError>(ErrorType::CannotBeHeldWeakly, target.to_string_without_side_effects());
  40. // 3. Let weakRef be ? OrdinaryCreateFromConstructor(NewTarget, "%WeakRef.prototype%", « [[WeakRefTarget]] »).
  41. // 4. Perform AddToKeptObjects(target).
  42. // 5. Set weakRef.[[WeakRefTarget]] to target.
  43. // 6. Return weakRef.
  44. if (target.is_object())
  45. return TRY(ordinary_create_from_constructor<WeakRef>(vm, new_target, &Intrinsics::weak_ref_prototype, target.as_object()));
  46. VERIFY(target.is_symbol());
  47. return TRY(ordinary_create_from_constructor<WeakRef>(vm, new_target, &Intrinsics::weak_ref_prototype, target.as_symbol()));
  48. }
  49. }