AsyncGenerator.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Variant.h>
  9. #include <LibJS/Bytecode/Interpreter.h>
  10. #include <LibJS/Runtime/ExecutionContext.h>
  11. #include <LibJS/Runtime/Object.h>
  12. namespace JS {
  13. // 27.6.2 Properties of AsyncGenerator Instances, https://tc39.es/ecma262/#sec-properties-of-asyncgenerator-intances
  14. class AsyncGenerator final : public Object {
  15. JS_OBJECT(AsyncGenerator, Object);
  16. public:
  17. enum class State {
  18. SuspendedStart,
  19. SuspendedYield,
  20. Executing,
  21. AwaitingReturn,
  22. Completed,
  23. };
  24. static ThrowCompletionOr<NonnullGCPtr<AsyncGenerator>> create(Realm&, Value, ECMAScriptFunctionObject*, ExecutionContext, Bytecode::CallFrame);
  25. virtual ~AsyncGenerator() override = default;
  26. void async_generator_enqueue(Completion, NonnullGCPtr<PromiseCapability>);
  27. ThrowCompletionOr<void> resume(VM&, Completion completion);
  28. void await_return();
  29. void complete_step(Completion, bool done, Realm* realm = nullptr);
  30. void drain_queue();
  31. State async_generator_state() const { return m_async_generator_state; }
  32. void set_async_generator_state(Badge<AsyncGeneratorPrototype>, State value);
  33. Optional<String> const& generator_brand() const { return m_generator_brand; }
  34. private:
  35. AsyncGenerator(Realm&, Object& prototype, ExecutionContext);
  36. virtual void visit_edges(Cell::Visitor&) override;
  37. void execute(VM&, Completion completion);
  38. ThrowCompletionOr<void> await(Value);
  39. // At the time of constructing an AsyncGenerator, we still need to point to an
  40. // execution context on the stack, but later need to 'adopt' it.
  41. State m_async_generator_state { State::SuspendedStart }; // [[AsyncGeneratorState]]
  42. ExecutionContext m_async_generator_context; // [[AsyncGeneratorContext]]
  43. Vector<AsyncGeneratorRequest> m_async_generator_queue; // [[AsyncGeneratorQueue]]
  44. Optional<String> m_generator_brand; // [[GeneratorBrand]]
  45. GCPtr<ECMAScriptFunctionObject> m_generating_function;
  46. Value m_previous_value;
  47. Optional<Bytecode::CallFrame> m_frame;
  48. GCPtr<Promise> m_current_promise;
  49. };
  50. }