AsyncFunctionConstructor.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Interpreter.h>
  7. #include <LibJS/Runtime/AsyncFunctionConstructor.h>
  8. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  9. #include <LibJS/Runtime/FunctionConstructor.h>
  10. #include <LibJS/Runtime/FunctionObject.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. namespace JS {
  13. AsyncFunctionConstructor::AsyncFunctionConstructor(GlobalObject& global_object)
  14. : NativeFunction(vm().names.AsyncFunction.as_string(), *global_object.function_prototype())
  15. {
  16. }
  17. void AsyncFunctionConstructor::initialize(GlobalObject& global_object)
  18. {
  19. auto& vm = this->vm();
  20. NativeFunction::initialize(global_object);
  21. // 27.7.2.2 AsyncFunction.prototype, https://tc39.es/ecma262/#sec-async-function-constructor-prototype
  22. define_direct_property(vm.names.prototype, global_object.async_function_prototype(), 0);
  23. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  24. }
  25. // 27.7.1.1 AsyncFunction ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-async-function-constructor-arguments
  26. ThrowCompletionOr<Value> AsyncFunctionConstructor::call()
  27. {
  28. return TRY(construct(*this));
  29. }
  30. // 27.7.1.1 AsyncFunction ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-async-function-constructor-arguments
  31. ThrowCompletionOr<Object*> AsyncFunctionConstructor::construct(FunctionObject& new_target)
  32. {
  33. auto& vm = this->vm();
  34. auto function = TRY(FunctionConstructor::create_dynamic_function_node(global_object(), new_target, FunctionKind::Async));
  35. OwnPtr<Interpreter> local_interpreter;
  36. Interpreter* interpreter = vm.interpreter_if_exists();
  37. if (!interpreter) {
  38. local_interpreter = Interpreter::create_with_existing_realm(*realm());
  39. interpreter = local_interpreter.ptr();
  40. }
  41. VM::InterpreterExecutionScope scope(*interpreter);
  42. auto result = function->execute(*interpreter, global_object());
  43. if (auto* exception = vm.exception())
  44. return throw_completion(exception->value());
  45. VERIFY(result.is_object() && is<ECMAScriptFunctionObject>(result.as_object()));
  46. return &result.as_object();
  47. }
  48. }