forward.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // forward.h
  3. // reflection
  4. //
  5. // Created by Sam Jaffe on 7/3/22.
  6. // Copyright © 2022 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <functional>
  10. #include <map>
  11. #include <string>
  12. #include <type_traits>
  13. #include <typeindex>
  14. #include <unordered_map>
  15. namespace reflection {
  16. class Context;
  17. class ContextScope;
  18. class Object;
  19. class Scope;
  20. template <typename Obj, typename = void> class Reflection;
  21. template <typename T> class Proxy;
  22. template <typename T> class TypeCast;
  23. template <typename Func> using Cache = std::map<std::string_view, Func>;
  24. template <typename T> using TypeMap = std::unordered_map<std::type_index, T>;
  25. template <typename Obj>
  26. using Accessor = std::function<Object(Obj &, std::string)>;
  27. template <typename Obj>
  28. using Getter = std::function<Object(Obj const &, std::string)>;
  29. template <typename T> constexpr std::string_view Name = "";
  30. }
  31. #define reflect(object) reflection::Object(object, #object)
  32. #define INSTANTIATE_REFLECTION_IMPL(T, name, ...) \
  33. template <> constexpr std::string_view Name<T> = name; \
  34. template Cache<Accessor<T>> Reflection<T>::members_; \
  35. template Cache<Getter<T>> Reflection<T>::const_members_
  36. #define INSTANTIATE_REFLECTION(T, ...) \
  37. INSTANTIATE_REFLECTION_IMPL(T, ##__VA_ARGS__, #T)
  38. #define INSTANTIATE_REFLECTION_TYPECAST_IMPL(T, name, ...) \
  39. template <> constexpr std::string_view Name<T> = name; \
  40. template TypeMap<std::function<T(Object const &)>> TypeCast<T>::get_; \
  41. template TypeMap<std::function<void(Object &, T const &)>> TypeCast<T>::set_
  42. #define INSTANTIATE_REFLECTION_TYPECAST(T, ...) \
  43. INSTANTIATE_REFLECTION_TYPECAST_IMPL(T, ##__VA_ARGS__, #T)
  44. #if !defined(CONCAT)
  45. #define CONCAT_IMPL(A, B) A##B
  46. #define CONCAT(A, B) CONCAT_IMPL(A, B)
  47. #endif
  48. #define REFLECTION(T) \
  49. bool const CONCAT(reflection_, __LINE__) = ::reflection::Reflection<T>()
  50. #define REFLECTION_TYPE_CAST(T) \
  51. bool const CONCAT(type_cast_, __LINE__) = ::reflection::TypeCast<T>()
  52. #define IS_SCOPE_CONTAINER(C) \
  53. std::is_constructible_v<std::string_view, \
  54. decltype(*std::begin(std::declval<C>()))>