enum_base.h 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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_COMMON_ENUM_BASE_H_
  5. #define CARBON_COMMON_ENUM_BASE_H_
  6. #include <type_traits>
  7. #include "common/ostream.h"
  8. #include "llvm/ADT/StringRef.h"
  9. namespace Carbon::Internal {
  10. // CRTP-style base class used to define the common pattern of Carbon enum-like
  11. // classes. The result is a class with named constants similar to enumerators,
  12. // but that are normal classes, can contain other methods, and support a `name`
  13. // method and printing the enums. These even work in switch statements and
  14. // support `case MyEnum::Name:`.
  15. //
  16. // It is specifically designed to compose with X-MACRO style `.def` files that
  17. // stamp out all the enumerators.
  18. //
  19. // It also supports some opt-in APIs that classes can enable by `using` the
  20. // names to make them public: `AsInt` and `FromInt` allow converting to and from
  21. // the underlying type of the enumerator.
  22. //
  23. // Users must be in the `Carbon` namespace and should look like the following.
  24. //
  25. // In `my_kind.h`:
  26. // ```
  27. // CARBON_DEFINE_RAW_ENUM_CLASS(MyKind, uint8_t) {
  28. // #define CARBON_MY_KIND(Name) CARBON_RAW_ENUM_ENUMERATOR(Name)
  29. // #include ".../my_kind.def"
  30. // };
  31. //
  32. // class MyKind : public CARBON_ENUM_BASE(MyKind) {
  33. // public:
  34. // #define CARBON_MY_KIND(Name) CARBON_ENUM_CONSTANT_DECLARATION(Name)
  35. // #include ".../my_kind.def"
  36. // };
  37. //
  38. // #define CARBON_MY_KIND(Name) CARBON_ENUM_CONSTANT_DEFINITION(MyKind, Name)
  39. // #include ".../my_kind.def"
  40. // ```
  41. //
  42. // In `my_kind.cpp`:
  43. // ```
  44. // CARBON_DEFINE_ENUM_CLASS_NAMES(MyKind) = {
  45. // #define CARBON_MY_KIND(Name) CARBON_ENUM_CLASS_NAME_STRING(Name)
  46. // #include ".../my_kind.def"
  47. // };
  48. // ```
  49. template <typename DerivedT, typename EnumT, const llvm::StringLiteral Names[]>
  50. class EnumBase : public Printable<DerivedT> {
  51. public:
  52. // An alias for the raw enum type. This is an implementation detail and
  53. // should rarely be used directly, only when an actual enum type is needed.
  54. using RawEnumType = EnumT;
  55. using EnumType = DerivedT;
  56. using UnderlyingType = std::underlying_type_t<RawEnumType>;
  57. // Enable conversion to the raw enum type, including in a `constexpr` context,
  58. // to enable comparisons and usage in `switch` and `case`. The enum type
  59. // remains an implementation detail and nothing else should be using this
  60. // function.
  61. //
  62. // NOLINTNEXTLINE(google-explicit-constructor)
  63. constexpr operator RawEnumType() const { return value_; }
  64. // Conversion to bool is deleted to prevent direct use in an `if` condition
  65. // instead of comparing with another value.
  66. explicit operator bool() const = delete;
  67. // Returns the name of this value.
  68. //
  69. // This method will be automatically defined using the static `names` string
  70. // table in the base class, which is in turn will be populated for each
  71. // derived type using the macro helpers in this file.
  72. [[nodiscard]] auto name() const -> llvm::StringRef { return Names[AsInt()]; }
  73. // Prints this value using its name.
  74. auto Print(llvm::raw_ostream& out) const -> void { out << name(); }
  75. protected:
  76. // The default constructor is explicitly defaulted (and constexpr) as a
  77. // protected constructor to allow derived classes to be constructed but not
  78. // the base itself. This should only be used in the `Create` function below.
  79. constexpr EnumBase() = default;
  80. // Create an instance from the raw enumerator. Mainly used internally, but may
  81. // be exposed for unusual use cases.
  82. static constexpr auto Create(RawEnumType value) -> EnumType {
  83. EnumType result;
  84. result.value_ = value;
  85. return result;
  86. }
  87. // Convert to the underlying integer type. Derived types can choose to expose
  88. // this as part of their API.
  89. constexpr auto AsInt() const -> UnderlyingType {
  90. return static_cast<UnderlyingType>(value_);
  91. }
  92. // Convert from the underlying integer type. Derived types can choose to
  93. // expose this as part of their API.
  94. static constexpr auto FromInt(UnderlyingType value) -> EnumType {
  95. return Create(static_cast<RawEnumType>(value));
  96. }
  97. private:
  98. RawEnumType value_;
  99. };
  100. } // namespace Carbon::Internal
  101. // For use when multiple enums use the same list of names.
  102. #define CARBON_DEFINE_RAW_ENUM_CLASS_NO_NAMES(EnumClassName, UnderlyingType) \
  103. namespace Internal { \
  104. /* NOLINTNEXTLINE(bugprone-macro-parentheses) */ \
  105. enum class EnumClassName##RawEnum : UnderlyingType; \
  106. } \
  107. enum class Internal::EnumClassName##RawEnum : UnderlyingType
  108. // Use this before defining a class that derives from `EnumBase` to begin the
  109. // definition of the raw `enum class`. It should be followed by the body of that
  110. // raw enum class.
  111. #define CARBON_DEFINE_RAW_ENUM_CLASS(EnumClassName, UnderlyingType) \
  112. namespace Internal { \
  113. extern const llvm::StringLiteral EnumClassName##Names[]; \
  114. } \
  115. CARBON_DEFINE_RAW_ENUM_CLASS_NO_NAMES(EnumClassName, UnderlyingType)
  116. // In CARBON_DEFINE_RAW_ENUM_CLASS block, use this to generate each enumerator.
  117. #define CARBON_RAW_ENUM_ENUMERATOR(Name) Name,
  118. // Use this to compute the `Internal::EnumBase` specialization for a Carbon enum
  119. // class. It both computes the name of the raw enum and ensures all the
  120. // namespaces are correct.
  121. #define CARBON_ENUM_BASE(EnumClassName) \
  122. CARBON_ENUM_BASE_CRTP(EnumClassName, EnumClassName, EnumClassName)
  123. // This variant handles the case where the external name for the Carbon enum is
  124. // not the same as the name by which we refer to it from this context.
  125. #define CARBON_ENUM_BASE_CRTP(EnumClassName, LocalTypeNameForEnumClass, \
  126. EnumClassNameForNames) \
  127. ::Carbon::Internal::EnumBase<LocalTypeNameForEnumClass, \
  128. Internal::EnumClassName##RawEnum, \
  129. Internal::EnumClassNameForNames##Names>
  130. // Use this within the Carbon enum class body to generate named constant
  131. // declarations for each value.
  132. #define CARBON_ENUM_CONSTANT_DECLARATION(Name) static const EnumType Name;
  133. // Use this immediately after the Carbon enum class body to define each named
  134. // constant.
  135. #define CARBON_ENUM_CONSTANT_DEFINITION(EnumClassName, Name) \
  136. constexpr EnumClassName EnumClassName::Name = \
  137. EnumClassName::Create(RawEnumType::Name);
  138. // Alternatively, use this within the Carbon enum class body to declare and
  139. // define each named constant. Due to type completeness constraints, this will
  140. // only work if the enum-like class is templated.
  141. //
  142. // This requires the template to have a member named `Base` that names the
  143. // `EnumBase` base class.
  144. #define CARBON_INLINE_ENUM_CONSTANT_DEFINITION(Name) \
  145. static constexpr const typename Base::EnumType& Name = \
  146. Base::Create(Base::RawEnumType::Name);
  147. // Use this in the `.cpp` file for an enum class to start the definition of the
  148. // constant names array for each enumerator. It is followed by the desired
  149. // constant initializer.
  150. //
  151. // `clang-format` has a bug with spacing around `->` returns in macros. See
  152. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  153. #define CARBON_DEFINE_ENUM_CLASS_NAMES(EnumClassName) \
  154. constexpr llvm::StringLiteral Internal::EnumClassName##Names[]
  155. // Use this within the names array initializer to generate a string for each
  156. // name.
  157. #define CARBON_ENUM_CLASS_NAME_STRING(Name) #Name,
  158. #endif // CARBON_COMMON_ENUM_BASE_H_