enum_base.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. // Users must be in the `Carbon` namespace and should look like the following.
  20. //
  21. // In `my_kind.h`:
  22. // ```
  23. // CARBON_DEFINE_RAW_ENUM_CLASS(MyKind, uint8_t) {
  24. // #define CARBON_MY_KIND(Name) CARBON_RAW_ENUM_ENUMERATOR(Name)
  25. // #include ".../my_kind.def"
  26. // };
  27. //
  28. // class MyKind : public CARBON_ENUM_BASE(MyKind) {
  29. // public:
  30. // #define CARBON_MY_KIND(Name) CARBON_ENUM_CONSTANT_DECL(Name)
  31. // #include ".../my_kind.def"
  32. //
  33. // // OPTIONAL: To support converting to and from the underlying type of
  34. // // the enumerator, add these lines:
  35. // using EnumBase::AsInt;
  36. // using EnumBase::FromInt;
  37. //
  38. // // OPTIONAL: To expose the ability to create an instance from the raw
  39. // // enumerator (for unusual use cases), add this:
  40. // using EnumBase::Make;
  41. //
  42. // // Plus, anything else you wish to include.
  43. // };
  44. //
  45. // #define CARBON_MY_KIND(Name) CARBON_ENUM_CONSTANT_DEFINITION(MyKind, Name)
  46. // #include ".../my_kind.def"
  47. // ```
  48. //
  49. // In `my_kind.cpp`:
  50. // ```
  51. // CARBON_DEFINE_ENUM_CLASS_NAMES(MyKind) = {
  52. // #define CARBON_MY_KIND(Name) CARBON_ENUM_CLASS_NAME_STRING(Name)
  53. // #include ".../my_kind.def"
  54. // };
  55. // ```
  56. //
  57. // The result of the above:
  58. // - An enum class (`RawEnumType`) defined in an `Internal` namespace with one
  59. // enumerator per call to CARBON_MY_KIND(Name) in `.../my_kind.def`, with name
  60. // `Name`. This won't generally be used directly, but may be needed for niche
  61. // use cases such as a template argument.
  62. // - A type `MyKind` that extends `Carbon::Internal::EnumBase`.
  63. // - `MyKind` includes all the public members of `EnumBase`, like `name` and
  64. // `Print`. For example, you might call `name()` to construct an error
  65. // message:
  66. // ```
  67. // auto ErrorMessage(MyKind k) -> std::string {
  68. // return k.name() + " not found";
  69. // }
  70. // ```
  71. // - `MyKind` includes all protected members of `EnumBase`, like `AsInt`,
  72. // `FromInt`. They will be part of the public API of `EnumBase` if they
  73. // were included in a `using` declaration.
  74. // - `MyKind` includes a member `static const MyKind Name;` per call to
  75. // `CARBON_MY_KIND(Name)` in `.../my_kind.def`. It will have the
  76. // corresponding value from `RawEnumType`. This is the primary way to create
  77. // an instance of `MyKind`. For example, it might be used like:
  78. // ```
  79. // ErrorMessage(MyKind::Name1);
  80. // ```
  81. // - `MyKind` includes an implicit conversion to the `RawEnumType`, returning
  82. // the value of a private field in `EnumBase`. This is used when writing a
  83. // `switch` statement, as in this example:
  84. // ```
  85. // auto MyFunction(MyKind k) -> void {
  86. // // Implicitly converts `k` and every `case` expression to
  87. // // `RawEnumType`:
  88. // switch (k) {
  89. // case MyKind::Name1:
  90. // // ...
  91. // break;
  92. //
  93. // case MyKind::Name2:
  94. // // ...
  95. // break;
  96. //
  97. // // No `default` case needed if the above cases are exhaustive.
  98. // // Prefer no `default` case when possible, to get an error if
  99. // // a case is skipped.
  100. // }
  101. // }
  102. // ```
  103. //
  104. template <typename DerivedT, typename EnumT, const llvm::StringLiteral Names[]>
  105. class EnumBase : public Printable<DerivedT> {
  106. public:
  107. // An alias for the raw enum type. This is an implementation detail and
  108. // should rarely be used directly, only when an actual enum type is needed.
  109. using RawEnumType = EnumT;
  110. using EnumType = DerivedT;
  111. using UnderlyingType = std::underlying_type_t<RawEnumType>;
  112. // Enable conversion to the raw enum type, including in a `constexpr` context,
  113. // to enable comparisons and usage in `switch` and `case`. The enum type
  114. // remains an implementation detail and nothing else should be using this
  115. // function.
  116. //
  117. // NOLINTNEXTLINE(google-explicit-constructor)
  118. constexpr operator RawEnumType() const { return value_; }
  119. // Conversion to bool is deleted to prevent direct use in an `if` condition
  120. // instead of comparing with another value.
  121. explicit operator bool() const = delete;
  122. // Returns the name of this value.
  123. //
  124. // This method will be automatically defined using the static `names` string
  125. // table in the base class, which is in turn will be populated for each
  126. // derived type using the macro helpers in this file.
  127. auto name() const -> llvm::StringRef { return Names[AsInt()]; }
  128. // Prints this value using its name.
  129. auto Print(llvm::raw_ostream& out) const -> void { out << name(); }
  130. protected:
  131. // The default constructor is explicitly defaulted (and constexpr) as a
  132. // protected constructor to allow derived classes to be constructed but not
  133. // the base itself. This should only be used in the `Make` function below.
  134. constexpr EnumBase() = default;
  135. // Create an instance from the raw enumerator. Mainly used internally, but may
  136. // be exposed for unusual use cases.
  137. static constexpr auto Make(RawEnumType value) -> EnumType {
  138. EnumType result;
  139. result.value_ = value;
  140. return result;
  141. }
  142. // Convert to the underlying integer type. Derived types can choose to expose
  143. // this as part of their API.
  144. constexpr auto AsInt() const -> UnderlyingType {
  145. return static_cast<UnderlyingType>(value_);
  146. }
  147. // Convert from the underlying integer type. Derived types can choose to
  148. // expose this as part of their API.
  149. static constexpr auto FromInt(UnderlyingType value) -> EnumType {
  150. return Make(static_cast<RawEnumType>(value));
  151. }
  152. private:
  153. RawEnumType value_;
  154. };
  155. } // namespace Carbon::Internal
  156. // For use when multiple enums use the same list of names.
  157. #define CARBON_DEFINE_RAW_ENUM_CLASS_NO_NAMES(EnumClassName, UnderlyingType) \
  158. namespace Internal { \
  159. enum class EnumClassName##RawEnum : UnderlyingType; \
  160. } \
  161. enum class Internal::EnumClassName##RawEnum : UnderlyingType
  162. // Use this before defining a class that derives from `EnumBase` to begin the
  163. // definition of the raw `enum class`. It should be followed by the body of that
  164. // raw enum class.
  165. #define CARBON_DEFINE_RAW_ENUM_CLASS(EnumClassName, UnderlyingType) \
  166. namespace Internal { \
  167. extern const llvm::StringLiteral EnumClassName##Names[]; \
  168. } \
  169. CARBON_DEFINE_RAW_ENUM_CLASS_NO_NAMES(EnumClassName, UnderlyingType)
  170. // In CARBON_DEFINE_RAW_ENUM_CLASS block, use this to generate each enumerator.
  171. #define CARBON_RAW_ENUM_ENUMERATOR(Name) Name,
  172. // Use this to compute the `Internal::EnumBase` specialization for a Carbon enum
  173. // class. It both computes the name of the raw enum and ensures all the
  174. // namespaces are correct.
  175. #define CARBON_ENUM_BASE(EnumClassName) \
  176. CARBON_ENUM_BASE_CRTP(EnumClassName, EnumClassName, EnumClassName)
  177. // This variant handles the case where the external name for the Carbon enum is
  178. // not the same as the name by which we refer to it from this context.
  179. #define CARBON_ENUM_BASE_CRTP(EnumClassName, LocalTypeNameForEnumClass, \
  180. EnumClassNameForNames) \
  181. ::Carbon::Internal::EnumBase<LocalTypeNameForEnumClass, \
  182. Internal::EnumClassName##RawEnum, \
  183. Internal::EnumClassNameForNames##Names>
  184. // Use this within the Carbon enum class body to generate named constant
  185. // declarations for each value.
  186. #define CARBON_ENUM_CONSTANT_DECL(Name) static const EnumType Name;
  187. // Use this immediately after the Carbon enum class body to define each named
  188. // constant.
  189. #define CARBON_ENUM_CONSTANT_DEFINITION(EnumClassName, Name) \
  190. constexpr EnumClassName EnumClassName::Name = \
  191. EnumClassName::Make(RawEnumType::Name);
  192. // Alternatively, use this within the Carbon enum class body to declare and
  193. // define each named constant. Due to type completeness constraints, this will
  194. // only work if the enum-like class is templated.
  195. //
  196. // This requires the template to have a member named `Base` that names the
  197. // `EnumBase` base class.
  198. #define CARBON_INLINE_ENUM_CONSTANT_DEFINITION(Name) \
  199. static constexpr const typename Base::EnumType& Name = \
  200. Base::Make(Base::RawEnumType::Name);
  201. // Use this in the `.cpp` file for an enum class to start the definition of the
  202. // constant names array for each enumerator. It is followed by the desired
  203. // constant initializer.
  204. //
  205. // `clang-format` has a bug with spacing around `->` returns in macros. See
  206. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  207. #define CARBON_DEFINE_ENUM_CLASS_NAMES(EnumClassName) \
  208. constexpr llvm::StringLiteral Internal::EnumClassName##Names[]
  209. // Use this within the names array initializer to generate a string for each
  210. // name.
  211. #define CARBON_ENUM_CLASS_NAME_STRING(Name) #Name,
  212. #endif // CARBON_COMMON_ENUM_BASE_H_