ShadowRealmConstructor.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/ShadowRealm.h>
  9. #include <LibJS/Runtime/ShadowRealmConstructor.h>
  10. namespace JS {
  11. GC_DEFINE_ALLOCATOR(ShadowRealmConstructor);
  12. // 3.2 The ShadowRealm Constructor, https://tc39.es/proposal-shadowrealm/#sec-shadowrealm-constructor
  13. ShadowRealmConstructor::ShadowRealmConstructor(Realm& realm)
  14. : NativeFunction(realm.vm().names.ShadowRealm.as_string(), realm.intrinsics().function_prototype())
  15. {
  16. }
  17. void ShadowRealmConstructor::initialize(Realm& realm)
  18. {
  19. auto& vm = this->vm();
  20. Base::initialize(realm);
  21. // 3.3.1 ShadowRealm.prototype, https://tc39.es/proposal-shadowrealm/#sec-shadowrealm.prototype
  22. define_direct_property(vm.names.prototype, realm.intrinsics().shadow_realm_prototype(), 0);
  23. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  24. }
  25. // 3.2.1 ShadowRealm ( ), https://tc39.es/proposal-shadowrealm/#sec-shadowrealm
  26. ThrowCompletionOr<Value> ShadowRealmConstructor::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.ShadowRealm);
  31. }
  32. // 3.2.1 ShadowRealm ( ), https://tc39.es/proposal-shadowrealm/#sec-shadowrealm
  33. ThrowCompletionOr<GC::Ref<Object>> ShadowRealmConstructor::construct(FunctionObject& new_target)
  34. {
  35. auto& vm = this->vm();
  36. // 2. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%ShadowRealm.prototype%", « [[ShadowRealm]] »).
  37. auto object = TRY(ordinary_create_from_constructor<ShadowRealm>(vm, new_target, &Intrinsics::shadow_realm_prototype));
  38. // 3. Let callerContext be the running execution context.
  39. // 4. Perform ? InitializeHostDefinedRealm().
  40. // 5. Let innerContext be the running execution context.
  41. auto inner_context = TRY(Realm::initialize_host_defined_realm(vm, nullptr, nullptr));
  42. // 6. Remove innerContext from the execution context stack and restore callerContext as the running execution context.
  43. vm.pop_execution_context();
  44. // 7. Let realmRec be the Realm of innerContext.
  45. auto& realm_record = *inner_context->realm;
  46. // 8. Set O.[[ShadowRealm]] to realmRec.
  47. object->set_shadow_realm(realm_record);
  48. // 9. Perform ? HostInitializeShadowRealm(realmRec, innerContext, O).
  49. TRY(vm.host_initialize_shadow_realm(realm_record, move(inner_context), object));
  50. // 10. Return O.
  51. return object;
  52. }
  53. }