class.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. #pragma once
  2. #include "module.h"
  3. #include "type_traits.h"
  4. namespace pkbind {
  5. struct dynamic_attr {};
  6. template <typename T, typename Base = void>
  7. class class_ : public type {
  8. protected:
  9. handle m_scope;
  10. public:
  11. using type::type;
  12. using underlying_type = T;
  13. template <typename... Args>
  14. class_(handle scope, const char* name, const Args&... args) :
  15. type(py_newtype(name,
  16. std::is_same_v<Base, void> ? tp_object : type::of<Base>().index(),
  17. scope.ptr(),
  18. [](void* data) {
  19. static_cast<instance*>(data)->~instance();
  20. })),
  21. m_scope(scope) {
  22. m_type_map->try_emplace(typeid(T), this->index());
  23. auto& info = type_info::of<T>();
  24. info.name = name;
  25. py_newfunction(
  26. py_tpgetmagic(this->index(), py_MagicNames::__new__),
  27. "__new__(type, *args, **kwargs)",
  28. [](int, py_Ref stack) {
  29. auto cls = py_offset(stack, 0);
  30. [[maybe_unused]] auto args = py_offset(stack, 1);
  31. [[maybe_unused]] auto kwargs = py_offset(stack, 2);
  32. auto info = &type_info::of<T>();
  33. int slot = ((std::is_same_v<dynamic_attr, Args> || ...) ? -1 : 0);
  34. void* data = py_newobject(retv, steal<type>(cls).index(), slot, sizeof(instance));
  35. new (data) instance{instance::Flag::Own, operator new (info->size), info};
  36. return true;
  37. },
  38. nullptr,
  39. 0);
  40. }
  41. /// bind constructor
  42. template <typename... Args, typename... Extra>
  43. class_& def(impl::constructor<Args...>, const Extra&... extra) {
  44. if constexpr(!std::is_constructible_v<T, Args...>) {
  45. static_assert(std::is_constructible_v<T, Args...>, "Invalid constructor arguments");
  46. } else {
  47. impl::bind_function<true, false>(
  48. *this,
  49. "__init__",
  50. [](T* self, Args... args) {
  51. new (self) T(args...);
  52. },
  53. extra...);
  54. return *this;
  55. }
  56. }
  57. template <typename Fn, typename... Extra>
  58. class_& def(impl::factory<Fn> factory, const Extra&... extra) {
  59. using ret = callable_return_t<Fn>;
  60. if constexpr(!std::is_same_v<T, ret>) {
  61. static_assert(std::is_same_v<T, ret>, "Factory function must return the class type");
  62. } else {
  63. impl::bind_function<true, false>(*this, "__init__", factory.make(), extra...);
  64. return *this;
  65. }
  66. }
  67. /// bind member function
  68. template <typename Fn, typename... Extra>
  69. class_& def(const char* name, Fn&& f, const Extra&... extra) {
  70. using first = remove_cvref_t<std::tuple_element_t<0, callable_args_t<remove_cvref_t<Fn>>>>;
  71. constexpr bool is_first_base_of_v = std::is_base_of_v<first, T> || std::is_same_v<first, T>;
  72. if constexpr(!is_first_base_of_v) {
  73. static_assert(
  74. is_first_base_of_v,
  75. "If you want to bind member function, the first argument must be the base class");
  76. } else {
  77. impl::bind_function<true, false>(*this, name, std::forward<Fn>(f), extra...);
  78. }
  79. return *this;
  80. }
  81. /// bind operators
  82. template <typename Operator, typename... Extras>
  83. class_& def(Operator op, const Extras&... extras) {
  84. op.execute(*this, extras...);
  85. return *this;
  86. }
  87. /// bind static function
  88. template <typename Fn, typename... Extra>
  89. class_& def_static(const char* name, Fn&& f, const Extra&... extra) {
  90. impl::bind_function<false, true>(*this, name, std::forward<Fn>(f), extra...);
  91. return *this;
  92. }
  93. template <typename MP, typename... Extras>
  94. class_& def_readwrite(const char* name, MP mp, const Extras&... extras) {
  95. if constexpr(!std::is_member_object_pointer_v<MP>) {
  96. static_assert(std::is_member_object_pointer_v<MP>,
  97. "def_readwrite only supports pointer to data member");
  98. } else {
  99. impl::bind_property(
  100. *this,
  101. name,
  102. [mp](class_type_t<MP>& self) -> auto& {
  103. return self.*mp;
  104. },
  105. [mp](class_type_t<MP>& self, const member_type_t<MP>& value) {
  106. self.*mp = value;
  107. },
  108. extras...);
  109. }
  110. return *this;
  111. }
  112. template <typename MP, typename... Extras>
  113. class_& def_readonly(const char* name, MP mp, const Extras&... extras) {
  114. if constexpr(!std::is_member_object_pointer_v<MP>) {
  115. static_assert(std::is_member_object_pointer_v<MP>,
  116. "def_readonly only supports pointer to data member");
  117. } else {
  118. impl::bind_property(
  119. *this,
  120. name,
  121. [mp](class_type_t<MP>& self) -> auto& {
  122. return self.*mp;
  123. },
  124. nullptr,
  125. extras...);
  126. }
  127. return *this;
  128. }
  129. template <typename Getter, typename Setter, typename... Extras>
  130. class_& def_property(const char* name, Getter&& g, Setter&& s, const Extras&... extras) {
  131. impl::bind_property(*this,
  132. name,
  133. std::forward<Getter>(g),
  134. std::forward<Setter>(s),
  135. extras...);
  136. return *this;
  137. }
  138. template <typename Getter, typename... Extras>
  139. class_& def_property_readonly(const char* name, Getter&& mp, const Extras&... extras) {
  140. impl::bind_property(*this, name, std::forward<Getter>(mp), nullptr, extras...);
  141. return *this;
  142. }
  143. template <typename Var, typename... Extras>
  144. class_& def_readwrite_static(const char* name, Var& mp, const Extras&... extras) {
  145. static_assert(
  146. dependent_false<Var>,
  147. "define static properties requires metaclass. This is a complex feature with few use cases, so it may never be implemented.");
  148. return *this;
  149. }
  150. template <typename Var, typename... Extras>
  151. class_& def_readonly_static(const char* name, Var& mp, const Extras&... extras) {
  152. static_assert(
  153. dependent_false<Var>,
  154. "define static properties requires metaclass. This is a complex feature with few use cases, so it may never be implemented.");
  155. return *this;
  156. }
  157. template <typename Getter, typename Setter, typename... Extras>
  158. class_& def_property_static(const char* name, Getter&& g, Setter&& s, const Extras&... extras) {
  159. static_assert(
  160. dependent_false<Getter>,
  161. "define static properties requires metaclass. This is a complex feature with few use cases, so it may never be implemented.");
  162. return *this;
  163. }
  164. };
  165. template <typename T, typename... Others>
  166. class enum_ : public class_<T, Others...> {
  167. std::vector<std::pair<const char*, object>> m_values;
  168. public:
  169. using Base = class_<T, Others...>;
  170. template <typename... Args>
  171. enum_(const handle& scope, const char* name, Args&&... args) :
  172. class_<T, Others...>(scope, name, std::forward<Args>(args)...) {
  173. Base::def(init([](int value) {
  174. return static_cast<T>(value);
  175. }));
  176. Base::def("__eq__", [](T& self, T& other) {
  177. return self == other;
  178. });
  179. Base::def_property_readonly("value", [](T& self) {
  180. return int_(static_cast<std::underlying_type_t<T>>(self));
  181. });
  182. }
  183. enum_& value(const char* name, T value) {
  184. auto var = pkbind::cast(value, return_value_policy::copy);
  185. setattr(*this, name, var);
  186. m_values.emplace_back(name, std::move(var));
  187. return *this;
  188. }
  189. enum_& export_values() {
  190. for(auto& [name, value]: m_values) {
  191. setattr(Base::m_scope, name, value);
  192. }
  193. return *this;
  194. }
  195. };
  196. } // namespace pkbind