A handy, tiny but powerful compile-time reflection system for C++.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Tref.hpp 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. // Tref: A *T*iny compile time *ref*lection system.
  2. /***********************************************************************
  3. Copyright 2019-2020 crazybie<soniced@sina.com>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. this software and associated documentation files (the "Software"), to deal in
  6. the Software without restriction, including without limitation the rights to
  7. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  8. the Software, and to permit persons to whom the Software is furnished to do so,
  9. subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  14. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  15. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  16. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. */
  19. #pragma once
  20. #include <array>
  21. #include <string_view>
  22. #include <tuple>
  23. #include <type_traits>
  24. #define _TrefHasTref
  25. #define _TrefVersion 0x010000
  26. #ifdef _MSC_VER
  27. #define __TrefCxxVersion _MSVC_LANG
  28. #else
  29. #define __TrefCxxVersion __cplusplus
  30. #endif
  31. #if __TrefCxxVersion < 201700L
  32. #error "Need a c++17 compiler"
  33. #endif
  34. namespace tref {
  35. namespace imp {
  36. using namespace std;
  37. //////////////////////////////////////////////////////////////////////////
  38. //
  39. // Common facility
  40. //
  41. //////////////////////////////////////////////////////////////////////////
  42. template <typename T>
  43. struct Type {
  44. using type = T;
  45. };
  46. template <size_t L, size_t... R>
  47. constexpr auto tail(index_sequence<L, R...>) {
  48. return index_sequence<R...>();
  49. };
  50. // member pointer trait
  51. template <class C>
  52. struct member_pointer_trait {
  53. using enclosing_class_t = void;
  54. using member_t = void;
  55. };
  56. template <class T, class C>
  57. struct member_pointer_trait<T C::*> {
  58. using member_t = T;
  59. using enclosing_class_t = C;
  60. };
  61. template <class T>
  62. using member_t = typename member_pointer_trait<T>::member_t;
  63. template <class T>
  64. using enclosing_class_t = typename member_pointer_trait<T>::enclosing_class_t;
  65. // function trait
  66. template <typename T>
  67. struct func_trait : func_trait<decltype(&T::operator())> {};
  68. template <typename R, typename C, typename... A>
  69. struct func_trait<R (C::*)(A...) const> {
  70. using args_t = tuple<A...>;
  71. static constexpr auto args_count = sizeof...(A);
  72. using ret_t = R;
  73. };
  74. template <typename R, typename C, typename... A>
  75. struct func_trait<R (C::*)(A...)> {
  76. using args_t = tuple<A...>;
  77. static constexpr auto args_count = sizeof...(A);
  78. using ret_t = R;
  79. };
  80. // function overloading helper
  81. template <typename... Args>
  82. struct Overload {
  83. template <typename R, typename T>
  84. constexpr auto operator()(R (T::*ptr)(Args...)) const {
  85. return ptr;
  86. }
  87. template <typename R, typename T>
  88. constexpr auto operator()(R (T::*ptr)(Args...) const) const {
  89. return ptr;
  90. }
  91. template <typename R>
  92. constexpr auto operator()(R (*ptr)(Args...)) const {
  93. return ptr;
  94. }
  95. };
  96. template <typename... Args>
  97. constexpr Overload<Args...> overload_v{};
  98. // common macros
  99. #define _TrefReturn(...) \
  100. ->decltype(__VA_ARGS__) { return __VA_ARGS__; }
  101. #define _TrefMsvcExpand(...) __VA_ARGS__
  102. #define _TrefDelay(X, ...) _TrefMsvcExpand(X(__VA_ARGS__))
  103. #define _TrefDelay2(X, ...) _TrefMsvcExpand(X(__VA_ARGS__))
  104. #define _TrefFirst(...) _TrefMsvcExpand(_TrefFirst2(__VA_ARGS__))
  105. #define _TrefFirst2(A, ...) A
  106. #define _TrefSecond(...) _TrefMsvcExpand(_TrefSecond2(__VA_ARGS__))
  107. #define _TrefSecond2(A, B, ...) B
  108. #define _TrefTail(A, ...) __VA_ARGS__
  109. #define _TrefStringify(...) _TrefStringify2(__VA_ARGS__)
  110. #define _TrefStringify2(...) #__VA_ARGS__
  111. #define _TrefRemoveParen(A) \
  112. _TrefDelay(_TrefRemoveParen2, _TrefRemoveParenHelper A)
  113. #define _TrefRemoveParen2(...) \
  114. _TrefDelay2(_TrefTail, _TrefRemoveParenHelper##__VA_ARGS__)
  115. #define _TrefRemoveParenHelper(...) _, __VA_ARGS__
  116. #define _TrefRemoveParenHelper_TrefRemoveParenHelper _,
  117. #define _TrefFirstRemoveParen(X) _TrefFirst(_TrefRemoveParen(X))
  118. #define _TrefSecondRemoveParen(X) _TrefSecond(_TrefRemoveParen(X))
  119. // macro version of map
  120. #define _TrefMap(f, arg1, ...) \
  121. _TrefMsvcExpand(_TrefDelay(_TrefChooseMap, _TrefCount(__VA_ARGS__))( \
  122. f, arg1, __VA_ARGS__))
  123. #define _TrefChooseMap(N) _TrefMap##N
  124. #define _TrefMap1(m, a, x) m(a, x)
  125. #define _TrefMap2(m, a, x, ...) \
  126. m(a, x) _TrefMsvcExpand(_TrefMap1(m, a, __VA_ARGS__))
  127. #define _TrefMap3(m, a, x, ...) \
  128. m(a, x) _TrefMsvcExpand(_TrefMap2(m, a, __VA_ARGS__))
  129. #define _TrefMap4(m, a, x, ...) \
  130. m(a, x) _TrefMsvcExpand(_TrefMap3(m, a, __VA_ARGS__))
  131. #define _TrefMap5(m, a, x, ...) \
  132. m(a, x) _TrefMsvcExpand(_TrefMap4(m, a, __VA_ARGS__))
  133. #define _TrefMap6(m, a, x, ...) \
  134. m(a, x) _TrefMsvcExpand(_TrefMap5(m, a, __VA_ARGS__))
  135. #define _TrefMap7(m, a, x, ...) \
  136. m(a, x) _TrefMsvcExpand(_TrefMap6(m, a, __VA_ARGS__))
  137. #define _TrefMap8(m, a, x, ...) \
  138. m(a, x) _TrefMsvcExpand(_TrefMap7(m, a, __VA_ARGS__))
  139. #define _TrefMap9(m, a, x, ...) \
  140. m(a, x) _TrefMsvcExpand(_TrefMap8(m, a, __VA_ARGS__))
  141. #define _TrefMap10(m, a, x, ...) \
  142. m(a, x) _TrefMsvcExpand(_TrefMap9(m, a, __VA_ARGS__))
  143. #define _TrefMap11(m, a, x, ...) \
  144. m(a, x) _TrefMsvcExpand(_TrefMap10(m, a, __VA_ARGS__))
  145. #define _TrefMap12(m, a, x, ...) \
  146. m(a, x) _TrefMsvcExpand(_TrefMap11(m, a, __VA_ARGS__))
  147. #define _TrefMap13(m, a, x, ...) \
  148. m(a, x) _TrefMsvcExpand(_TrefMap12(m, a, __VA_ARGS__))
  149. #define _TrefMap14(m, a, x, ...) \
  150. m(a, x) _TrefMsvcExpand(_TrefMap13(m, a, __VA_ARGS__))
  151. #define _TrefMap15(m, a, x, ...) \
  152. m(a, x) _TrefMsvcExpand(_TrefMap14(m, a, __VA_ARGS__))
  153. #define _TrefMap16(m, a, x, ...) \
  154. m(a, x) _TrefMsvcExpand(_TrefMap15(m, a, __VA_ARGS__))
  155. #define _TrefMap17(m, a, x, ...) \
  156. m(a, x) _TrefMsvcExpand(_TrefMap16(m, a, __VA_ARGS__))
  157. #define _TrefMap18(m, a, x, ...) \
  158. m(a, x) _TrefMsvcExpand(_TrefMap17(m, a, __VA_ARGS__))
  159. #define _TrefMap19(m, a, x, ...) \
  160. m(a, x) _TrefMsvcExpand(_TrefMap18(m, a, __VA_ARGS__))
  161. #define _TrefMap20(m, a, x, ...) \
  162. m(a, x) _TrefMsvcExpand(_TrefMap19(m, a, __VA_ARGS__))
  163. #define _TrefMap21(m, a, x, ...) \
  164. m(a, x) _TrefMsvcExpand(_TrefMap20(m, a, __VA_ARGS__))
  165. #define _TrefMap22(m, a, x, ...) \
  166. m(a, x) _TrefMsvcExpand(_TrefMap21(m, a, __VA_ARGS__))
  167. #define _TrefMap23(m, a, x, ...) \
  168. m(a, x) _TrefMsvcExpand(_TrefMap22(m, a, __VA_ARGS__))
  169. #define _TrefMap24(m, a, x, ...) \
  170. m(a, x) _TrefMsvcExpand(_TrefMap23(m, a, __VA_ARGS__))
  171. #define _TrefMap25(m, a, x, ...) \
  172. m(a, x) _TrefMsvcExpand(_TrefMap24(m, a, __VA_ARGS__))
  173. #define _TrefMap26(m, a, x, ...) \
  174. m(a, x) _TrefMsvcExpand(_TrefMap25(m, a, __VA_ARGS__))
  175. #define _TrefMap27(m, a, x, ...) \
  176. m(a, x) _TrefMsvcExpand(_TrefMap26(m, a, __VA_ARGS__))
  177. #define _TrefMap28(m, a, x, ...) \
  178. m(a, x) _TrefMsvcExpand(_TrefMap27(m, a, __VA_ARGS__))
  179. #define _TrefMap29(m, a, x, ...) \
  180. m(a, x) _TrefMsvcExpand(_TrefMap28(m, a, __VA_ARGS__))
  181. #define _TrefMap30(m, a, x, ...) \
  182. m(a, x) _TrefMsvcExpand(_TrefMap29(m, a, __VA_ARGS__))
  183. #define _TrefEvaluateCount(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, \
  184. _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, \
  185. _23, _24, _25, _26, _27, _28, _29, _30, N, ...) \
  186. N
  187. #define _TrefCount(...) \
  188. _TrefMsvcExpand(_TrefEvaluateCount( \
  189. __VA_ARGS__, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, \
  190. 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
  191. //////////////////////////////////////////////////////////////////////////
  192. //
  193. // Core facility
  194. //
  195. //////////////////////////////////////////////////////////////////////////
  196. template <int N = 255>
  197. struct Id : Id<N - 1> {
  198. enum { value = N };
  199. };
  200. template <>
  201. struct Id<0> {
  202. enum { value = 0 };
  203. };
  204. constexpr auto invalid_index = 0;
  205. template <typename C, typename Tag>
  206. tuple<Id<invalid_index>> _tref_state(C**, Tag, Id<0> id);
  207. // use macro to delay the evaluation
  208. #define _TrefStateCnt(C, Tag) \
  209. std::tuple_element_t<0, \
  210. decltype(_tref_state((_TrefRemoveParen(C)**)0, Tag{}, \
  211. tref::imp::Id<>{}))>::value
  212. #define _TrefStatePush(C, Tag, ...) \
  213. constexpr auto _tref_state(_TrefRemoveParen(C)**, Tag, \
  214. tref::imp::Id<_TrefStateCnt(C, Tag) + 1> id) \
  215. _TrefReturn(std::tuple(id, __VA_ARGS__))
  216. template <class C, class Tag, int idx>
  217. constexpr auto get_state() {
  218. return _tref_state((C**)0, Tag{}, Id<idx>{});
  219. }
  220. template <class C, class Tag, class F, size_t... Is>
  221. constexpr bool state_fold(index_sequence<Is...>, F&& f) {
  222. return (f(get<1>(get_state<C, Tag, Is>())) && ...);
  223. }
  224. template <typename C, typename Tag, typename F>
  225. constexpr bool each_state(F f) {
  226. constexpr auto cnt = _TrefStateCnt(C, Tag);
  227. if constexpr (cnt > 0) {
  228. return state_fold<C, Tag>(tail(make_index_sequence<cnt + 1>{}), f);
  229. } else
  230. return true;
  231. };
  232. //////////////////////////////////////////////////////////////////////////
  233. //
  234. // class reflection
  235. //
  236. //////////////////////////////////////////////////////////////////////////
  237. struct DummyBase;
  238. struct FieldTag {};
  239. struct MemberTypeTag {};
  240. struct SubclassTag {};
  241. void _tref_class_info(void*);
  242. template <typename T>
  243. constexpr auto is_reflected_v =
  244. !std::is_same_v<decltype(_tref_class_info((T**)0)), void>;
  245. // Use function to delay the evaluation. (for non-conformance mode of MSVC)
  246. template <typename T>
  247. constexpr auto class_info() {
  248. return _tref_class_info((T**)0);
  249. };
  250. // Use macro to delay the evaluation. (for non-conformance mode of MSVC)
  251. #define _TrefBaseOf(T) \
  252. typename decltype(tref::imp::class_info<_TrefRemoveParen(T)>())::base_t
  253. template <typename T>
  254. constexpr auto has_base_class_v =
  255. is_reflected_v<T> ? !std::is_same_v<_TrefBaseOf(T), DummyBase> : false;
  256. // Meta for Member
  257. template <typename T, typename Meta>
  258. struct FieldInfo {
  259. using enclosing_class_t = imp::enclosing_class_t<T>;
  260. using member_t = imp::member_t<T>;
  261. static constexpr auto is_member_v = !is_same_v<enclosing_class_t, void>;
  262. int index;
  263. string_view name;
  264. // Possible values:
  265. // 1. Address of member variables & functions
  266. // 2. Type<T> for member type T: use decltype(value)::type to retrive it.
  267. T value;
  268. Meta meta;
  269. constexpr FieldInfo(int idx, string_view n, T a, Meta m)
  270. : index{idx}, name{n}, value{a}, meta{m} {}
  271. };
  272. // Meta for class
  273. template <typename T, typename Base, typename Meta>
  274. struct ClassInfo {
  275. using class_t = T;
  276. using base_t = Base;
  277. string_view name;
  278. size_t size;
  279. Type<Base> base;
  280. Meta meta;
  281. constexpr ClassInfo(T*, string_view n, size_t sz, Type<Base> b, Meta&& m)
  282. : name{n}, size{sz}, base{b}, meta{move(m)} {
  283. if constexpr (!is_same_v<Base, DummyBase>) {
  284. static_assert(is_base_of_v<Base, class_t>, "invalid base class");
  285. }
  286. }
  287. template <typename Tag, typename F>
  288. constexpr bool each_r(F&& f, int level = 0) const {
  289. auto next =
  290. each_state<T, Tag>([&](const auto& info) { return f(info, level); });
  291. if (next)
  292. if constexpr (!is_same_v<Base, DummyBase>)
  293. return class_info<Base>().template each_r<Tag>(f, level + 1);
  294. return next;
  295. }
  296. // Iterate through the members recursively.
  297. // @param f: [](MemberInfo info, int level) -> bool, return false to stop the
  298. // iterating.
  299. template <typename F>
  300. constexpr bool each_field(F&& f) const {
  301. return each_r<FieldTag>(f);
  302. }
  303. constexpr int get_field_index(string_view name) const {
  304. int idx = invalid_index;
  305. each_field([&](auto info, int) {
  306. if (info.name == name) {
  307. idx = info.index;
  308. return false;
  309. }
  310. return true;
  311. });
  312. return idx;
  313. }
  314. template <int index>
  315. constexpr auto get_field() const {
  316. return get<1>(get_state<T, FieldTag, index>());
  317. }
  318. // Iterate through the subclasses recursively.
  319. // @param F: [](ClassInfo info, int level) -> bool, return false to stop the
  320. // iterating.
  321. template <typename F>
  322. constexpr bool each_subclass(F&& f, int level = 0) const {
  323. return each_state<T, SubclassTag>([&](auto info) {
  324. using S = typename decltype(info)::type;
  325. return f(class_info<S>(), level) &&
  326. class_info<S>().each_subclass(f, level + 1);
  327. });
  328. }
  329. // Iterate through the member types.
  330. // @param F: [](MemberInfo info) -> bool, return false to stop the
  331. // iterating.
  332. template <typename F>
  333. constexpr bool each_member_type(F&& f) const {
  334. return each_r<MemberTypeTag>(f);
  335. }
  336. };
  337. #define _TrefClassMetaImp(T, Base, meta) \
  338. constexpr auto _tref_class_info(_TrefRemoveParen(T)**) { \
  339. return tref::imp::ClassInfo{ \
  340. (_TrefRemoveParen(T)*)0, _TrefStringify(_TrefRemoveParen(T)), \
  341. sizeof(_TrefRemoveParen(T)), \
  342. tref::imp::Type<_TrefRemoveParen(Base)>{}, meta}; \
  343. }
  344. #define _TrefClassMeta(T, Base, meta) friend _TrefClassMetaImp(T, Base, meta)
  345. #define _TrefPushFieldImp(T, Tag, name, val, meta) \
  346. _TrefStatePush(T, Tag, tref::imp::FieldInfo{id.value, name, val, meta})
  347. //////////////////////////////////////////////////////////////////////////
  348. //
  349. // macros for class reflection
  350. //
  351. //////////////////////////////////////////////////////////////////////////
  352. // sub type
  353. template <typename T, class = void_t<>>
  354. struct get_parent {
  355. using type = DummyBase;
  356. };
  357. template <typename T>
  358. struct get_parent<T, void_t<typename T::__parent_t>> {
  359. using type = typename T::__parent_t;
  360. };
  361. #define _TrefSubType(T) \
  362. _TrefSubTypeImp(T, typename tref::imp::get_parent<_TrefRemoveParen(T)>::type)
  363. #define _TrefSubTypeImp(T, Base) \
  364. _TrefStatePush(Base, tref::imp::SubclassTag, tref::imp::Type<T>{})
  365. //
  366. #define _TrefTypeCommon(T, Base, meta) \
  367. private: \
  368. using self_t = _TrefRemoveParen(T); \
  369. \
  370. public: \
  371. using __parent_t = self_t; \
  372. _TrefClassMeta(T, Base, meta);
  373. // Just reflect the type.
  374. #define _TrefType(T) _TrefTypeWithMeta(T, nullptr)
  375. #define _TrefTypeWithMeta(T, meta) \
  376. private: \
  377. using __base_t = typename tref::imp::get_parent<_TrefRemoveParen(T)>::type; \
  378. _TrefTypeCommon(T, __base_t, meta);
  379. // reflect member variable & function
  380. #define _TrefField1(t) _TrefFieldWithMeta2(t, nullptr)
  381. #define _TrefFieldWithMeta2(t, meta) _TrefFieldWithMeta2Imp(self_t, t, meta)
  382. #define _TrefFieldWithMeta2Imp(T, t, meta) \
  383. _TrefPushFieldImp(T, tref::imp::FieldTag, \
  384. _TrefStringify(_TrefRemoveParen(t)), \
  385. &T::_TrefRemoveParen(t), meta)
  386. // provide arguments for overloaded function
  387. #define _TrefField2(t, sig) _TrefFieldWithMeta3(t, sig, nullptr)
  388. #define _TrefFieldWithMeta3(t, sig, meta) \
  389. _TrefFieldWithMeta3Imp(self_t, t, sig, meta)
  390. #define _TrefFieldWithMeta3Imp(T, t, sig, meta) \
  391. _TrefPushFieldImp( \
  392. T, tref::imp::FieldTag, _TrefStringify(_TrefRemoveParen(t)), \
  393. tref::imp::overload_v<_TrefRemoveParen(sig)>(&T::_TrefRemoveParen(t)), \
  394. meta)
  395. // auto select from _TrefField1 or _TrefField2 by argument count
  396. #define _TrefFieldImp(...) \
  397. _TrefMsvcExpand( \
  398. _TrefDelay(_TrefChooseField, _TrefCount(__VA_ARGS__))(__VA_ARGS__))
  399. #define _TrefChooseField(N) _TrefField##N
  400. #define _TrefField(...) friend _TrefFieldImp(__VA_ARGS__)
  401. // auto select from _TrefFieldWithMeta2 or _TrefFieldWithMeta3 by argument
  402. // count
  403. #define _TrefFieldWithMetaImp(...) \
  404. _TrefMsvcExpand(_TrefDelay(_TrefChooseFieldWithMeta, \
  405. _TrefCount(__VA_ARGS__))(__VA_ARGS__))
  406. #define _TrefChooseFieldWithMeta(N) _TrefFieldWithMeta##N
  407. #define _TrefFieldWithMeta(...) friend _TrefFieldWithMetaImp(__VA_ARGS__)
  408. // reflect member type
  409. #define _TrefMemberTypeImp(T) _TrefMemberTypeWithMetaImp(T, nullptr)
  410. #define _TrefMemberTypeWithMetaImp(T, meta) \
  411. _TrefPushFieldImp(self_t, tref::imp::MemberTypeTag, \
  412. _TrefStringify(_TrefRemoveParen(T)), \
  413. tref::imp::Type<_TrefRemoveParen(T)>{}, meta)
  414. #define _TrefMemberType(T) friend _TrefMemberTypeImp(T)
  415. #define _TrefMemberTypeWithMeta(T, meta) \
  416. friend _TrefMemberTypeWithMetaImp(T, meta)
  417. //////////////////////////////////////////////////////////////////////////
  418. //
  419. // enum reflection
  420. //
  421. //////////////////////////////////////////////////////////////////////////
  422. struct EnumValueConvertor {
  423. template <typename T>
  424. constexpr EnumValueConvertor(T v) : value((size_t)v) {
  425. static_assert(sizeof(T) <= sizeof(value));
  426. }
  427. template <typename U>
  428. constexpr EnumValueConvertor operator=(U) {
  429. return *this;
  430. }
  431. template <typename U>
  432. constexpr operator U() {
  433. static_assert(is_enum_v<U>);
  434. return (U)value;
  435. }
  436. size_t value = 0;
  437. };
  438. template <typename T, typename Meta>
  439. struct EnumItem {
  440. string_view name;
  441. T value;
  442. Meta meta;
  443. };
  444. template <typename T, size_t N, typename ItemMeta>
  445. using EnumItems = array<EnumItem<T, ItemMeta>, N>;
  446. template <typename T, size_t N, typename Meta, typename ItemMeta>
  447. struct EnumInfo {
  448. using enum_t = T;
  449. string_view name;
  450. size_t size;
  451. EnumItems<T, N, ItemMeta> items;
  452. Meta meta;
  453. // @param f: [](string_view name, enum_t val)-> bool, return false to stop
  454. // the iterating.
  455. //
  456. // NOTE: the name.data() is not the name of the item, please use
  457. // string(name.data(), name.size()).
  458. template <typename F>
  459. constexpr auto each_item(F&& f) const {
  460. for (auto& e : items) {
  461. if (!f(e))
  462. return false;
  463. }
  464. return true;
  465. }
  466. static constexpr auto npos = -1;
  467. constexpr int index_of_value(T v) {
  468. auto i = 0;
  469. for (auto& e : items) {
  470. if (e.value == v) {
  471. return i;
  472. }
  473. i++;
  474. }
  475. return npos;
  476. }
  477. constexpr int index_of_name(string_view n) {
  478. auto i = 0;
  479. for (auto& e : items) {
  480. if (e.name == n) {
  481. return i;
  482. }
  483. i++;
  484. }
  485. return npos;
  486. }
  487. };
  488. template <typename T, int N, typename Meta, typename ItemMeta>
  489. constexpr auto makeEnumInfo(string_view name,
  490. size_t size,
  491. const EnumItems<T, N, ItemMeta>& items,
  492. Meta meta) {
  493. return EnumInfo<T, N, Meta, ItemMeta>{name, size, items, meta};
  494. }
  495. void* _tref_enum_info(void*);
  496. template <typename T, typename = enable_if_t<is_enum_v<T>, bool>>
  497. constexpr auto enum_info() {
  498. return _tref_enum_info((T**)0);
  499. };
  500. // Use it out of class.
  501. #define _TrefEnum(T, ...) _TrefEnumWithMeta(T, nullptr, __VA_ARGS__)
  502. #define _TrefEnumWithMeta(T, meta, ...) \
  503. enum class T { __VA_ARGS__ }; \
  504. _TrefEnumImpWithMeta(T, meta, __VA_ARGS__)
  505. // Use it inside of class.
  506. #define _TrefMemberEnum(T, ...) _TrefMemberEnumWithMeta(T, 0, __VA_ARGS__)
  507. #define _TrefMemberEnumWithMeta(T, meta, ...) \
  508. enum class T { __VA_ARGS__ }; \
  509. friend _TrefEnumImpWithMeta(T, meta, __VA_ARGS__)
  510. // Reflect enum items of already defined enum.
  511. #define _TrefEnumImp(T, ...) _TrefEnumImpWithMeta(T, nullptr, __VA_ARGS__)
  512. #define _TrefEnumImpWithMeta(T, meta, ...) \
  513. constexpr auto _tref_enum_info(_TrefRemoveParen(T)**) { \
  514. return tref::imp::EnumInfo<_TrefRemoveParen(T), _TrefCount(__VA_ARGS__), \
  515. decltype(meta), nullptr_t>{ \
  516. _TrefStringify(_TrefRemoveParen(T)), \
  517. sizeof(_TrefRemoveParen(T)), \
  518. {_TrefEnumStringize(T, __VA_ARGS__)}, \
  519. std::move(meta)}; \
  520. }
  521. #define _TrefEnumStringize(P, ...) \
  522. _TrefMsvcExpand(_TrefMap(_TrefEnumStringizeSingle, P, __VA_ARGS__))
  523. #define _TrefEnumStringizeSingle(P, E) \
  524. tref::imp::EnumItem<_TrefRemoveParen(P), nullptr_t>{ \
  525. tref::imp::enum_trim_name(#E), \
  526. (tref::imp::EnumValueConvertor)_TrefRemoveParen(P)::_TrefRemoveParen(E), \
  527. nullptr},
  528. //////////////////////////////////////////////////////////////////////////
  529. // ex version support meta for enum items.
  530. #define _TrefMemberEnumEx(T, ...) _TrefMemberEnumWithMetaEx(T, 0, __VA_ARGS__)
  531. #define _TrefMemberEnumWithMetaEx(T, meta, ...) \
  532. _TrefEnumDefineEnum2(T, __VA_ARGS__); \
  533. friend _TrefEnumImpWithMetaEx(T, meta, __VA_ARGS__)
  534. #define _TrefEnumEx(T, ...) _TrefEnumWithMetaEx(T, nullptr, __VA_ARGS__)
  535. #define _TrefEnumWithMetaEx(T, meta, ...) \
  536. _TrefEnumDefineEnum2(T, __VA_ARGS__); \
  537. _TrefEnumImpWithMetaEx(T, meta, __VA_ARGS__)
  538. #define _TrefFirstArgAsEnumItemDef(P, E) _TrefFirstRemoveParen(E),
  539. #define _TrefEnumDefineEnum2(T, ...) \
  540. enum class T { \
  541. _TrefMsvcExpand(_TrefMap(_TrefFirstArgAsEnumItemDef, T, __VA_ARGS__)) \
  542. }
  543. #define _TrefEnumImpEx(T, ...) _TrefEnumImpWithMetaEx(T, 0, __VA_ARGS__)
  544. #define _TrefEnumImpWithMetaEx(T, meta, ...) \
  545. constexpr auto _tref_enum_info(_TrefRemoveParen(T)**) { \
  546. return tref::imp::makeEnumInfo<_TrefRemoveParen(T), \
  547. _TrefCount(__VA_ARGS__)>( \
  548. _TrefStringify(_TrefRemoveParen(T)), sizeof(_TrefRemoveParen(T)), \
  549. std::array{_TrefEnumStringize2(T, __VA_ARGS__)}, std::move(meta)); \
  550. }
  551. #define _TrefEnumStringize2(P, ...) \
  552. _TrefMsvcExpand(_TrefMap(_TrefEnumStringizeSingle2, P, __VA_ARGS__))
  553. #define _TrefEnumStringizeSingle2(P, E) \
  554. tref::imp::EnumItem<_TrefRemoveParen(P), \
  555. decltype(_TrefRemoveParen(_TrefSecondRemoveParen(E)))>{ \
  556. tref::imp::enum_trim_name(_TrefStringify(_TrefFirstRemoveParen(E))), \
  557. (tref::imp::EnumValueConvertor)_TrefRemoveParen(P)::_TrefRemoveParen( \
  558. _TrefFirstRemoveParen(E)), \
  559. _TrefRemoveParen(_TrefSecondRemoveParen(E))},
  560. /////////////////////////////////////
  561. constexpr string_view enum_trim_name(string_view s) {
  562. auto p = s.find_first_of('=');
  563. if (p != string_view::npos)
  564. p = s.rfind(' ', p);
  565. return s.substr(0, p);
  566. }
  567. template <typename T>
  568. constexpr auto enum_to_string(T v) {
  569. static_assert(is_enum_v<T>);
  570. for (auto& e : enum_info<T>().items) {
  571. if (e.value == v) {
  572. return e.name;
  573. }
  574. }
  575. return string_view{};
  576. }
  577. template <typename T>
  578. constexpr auto string_to_enum(string_view s, T default_) {
  579. static_assert(is_enum_v<T>);
  580. for (auto& e : enum_info<T>().items) {
  581. if (s == e.name) {
  582. return e.value;
  583. }
  584. }
  585. return default_;
  586. }
  587. template <typename T, typename Storage = unsigned int>
  588. struct Flags {
  589. static_assert(std::is_enum_v<T>);
  590. Storage value = 0;
  591. constexpr Flags() {}
  592. constexpr void clear() { value = 0; }
  593. constexpr bool hasFlag(T e) {
  594. assert(e < sizeof(value) * 8);
  595. return (value & (1 << static_cast<Storage>(e))) != 0;
  596. }
  597. constexpr void setFlag(T e) {
  598. assert(e < sizeof(value) * 8);
  599. value |= (1 << static_cast<Storage>(e));
  600. }
  601. constexpr void clearFlag(T e) {
  602. assert(e < sizeof(value) * 8);
  603. value &= ~(1 << static_cast<Storage>(e));
  604. }
  605. };
  606. } // namespace imp
  607. //////////////////////////////////////////////////////////////////////////
  608. //
  609. // public APIs
  610. //
  611. //////////////////////////////////////////////////////////////////////////
  612. #define TrefHasTref _TrefHasTref
  613. #define TrefVersion _TrefVersion
  614. using imp::class_info;
  615. using imp::ClassInfo;
  616. using imp::enclosing_class_t;
  617. using imp::FieldInfo;
  618. using imp::func_trait;
  619. using imp::has_base_class_v;
  620. using imp::is_reflected_v;
  621. using imp::member_t;
  622. using imp::overload_v;
  623. #define TrefType _TrefType
  624. #define TrefTypeWithMeta _TrefTypeWithMeta
  625. #define TrefSubType _TrefSubType
  626. #define TrefBaseOf _TrefBaseOf
  627. #define TrefField _TrefField
  628. #define TrefFieldWithMeta _TrefFieldWithMeta
  629. #define TrefMemberType _TrefMemberType
  630. #define TrefMemberTypeWithMeta _TrefMemberTypeWithMeta
  631. //////////////////////////
  632. // Reflect external types
  633. // NOTE: not support template.
  634. //////////////////////////
  635. #define TrefNoBase tref::imp::DummyBase
  636. #define TrefExternalTypeWithMeta _TrefClassMetaImp
  637. #define TrefExternalFieldWithMeta _TrefFieldWithMeta2Imp
  638. #define TrefExternalOverloadedFieldWithMeta _TrefFieldWithMeta3Imp
  639. #define TrefExternalSubType _TrefSubTypeImp
  640. /// enum
  641. using imp::enum_info;
  642. using imp::enum_to_string;
  643. using imp::Flags;
  644. using imp::string_to_enum;
  645. // ex version support meta for enum items.
  646. #define TrefEnum _TrefEnum
  647. #define TrefEnumEx _TrefEnumEx
  648. #define TrefEnumWithMeta _TrefEnumWithMeta
  649. #define TrefEnumWithMetaEx _TrefEnumWithMetaEx
  650. #define TrefMemberEnum _TrefMemberEnum
  651. #define TrefMemberEnumEx _TrefMemberEnumEx
  652. #define TrefMemberEnumWithMeta _TrefMemberEnumWithMeta
  653. #define TrefMemberEnumWithMetaEx _TrefMemberEnumWithMetaEx
  654. #define TrefExternalEnum _TrefEnumImp
  655. #define TrefExternalEnumEx _TrefEnumImpEx
  656. #define TrefExternalEnumWithMeta _TrefEnumImpWithMeta
  657. #define TrefExternalEnumWithMetaEx _TrefEnumImpWithMetaEx
  658. } // namespace tref