semantics_node_kind.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. friend auto operator==(SemanticsNodeKind lhs, SemanticsNodeKind rhs) -> bool {
  30. return lhs.kind_ == rhs.kind_;
  31. }
  32. friend auto operator!=(SemanticsNodeKind lhs, SemanticsNodeKind rhs) -> bool {
  33. return lhs.kind_ != rhs.kind_;
  34. }
  35. // Gets a friendly name for the token for logging or debugging.
  36. [[nodiscard]] auto name() const -> llvm::StringRef;
  37. // Enable conversion to our private enum, including in a `constexpr` context,
  38. // to enable usage in `switch` and `case`. The enum remains private and
  39. // nothing else should be using this function.
  40. // NOLINTNEXTLINE(google-explicit-constructor)
  41. constexpr operator KindEnum() const { return kind_; }
  42. void Print(llvm::raw_ostream& out) const { out << name(); }
  43. private:
  44. constexpr explicit SemanticsNodeKind(KindEnum k) : kind_(k) {}
  45. KindEnum kind_;
  46. };
  47. // We expect the node kind to fit compactly into 8 bits.
  48. static_assert(sizeof(SemanticsNodeKind) == 1, "Kind objects include padding!");
  49. } // namespace Carbon
  50. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_KIND_H_