GeneratorFunctionConstructor.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  7. #include <LibJS/Runtime/FunctionConstructor.h>
  8. #include <LibJS/Runtime/GeneratorFunctionConstructor.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. namespace JS {
  11. JS_DEFINE_ALLOCATOR(GeneratorFunctionConstructor);
  12. GeneratorFunctionConstructor::GeneratorFunctionConstructor(Realm& realm)
  13. : NativeFunction(static_cast<Object&>(realm.intrinsics().function_constructor()))
  14. {
  15. }
  16. void GeneratorFunctionConstructor::initialize(Realm& realm)
  17. {
  18. auto& vm = this->vm();
  19. Base::initialize(realm);
  20. // 27.3.2.1 GeneratorFunction.length, https://tc39.es/ecma262/#sec-generatorfunction.length
  21. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  22. // 27.3.2.2 GeneratorFunction.prototype, https://tc39.es/ecma262/#sec-generatorfunction.length
  23. define_direct_property(vm.names.prototype, realm.intrinsics().generator_function_prototype(), 0);
  24. }
  25. // 27.3.1.1 GeneratorFunction ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-generatorfunction
  26. ThrowCompletionOr<Value> GeneratorFunctionConstructor::call()
  27. {
  28. return TRY(construct(*this));
  29. }
  30. // 27.3.1.1 GeneratorFunction ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-generatorfunction
  31. ThrowCompletionOr<NonnullGCPtr<Object>> GeneratorFunctionConstructor::construct(FunctionObject& new_target)
  32. {
  33. auto& vm = this->vm();
  34. // 1. Let C be the active function object.
  35. auto* constructor = vm.active_function_object();
  36. // 2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
  37. MarkedVector<Value> args(heap());
  38. for (auto argument : vm.running_execution_context().arguments)
  39. args.append(argument);
  40. // 3. Return ? CreateDynamicFunction(C, NewTarget, generator, args).
  41. return *TRY(FunctionConstructor::create_dynamic_function(vm, *constructor, &new_target, FunctionKind::Generator, args));
  42. }
  43. }