node_store.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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_STORE_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_NODE_STORE_H_
  6. #include <tuple>
  7. #include "common/check.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/semantics/node_ref.h"
  10. #include "toolchain/semantics/nodes/binary_operator.h"
  11. #include "toolchain/semantics/nodes/function.h"
  12. #include "toolchain/semantics/nodes/integer_literal.h"
  13. #include "toolchain/semantics/nodes/return.h"
  14. #include "toolchain/semantics/nodes/set_name.h"
  15. namespace Carbon::Semantics {
  16. // Provides storage for nodes, indexed by Nodes.
  17. //
  18. // This uses templating versus either a macro or repeated functions to provide
  19. // per-type storage.
  20. template <typename... StoredNodeT>
  21. class NodeStoreBase {
  22. public:
  23. // Stores the provided node, returning a pointer to it.
  24. template <typename NodeT>
  25. auto Store(NodeT node) -> NodeRef {
  26. auto& node_store = std::get<static_cast<size_t>(NodeT::Kind)>(node_stores_);
  27. NodeStoreIndex index(node_store.size());
  28. node_store.push_back(node);
  29. return NodeRef(NodeT::Kind, index);
  30. }
  31. // Returns the requested node. Requires that the pointer is valid for this
  32. // store.
  33. template <typename NodeT>
  34. auto Get(NodeRef node_ref) const -> const NodeT& {
  35. CARBON_CHECK(node_ref.index_.index >= 0);
  36. CARBON_CHECK(node_ref.kind_ == NodeT::Kind)
  37. << "Kind mismatch: " << static_cast<int>(node_ref.kind_) << " vs "
  38. << static_cast<int>(NodeT::Kind);
  39. auto& node_store = std::get<static_cast<size_t>(NodeT::Kind)>(node_stores_);
  40. CARBON_CHECK(static_cast<size_t>(node_ref.index_.index) <
  41. node_store.size());
  42. return node_store[node_ref.index_.index];
  43. }
  44. private:
  45. std::tuple<llvm::SmallVector<StoredNodeT, 0>...> node_stores_;
  46. };
  47. using NodeStore =
  48. NodeStoreBase<BinaryOperator, Function, IntegerLiteral, Return, SetName>;
  49. } // namespace Carbon::Semantics
  50. #endif // CARBON_TOOLCHAIN_SEMANTICS_NODE_STORE_H_