semantics_node_kind.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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_SEMANTICS_NODE_KIND_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_KIND_H_
  6. #include <cstdint>
  7. #include "common/ostream.h"
  8. namespace Carbon {
  9. class SemanticsNodeKind {
  10. private:
  11. // Note that this must be declared earlier in the class so that its type can
  12. // be used, for example in the conversion operator.
  13. enum class KindEnum : uint8_t {
  14. #define CARBON_SEMANTICS_NODE_KIND(Name, ...) Name,
  15. #include "toolchain/semantics/semantics_node_kind.def"
  16. };
  17. public:
  18. // `clang-format` has a bug with spacing around `->` returns in macros. See
  19. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  20. #define CARBON_SEMANTICS_NODE_KIND(Name, ...) \
  21. static constexpr auto Name()->SemanticsNodeKind { \
  22. return SemanticsNodeKind(KindEnum::Name); \
  23. }
  24. #include "toolchain/semantics/semantics_node_kind.def"
  25. // The default constructor is deleted because objects of this type should
  26. // always be constructed using the above factory functions for each unique
  27. // kind.
  28. SemanticsNodeKind() = delete;
  29. // Gets a friendly name for the token for logging or debugging.
  30. [[nodiscard]] auto name() const -> llvm::StringRef;
  31. // Enable conversion to our private enum, including in a `constexpr` context,
  32. // to enable usage in `switch` and `case`. The enum remains private and
  33. // nothing else should be using this function.
  34. // NOLINTNEXTLINE(google-explicit-constructor)
  35. constexpr operator KindEnum() const { return kind_; }
  36. void Print(llvm::raw_ostream& out) const { out << name(); }
  37. private:
  38. constexpr explicit SemanticsNodeKind(KindEnum k) : kind_(k) {}
  39. KindEnum kind_;
  40. };
  41. // We expect the node kind to fit compactly into 8 bits.
  42. static_assert(sizeof(SemanticsNodeKind) == 1, "Kind objects include padding!");
  43. } // namespace Carbon
  44. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_KIND_H_