types.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #pragma once
  2. #include "object.h"
  3. namespace pybind11 {
  4. template <typename T>
  5. handle cast(T&& value, return_value_policy policy = return_value_policy::automatic_reference, handle parent = {});
  6. struct arg {
  7. const char* name;
  8. handle default_;
  9. arg(const char* name) : name(name), default_() {}
  10. template <typename T>
  11. arg& operator= (T&& value) {
  12. default_ = cast(std::forward<T>(value));
  13. return *this;
  14. }
  15. };
  16. // undef in pybind11.h
  17. #define PYBIND11_REGISTER_INIT(func) \
  18. static inline int _register = [] { \
  19. interpreter::register_init(func); \
  20. return 0; \
  21. }();
  22. class none : public object {
  23. #if PK_VERSION_MAJOR == 2
  24. PYBIND11_TYPE_IMPLEMENT(object, empty, vm->tp_none_type);
  25. #else
  26. PYBIND11_TYPE_IMPLEMENT(object, empty, [](const handle& obj) {
  27. return obj.is_none();
  28. });
  29. #endif
  30. public:
  31. none() : object(vm->None) {}
  32. };
  33. /// corresponding to type in Python
  34. class type : public object {
  35. PYBIND11_TYPE_IMPLEMENT(object, pkpy::Type, vm->tp_type);
  36. public:
  37. template <typename T>
  38. static handle handle_of() {
  39. return type_visitor::type<T>();
  40. }
  41. static type of(const handle& obj) { return type(vm->_t(obj.ptr())); }
  42. };
  43. /// corresponding to bool in Python
  44. class bool_ : public object {
  45. PYBIND11_TYPE_IMPLEMENT(object, bool, vm->tp_bool);
  46. public:
  47. bool_(bool value) : object(create(value)) {}
  48. operator bool () const { return self(); }
  49. };
  50. /// corresponding to int in Python
  51. class int_ : public object {
  52. PYBIND11_TYPE_IMPLEMENT(object, pkpy::i64, vm->tp_int);
  53. public:
  54. int_(int64_t value) : object(create(value)) {}
  55. operator int64_t () const { return self(); }
  56. };
  57. /// corresponding to float in Python
  58. class float_ : public object {
  59. PYBIND11_TYPE_IMPLEMENT(object, pkpy::f64, vm->tp_float);
  60. public:
  61. float_(double value) : object(create(value)) {}
  62. operator double () const { return self(); }
  63. };
  64. class iterable : public object {
  65. PYBIND11_TYPE_IMPLEMENT(object, empty, [](const handle& obj) {
  66. return vm->getattr(obj.ptr(), pkpy::__iter__, false) != nullptr;
  67. });
  68. };
  69. class iterator : public object {
  70. PYBIND11_TYPE_IMPLEMENT(object, empty, [](const handle& obj) {
  71. return vm->getattr(obj.ptr(), pkpy::__next__, false) != nullptr &&
  72. vm->getattr(obj.ptr(), pkpy::__iter__, false) != nullptr;
  73. });
  74. handle m_value;
  75. iterator(pkpy::PyVar n, pkpy::PyVar s) : object(n), m_value(s) {}
  76. public:
  77. iterator(const handle& obj) : object(obj) { m_value = vm->py_next(obj.ptr()); }
  78. iterator operator++ () {
  79. m_value = vm->py_next(m_ptr);
  80. return *this;
  81. }
  82. iterator operator++ (int) {
  83. m_value = vm->py_next(m_ptr);
  84. return *this;
  85. }
  86. const handle& operator* () const { return m_value; }
  87. friend bool operator== (const iterator& lhs, const iterator& rhs) { return lhs.m_value.is(rhs.m_value); }
  88. friend bool operator!= (const iterator& lhs, const iterator& rhs) { return !(lhs == rhs); }
  89. static iterator sentinel() { return iterator(vm->None, vm->StopIteration); }
  90. };
  91. class str : public object {
  92. PYBIND11_TYPE_IMPLEMENT(object, pkpy::Str, vm->tp_str);
  93. public:
  94. str(const char* c, int len) : object(create(c, len)) {};
  95. str(const char* c = "") : str(c, strlen(c)) {}
  96. str(const std::string& s) : str(s.data(), s.size()) {}
  97. str(std::string_view sv) : str(sv.data(), sv.size()) {}
  98. // explicit str(const bytes& b);
  99. explicit str(handle h);
  100. operator std::string_view () const { return self().sv(); }
  101. template <typename... Args>
  102. str format(Args&&... args) const;
  103. };
  104. // class bytes : public object {
  105. // public:
  106. // using object::object;
  107. // };
  108. // class bytearray : public object {
  109. // public:
  110. // using object::object;
  111. // };
  112. class tuple : public object {
  113. PYBIND11_TYPE_IMPLEMENT(object, pkpy::Tuple, vm->tp_tuple);
  114. public:
  115. tuple(int n) : object(create(n)) {}
  116. template <typename... Args, std::enable_if_t<(sizeof...(Args) > 1)>* = nullptr>
  117. tuple(Args&&... args) : object(create(sizeof...(Args))) {
  118. int index = 0;
  119. ((self()[index++] = pybind11::cast(std::forward<Args>(args)).ptr()), ...);
  120. }
  121. int size() const { return self().size(); }
  122. bool empty() const { return size() == 0; }
  123. tuple_accessor operator[] (int i) const;
  124. };
  125. class list : public object {
  126. PYBIND11_TYPE_IMPLEMENT(object, pkpy::List, vm->tp_list)
  127. public:
  128. list() : object(create(0)) {}
  129. list(int n) : object(create(n)) {}
  130. template <typename... Args, std::enable_if_t<(sizeof...(Args) > 1)>* = nullptr>
  131. list(Args&&... args) : object(create(sizeof...(Args))) {
  132. int index = 0;
  133. ((self()[index++] = pybind11::cast(std::forward<Args>(args)).ptr()), ...);
  134. }
  135. int size() const { return self().size(); }
  136. bool empty() const { return size() == 0; }
  137. void clear() { self().clear(); }
  138. list_accessor operator[] (int i) const;
  139. void append(const handle& obj) { self().push_back(obj.ptr()); }
  140. void extend(const handle& iterable) {
  141. for(auto& item: iterable) {
  142. append(item);
  143. }
  144. }
  145. void insert(int index, const handle& obj) {
  146. #if PK_VERSION_MAJOR == 2
  147. const auto pos = self().begin() + index;
  148. self().insert(pos, obj.ptr());
  149. #else
  150. self().insert(index, obj.ptr());
  151. #endif
  152. }
  153. };
  154. class slice : public object {
  155. PYBIND11_TYPE_IMPLEMENT(object, pkpy::Slice, vm->tp_slice);
  156. public:
  157. };
  158. // class set : public object {
  159. // public:
  160. // using object::object;
  161. // // set() : object(vm->new_object<pkpy::Se>(pkpy::VM::tp_set), true) {}
  162. // };
  163. //
  164. class dict : public object {
  165. PYBIND11_TYPE_IMPLEMENT(object, pkpy::Dict, vm->tp_dict);
  166. public:
  167. #if PK_VERSION_MAJOR == 2
  168. dict() : object(create()) {}
  169. template <typename... Args, typename = std::enable_if_t<(std::is_same_v<remove_cvref_t<Args>, arg> && ...)>>
  170. dict(Args&&... args) : object(create()) {
  171. auto foreach_ = [&](pybind11::arg& arg) {
  172. setitem(str(arg.name), arg.default_);
  173. };
  174. (foreach_(args), ...);
  175. }
  176. void setitem(const handle& key, const handle& value) { self().set(vm, key.ptr(), value.ptr()); }
  177. handle getitem(const handle& key) const { return self().try_get(vm, key.ptr()); }
  178. struct iterator {
  179. pkpy_DictIter iter;
  180. std::pair<handle, handle> value;
  181. iterator operator++ () {
  182. bool is_ended = pkpy_DictIter__next(&iter, (PyVar*)&value.first, (PyVar*)&value.second);
  183. if(!is_ended) {
  184. iter._dict = nullptr;
  185. iter._index = -1;
  186. }
  187. return *this;
  188. }
  189. std::pair<handle, handle> operator* () const { return value; }
  190. bool operator== (const iterator& other) const {
  191. return iter._dict == other.iter._dict && iter._index == other.iter._index;
  192. }
  193. bool operator!= (const iterator& other) const { return !(*this == other); }
  194. };
  195. iterator begin() const {
  196. iterator iter{self().iter(), {}};
  197. ++iter;
  198. return iter;
  199. }
  200. iterator end() const { return {nullptr, -1}; }
  201. #else
  202. dict() : object(create(vm)) {}
  203. template <typename... Args, typename = std::enable_if_t<(std::is_same_v<remove_cvref_t<Args>, arg> && ...)>>
  204. dict(Args&&... args) : object(create(vm)) {
  205. auto foreach_ = [&](pybind11::arg& arg) {
  206. setitem(str(arg.name), arg.default_);
  207. };
  208. (foreach_(args), ...);
  209. }
  210. void setitem(const handle& key, const handle& value) { self().set(key.ptr(), value.ptr()); }
  211. handle getitem(const handle& key) const { return self().try_get(key.ptr()); }
  212. struct iterator {
  213. pkpy::Dict::Item* items;
  214. pkpy::Dict::ItemNode* nodes;
  215. int index;
  216. iterator operator++ () {
  217. index = nodes[index].next;
  218. if(index == -1) {
  219. items = nullptr;
  220. nodes = nullptr;
  221. }
  222. return *this;
  223. }
  224. std::pair<handle, handle> operator* () const { return {items[index].first, items[index].second}; }
  225. bool operator== (const iterator& other) const {
  226. return items == other.items && nodes == other.nodes && index == other.index;
  227. }
  228. bool operator!= (const iterator& other) const { return !(*this == other); }
  229. };
  230. iterator begin() const {
  231. auto index = self()._head_idx;
  232. if(index == -1) {
  233. return end();
  234. } else {
  235. return {self()._items, self()._nodes, index};
  236. }
  237. }
  238. iterator end() const { return {nullptr, nullptr, -1}; }
  239. template <typename Key>
  240. bool contains(Key&& key) const {
  241. return self().contains(vm, pybind11::cast(std::forward<Key>(key)).ptr());
  242. }
  243. #endif
  244. int size() const { return self().size(); }
  245. bool empty() const { return size() == 0; }
  246. void clear() { self().clear(); }
  247. dict_accessor operator[] (int index) const;
  248. dict_accessor operator[] (std::string_view) const;
  249. dict_accessor operator[] (const handle& key) const;
  250. };
  251. class function : public object {
  252. PYBIND11_TYPE_IMPLEMENT(object, pkpy::Function, vm->tp_function);
  253. };
  254. //
  255. // class buffer : public object {
  256. // public:
  257. // using object::object;
  258. //};
  259. //
  260. // class memory_view : public object {
  261. // public:
  262. // using object::object;
  263. //};
  264. //
  265. class capsule : public object {
  266. PYBIND11_REGISTER_INIT([] {
  267. type_visitor::create<impl::capsule>(vm->builtins, "capsule", true);
  268. });
  269. PYBIND11_TYPE_IMPLEMENT(object, impl::capsule, handle(vm->builtins->attr("capsule"))._as<pkpy::Type>());
  270. public:
  271. template <typename T>
  272. capsule(T&& value) : object(create(std::forward<T>(value))) {}
  273. template <typename T>
  274. T& cast() const {
  275. return *static_cast<T*>(self().ptr);
  276. }
  277. };
  278. class property : public object {
  279. PYBIND11_TYPE_IMPLEMENT(object, pkpy::Property, vm->tp_property);
  280. public:
  281. #if PK_VERSION_MAJOR == 2
  282. property(handle getter, handle setter) : object(create(getter.ptr(), setter.ptr())) {}
  283. #else
  284. property(handle getter, handle setter) : object(create(pkpy::Property{getter.ptr(), setter.ptr()})) {}
  285. #endif
  286. handle getter() const { return self().getter; }
  287. handle setter() const { return self().setter; }
  288. };
  289. class args : public tuple {
  290. PYBIND11_TYPE_IMPLEMENT(tuple, pybind11::empty, vm->tp_tuple);
  291. };
  292. class kwargs : public dict {
  293. PYBIND11_TYPE_IMPLEMENT(dict, pybind11::empty, vm->tp_dict);
  294. };
  295. } // namespace pybind11