Cell.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Format.h>
  8. #include <AK/Forward.h>
  9. #include <AK/Noncopyable.h>
  10. #include <AK/StringView.h>
  11. #include <LibJS/Forward.h>
  12. namespace JS {
  13. #define JS_CELL(class_, base_class) \
  14. public: \
  15. using Base = base_class; \
  16. virtual StringView class_name() const override \
  17. { \
  18. return #class_##sv; \
  19. }
  20. class Cell {
  21. AK_MAKE_NONCOPYABLE(Cell);
  22. AK_MAKE_NONMOVABLE(Cell);
  23. public:
  24. virtual void initialize(Realm&) { }
  25. virtual ~Cell() = default;
  26. bool is_marked() const { return m_mark; }
  27. void set_marked(bool b) { m_mark = b; }
  28. enum class State {
  29. Live,
  30. Dead,
  31. };
  32. State state() const { return m_state; }
  33. void set_state(State state) { m_state = state; }
  34. virtual StringView class_name() const = 0;
  35. class Visitor {
  36. public:
  37. void visit(Cell* cell)
  38. {
  39. if (cell)
  40. visit_impl(*cell);
  41. }
  42. void visit(Value);
  43. protected:
  44. virtual void visit_impl(Cell&) = 0;
  45. virtual ~Visitor() = default;
  46. };
  47. virtual bool is_environment() const { return false; }
  48. virtual void visit_edges(Visitor&) { }
  49. Heap& heap() const;
  50. VM& vm() const;
  51. protected:
  52. Cell() = default;
  53. private:
  54. bool m_mark : 1 { false };
  55. State m_state : 7 { State::Live };
  56. };
  57. }
  58. template<>
  59. struct AK::Formatter<JS::Cell> : AK::Formatter<FormatString> {
  60. ErrorOr<void> format(FormatBuilder& builder, JS::Cell const* cell)
  61. {
  62. if (!cell)
  63. return builder.put_string("Cell{nullptr}"sv);
  64. return Formatter<FormatString>::format(builder, "{}({})"sv, cell->class_name(), cell);
  65. }
  66. };