class.h 7.8 KB

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