Generator.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/OwnPtr.h>
  8. #include <LibJS/Bytecode/Label.h>
  9. #include <LibJS/Bytecode/Register.h>
  10. #include <LibJS/Forward.h>
  11. namespace JS::Bytecode {
  12. class Generator {
  13. public:
  14. static OwnPtr<Block> generate(ASTNode const&);
  15. Register allocate_register();
  16. template<typename OpType, typename... Args>
  17. OpType& emit(Args&&... args)
  18. {
  19. void* slot = next_slot();
  20. grow(sizeof(OpType));
  21. new (slot) OpType(forward<Args>(args)...);
  22. return *static_cast<OpType*>(slot);
  23. }
  24. template<typename OpType, typename... Args>
  25. OpType& emit_with_extra_register_slots(size_t extra_register_slots, Args&&... args)
  26. {
  27. void* slot = next_slot();
  28. grow(sizeof(OpType) + extra_register_slots * sizeof(Register));
  29. new (slot) OpType(forward<Args>(args)...);
  30. return *static_cast<OpType*>(slot);
  31. }
  32. Label make_label() const;
  33. void begin_continuable_scope();
  34. void end_continuable_scope();
  35. Label nearest_continuable_scope() const;
  36. private:
  37. Generator();
  38. ~Generator();
  39. void grow(size_t);
  40. void* next_slot();
  41. OwnPtr<Block> m_block;
  42. u32 m_next_register { 1 };
  43. Vector<Label> m_continuable_scopes;
  44. };
  45. }