class.h 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #pragma once
  2. #include "module.h"
  3. #include <vector>
  4. namespace pybind11 {
  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_(const handle& scope, const char* name, const Args&... args) :
  15. m_scope(scope), type(type_visitor::create<T, Base>(scope, name)) {
  16. auto& info = type_info::of<T>();
  17. info.name = name;
  18. // bind __new__
  19. interpreter::bind_func(m_ptr, pkpy::__new__, -1, [](pkpy::VM* vm, pkpy::ArgsView args) {
  20. auto cls = handle(args[0])._as<pkpy::Type>();
  21. // check if the class has constructor, if not, raise error
  22. if(vm->find_name_in_mro(cls, pkpy::__init__) == nullptr) {
  23. vm->RuntimeError("if you want to create instance of bound class, you must bind constructor for it");
  24. }
  25. auto var = instance::create(cls, &type_info::of<T>());
  26. if constexpr(types_count_v<dynamic_attr, Args...> != 0) {
  27. #if PK_VERSION_MAJOR == 2
  28. var.get()->_attr = new pkpy::NameDict();
  29. #else
  30. var->_enable_instance_dict();
  31. #endif
  32. }
  33. return var;
  34. });
  35. }
  36. /// bind constructor
  37. template <typename... Args, typename... Extra>
  38. class_& def(impl::constructor<Args...>, const Extra&... extra) {
  39. if constexpr(!std::is_constructible_v<T, Args...>) {
  40. static_assert(std::is_constructible_v<T, Args...>, "Invalid constructor arguments");
  41. } else {
  42. impl::bind_function<true>(
  43. *this,
  44. "__init__",
  45. [](T* self, Args... args) {
  46. new (self) T(args...);
  47. },
  48. pkpy::BindType::DEFAULT,
  49. extra...);
  50. return *this;
  51. }
  52. }
  53. template <typename Fn, typename... Extra>
  54. class_& def(impl::factory<Fn> factory, const Extra&... extra) {
  55. using ret = callable_return_t<Fn>;
  56. if constexpr(!std::is_same_v<T, ret>) {
  57. static_assert(std::is_same_v<T, ret>, "Factory function must return the class type");
  58. } else {
  59. impl::bind_function<true>(*this, "__init__", factory.make(), pkpy::BindType::DEFAULT, extra...);
  60. return *this;
  61. }
  62. }
  63. /// bind member function
  64. template <typename Fn, typename... Extra>
  65. class_& def(const char* name, Fn&& f, const Extra&... extra) {
  66. using first = remove_cvref_t<std::tuple_element_t<0, callable_args_t<remove_cvref_t<Fn>>>>;
  67. constexpr bool is_first_base_of_v = std::is_base_of_v<first, T> || std::is_same_v<first, T>;
  68. if constexpr(!is_first_base_of_v) {
  69. static_assert(is_first_base_of_v,
  70. "If you want to bind member function, the first argument must be the base class");
  71. } else {
  72. impl::bind_function<true>(*this, name, std::forward<Fn>(f), pkpy::BindType::DEFAULT, extra...);
  73. }
  74. return *this;
  75. }
  76. /// bind operators
  77. template <typename Operator, typename... Extras>
  78. class_& def(Operator op, const Extras&... extras) {
  79. op.execute(*this, extras...);
  80. return *this;
  81. }
  82. // TODO: factory function
  83. /// bind static function
  84. template <typename Fn, typename... Extra>
  85. class_& def_static(const char* name, Fn&& f, const Extra&... extra) {
  86. impl::bind_function<false>(*this, name, std::forward<Fn>(f), pkpy::BindType::STATICMETHOD, extra...);
  87. return *this;
  88. }
  89. template <typename MP, typename... Extras>
  90. class_& def_readwrite(const char* name, MP mp, const Extras&... extras) {
  91. if constexpr(!std::is_member_object_pointer_v<MP>) {
  92. static_assert(std::is_member_object_pointer_v<MP>, "def_readwrite only supports pointer to data member");
  93. } else {
  94. impl::bind_property(*this, name, mp, mp, extras...);
  95. }
  96. return *this;
  97. }
  98. template <typename MP, typename... Extras>
  99. class_& def_readonly(const char* name, MP mp, const Extras&... extras) {
  100. if constexpr(!std::is_member_object_pointer_v<MP>) {
  101. static_assert(std::is_member_object_pointer_v<MP>, "def_readonly only supports pointer to data member");
  102. } else {
  103. impl::bind_property(*this, name, mp, nullptr, extras...);
  104. }
  105. return *this;
  106. }
  107. template <typename Getter, typename Setter, typename... Extras>
  108. class_& def_property(const char* name, Getter&& g, Setter&& s, const Extras&... extras) {
  109. impl::bind_property(*this, name, std::forward<Getter>(g), std::forward<Setter>(s), extras...);
  110. return *this;
  111. }
  112. template <typename Getter, typename... Extras>
  113. class_& def_property_readonly(const char* name, Getter&& mp, const Extras&... extras) {
  114. impl::bind_property(*this, name, std::forward<Getter>(mp), nullptr, extras...);
  115. return *this;
  116. }
  117. template <typename Var, typename... Extras>
  118. class_& def_readwrite_static(const char* name, Var& mp, const Extras&... extras) {
  119. static_assert(
  120. dependent_false<Var>,
  121. "define static properties requires metaclass. This is a complex feature with few use cases, so it may never be implemented.");
  122. return *this;
  123. }
  124. template <typename Var, typename... Extras>
  125. class_& def_readonly_static(const char* name, Var& mp, const Extras&... extras) {
  126. static_assert(
  127. dependent_false<Var>,
  128. "define static properties requires metaclass. This is a complex feature with few use cases, so it may never be implemented.");
  129. return *this;
  130. }
  131. template <typename Getter, typename Setter, typename... Extras>
  132. class_& def_property_static(const char* name, Getter&& g, Setter&& s, const Extras&... extras) {
  133. static_assert(
  134. dependent_false<Getter>,
  135. "define static properties requires metaclass. This is a complex feature with few use cases, so it may never be implemented.");
  136. return *this;
  137. }
  138. };
  139. template <typename T, typename... Others>
  140. class enum_ : public class_<T, Others...> {
  141. std::vector<std::pair<const char*, handle>> m_values;
  142. public:
  143. using Base = class_<T, Others...>;
  144. using class_<T, Others...>::class_;
  145. template <typename... Args>
  146. enum_(const handle& scope, const char* name, Args&&... args) :
  147. class_<T, Others...>(scope, name, std::forward<Args>(args)...) {
  148. Base::def(init([](int value) {
  149. return static_cast<T>(value);
  150. }));
  151. Base::def("__eq__", [](T& self, T& other) {
  152. return self == other;
  153. });
  154. Base::def_property_readonly("value", [](T& self) {
  155. return int_(static_cast<std::underlying_type_t<T>>(self));
  156. });
  157. }
  158. enum_& value(const char* name, T value) {
  159. handle var = pybind11::cast(value, return_value_policy::copy);
  160. setattr(*this, name, var);
  161. m_values.emplace_back(name, var);
  162. return *this;
  163. }
  164. enum_& export_values() {
  165. for(auto& [name, value]: m_values) {
  166. setattr(Base::m_scope, name, value);
  167. }
  168. return *this;
  169. }
  170. };
  171. } // namespace pybind11