node_ref.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_SEMANTICS_NODE_REF_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_NODE_REF_H_
  6. #include <cstdint>
  7. #include "common/ostream.h"
  8. #include "toolchain/semantics/node_kind.h"
  9. namespace Carbon::Semantics {
  10. // Type-safe storage of NodeStore indices.
  11. struct NodeStoreIndex {
  12. explicit NodeStoreIndex(int32_t index) : index(index) {}
  13. explicit operator int32_t() const { return index; }
  14. int32_t index;
  15. };
  16. // The standard structure for nodes.
  17. //
  18. // This flyweight pattern is used so that each subtype can be stored in its own
  19. // vector, minimizing memory consumption and heap fragmentation when large
  20. // quantities are being created.
  21. class NodeRef {
  22. public:
  23. NodeRef() : NodeRef(NodeKind::Invalid, NodeStoreIndex(-1)) {}
  24. auto kind() -> NodeKind { return kind_; }
  25. private:
  26. template <typename... StoredNodeT>
  27. friend class NodeStoreBase;
  28. NodeRef(NodeKind kind, NodeStoreIndex index) : kind_(kind), index_(index) {}
  29. NodeKind kind_;
  30. // The index of the named entity within its list.
  31. NodeStoreIndex index_;
  32. };
  33. } // namespace Carbon::Semantics
  34. #endif // CARBON_TOOLCHAIN_SEMANTICS_NODE_REF_H_