pocketpy.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #pragma once
  2. #include <stdint.h>
  3. #include <stdbool.h>
  4. #include <stdarg.h>
  5. #include "pocketpy/common/config.h"
  6. #include "pocketpy/common/export.h"
  7. #ifdef __cplusplus
  8. extern "C" {
  9. #endif
  10. /************* Public Types *************/
  11. typedef struct py_TValue py_TValue;
  12. typedef uint16_t py_Name;
  13. typedef int16_t py_Type;
  14. typedef int64_t py_i64;
  15. typedef double py_f64;
  16. #define PY_RAISE // mark a function that can raise an exception
  17. typedef struct c11_sv {
  18. const char* data;
  19. int size;
  20. } c11_sv;
  21. /// Generic reference.
  22. typedef py_TValue* py_Ref;
  23. /// An object reference which has the same lifespan as the object.
  24. typedef py_TValue* py_ObjectRef;
  25. /// A global reference which has the same lifespan as the VM.
  26. typedef py_TValue* py_GlobalRef;
  27. /// A specific location in the stack.
  28. typedef py_TValue* py_StackRef;
  29. /// A temporary reference which has a short or unknown lifespan.
  30. typedef py_TValue* py_TmpRef;
  31. /// Native function signature.
  32. /// @param argc number of arguments.
  33. /// @param argv array of arguments. Use `py_arg(i)` macro to get the i-th argument.
  34. /// @return true if the function is successful.
  35. typedef bool (*py_CFunction)(int argc, py_StackRef argv) PY_RAISE;
  36. enum py_CompileMode { EXEC_MODE, EVAL_MODE, REPL_MODE, CELL_MODE };
  37. extern py_GlobalRef py_True;
  38. extern py_GlobalRef py_False;
  39. extern py_GlobalRef py_None;
  40. extern py_GlobalRef py_NIL;
  41. /************* Global Setup *************/
  42. /// Initialize pocketpy and the default VM.
  43. void py_initialize();
  44. /// Finalize pocketpy.
  45. void py_finalize();
  46. /// Get the current VM index.
  47. int py_currentvm();
  48. /// Switch to a VM.
  49. /// @param index index of the VM ranging from 0 to 16 (exclusive). `0` is the default VM.
  50. void py_switchvm(int index);
  51. /// Run a source string.
  52. /// @param source source string.
  53. /// @param filename filename (for error messages).
  54. /// @param mode compile mode. Use `EXEC_MODE` for statements `EVAL_MODE` for expressions.
  55. /// @param module target module. Use NULL for the main module.
  56. /// @return true if the execution is successful.
  57. bool py_exec(const char* source,
  58. const char* filename,
  59. enum py_CompileMode mode,
  60. py_Ref module) PY_RAISE;
  61. /************* Values Creation *************/
  62. void py_newint(py_Ref, py_i64);
  63. void py_newfloat(py_Ref, py_f64);
  64. void py_newbool(py_Ref, bool);
  65. void py_newstr(py_Ref, const char*);
  66. void py_newstrn(py_Ref, const char*, int);
  67. unsigned char* py_newbytes(py_Ref, int);
  68. void py_newnone(py_Ref);
  69. void py_newnotimplemented(py_Ref out);
  70. void py_newellipsis(py_Ref out);
  71. void py_newnil(py_Ref);
  72. /// Create a tuple with n UNINITIALIZED elements.
  73. /// You should initialize all elements before using it.
  74. void py_newtuple(py_Ref, int n);
  75. /// Create a list.
  76. void py_newlist(py_Ref);
  77. /// Create a list with n UNINITIALIZED elements.
  78. /// You should initialize all elements before using it.
  79. void py_newlistn(py_Ref, int n);
  80. void py_newdict(py_Ref);
  81. void py_newslice(py_Ref);
  82. void py_newnativefunc(py_Ref out, py_CFunction);
  83. py_Name
  84. py_newfunction(py_Ref out, const char* sig, py_CFunction f, const char* docstring, int slots);
  85. void py_newboundmethod(py_Ref out, py_Ref self, py_Ref func);
  86. /************* Name Convertions *************/
  87. py_Name py_name(const char*);
  88. const char* py_name2str(py_Name);
  89. py_Name py_namev(c11_sv name);
  90. c11_sv py_name2sv(py_Name);
  91. #define py_ismagicname(name) (name <= __missing__)
  92. /************* Meta Operations *************/
  93. /// Create a new type.
  94. /// @param name name of the type.
  95. /// @param base base type.
  96. /// @param module module where the type is defined. Use NULL for built-in types.
  97. /// @param dtor destructor function. Use NULL if not needed.
  98. py_Type py_newtype(const char* name, py_Type base, const py_GlobalRef module, void (*dtor)(void*));
  99. /// Create a new object.
  100. /// @param out output reference.
  101. /// @param type type of the object.
  102. /// @param slots number of slots. Use -1 to create a `__dict__`.
  103. /// @param udsize size of your userdata. You can use `py_touserdata()` to get the pointer to it.
  104. void* py_newobject(py_Ref out, py_Type type, int slots, int udsize);
  105. /************* Type Cast *************/
  106. py_i64 py_toint(py_Ref);
  107. py_f64 py_tofloat(py_Ref);
  108. bool py_castfloat(py_Ref, py_f64* out) PY_RAISE;
  109. bool py_tobool(py_Ref);
  110. py_Type py_totype(py_Ref);
  111. const char* py_tostr(py_Ref);
  112. const char* py_tostrn(py_Ref, int* size);
  113. c11_sv py_tosv(py_Ref);
  114. unsigned char* py_tobytes(py_Ref, int* size);
  115. void* py_touserdata(py_Ref);
  116. #define py_isint(self) py_istype(self, tp_int)
  117. #define py_isfloat(self) py_istype(self, tp_float)
  118. #define py_isbool(self) py_istype(self, tp_bool)
  119. #define py_isstr(self) py_istype(self, tp_str)
  120. #define py_islist(self) py_istype(self, tp_list)
  121. #define py_istuple(self) py_istype(self, tp_tuple)
  122. #define py_isdict(self) py_istype(self, tp_dict)
  123. #define py_isnil(self) py_istype(self, 0)
  124. #define py_isnone(self) py_istype(self, tp_NoneType)
  125. py_Type py_typeof(py_Ref self);
  126. bool py_istype(py_Ref, py_Type);
  127. bool py_isinstance(py_Ref obj, py_Type type);
  128. bool py_issubclass(py_Type derived, py_Type base);
  129. /// Search the magic method from the given type to the base type.
  130. py_GlobalRef py_tpfindmagic(py_Type, py_Name name);
  131. /// Search the name from the given type to the base type.
  132. py_GlobalRef py_tpfindname(py_Type, py_Name name);
  133. /// Get the type object of the given type.
  134. py_GlobalRef py_tpobject(py_Type type);
  135. /// Get the type name.
  136. const char* py_tpname(py_Type type);
  137. /// Call a type to create a new instance.
  138. bool py_tpcall(py_Type type, int argc, py_Ref argv) PY_RAISE;
  139. /// Find the magic method from the given type only.
  140. py_GlobalRef py_tpmagic(py_Type type, py_Name name);
  141. /// Check if the object is an instance of the given type.
  142. bool py_checktype(py_Ref self, py_Type type) PY_RAISE;
  143. #define py_checkint(self) py_checktype(self, tp_int)
  144. #define py_checkfloat(self) py_checktype(self, tp_float)
  145. #define py_checkbool(self) py_checktype(self, tp_bool)
  146. #define py_checkstr(self) py_checktype(self, tp_str)
  147. /************* References *************/
  148. /// Get the reference to the i-th register.
  149. /// All registers are located in a contiguous memory.
  150. py_GlobalRef py_getreg(int i);
  151. /// Set the reference to the i-th register.
  152. void py_setreg(int i, py_Ref val);
  153. /// Equivalent to `*dst = *src`.
  154. void py_assign(py_Ref dst, py_Ref src);
  155. /// The return value of the most recent call.
  156. py_GlobalRef py_retval();
  157. /// Get the reference of the object's `__dict__`.
  158. /// The object must have a `__dict__`.
  159. /// Returns a reference to the value or NULL if not found.
  160. py_ObjectRef py_getdict(py_Ref self, py_Name name);
  161. void py_setdict(py_Ref self, py_Name name, py_Ref val);
  162. bool py_deldict(py_Ref self, py_Name name);
  163. py_ObjectRef py_emplacedict(py_Ref self, py_Name name);
  164. /// Get the reference of the i-th slot of the object.
  165. /// The object must have slots and `i` must be in range.
  166. py_ObjectRef py_getslot(py_Ref self, int i);
  167. void py_setslot(py_Ref self, int i, py_Ref val);
  168. /************* Bindings *************/
  169. // new style decl-based bindings
  170. void py_bind(py_Ref obj, const char* sig, py_CFunction f);
  171. // old style argc-based bindings
  172. void py_bindmethod(py_Type type, const char* name, py_CFunction f);
  173. void py_bindfunc(py_Ref obj, const char* name, py_CFunction f);
  174. void py_bindproperty(py_Type type, const char* name, py_CFunction getter, py_CFunction setter);
  175. #define py_bindmagic(type, __magic__, f) py_newnativefunc(py_tpmagic((type), __magic__), (f))
  176. #define PY_CHECK_ARGC(n) \
  177. if(argc != n) return TypeError("expected %d arguments, got %d", n, argc)
  178. #define PY_CHECK_ARG_TYPE(i, type) \
  179. if(!py_checktype(py_arg(i), type)) return false
  180. #define py_offset(p, i) ((py_Ref)((char*)p + ((i) << 4)))
  181. #define py_arg(i) py_offset(argv, i)
  182. /************* Python Equivalents *************/
  183. bool py_getattr(py_Ref self, py_Name name) PY_RAISE;
  184. bool py_setattr(py_Ref self, py_Name name, py_Ref val) PY_RAISE;
  185. bool py_delattr(py_Ref self, py_Name name) PY_RAISE;
  186. bool py_getitem(py_Ref self, py_Ref key) PY_RAISE;
  187. bool py_setitem(py_Ref self, py_Ref key, py_Ref val) PY_RAISE;
  188. bool py_delitem(py_Ref self, py_Ref key) PY_RAISE;
  189. /// Perform a binary operation on the stack.
  190. /// It assumes `lhs` and `rhs` are already pushed to the stack.
  191. /// The result will be set to `py_retval()`.
  192. bool py_binaryop(py_Ref lhs, py_Ref rhs, py_Name op, py_Name rop) PY_RAISE;
  193. #define py_binaryadd(lhs, rhs) py_binaryop(lhs, rhs, __add__, __radd__)
  194. #define py_binarysub(lhs, rhs) py_binaryop(lhs, rhs, __sub__, __rsub__)
  195. #define py_binarymul(lhs, rhs) py_binaryop(lhs, rhs, __mul__, __rmul__)
  196. #define py_binarytruediv(lhs, rhs) py_binaryop(lhs, rhs, __truediv__, __rtruediv__)
  197. #define py_binaryfloordiv(lhs, rhs) py_binaryop(lhs, rhs, __floordiv__, __rfloordiv__)
  198. #define py_binarymod(lhs, rhs) py_binaryop(lhs, rhs, __mod__, __rmod__)
  199. #define py_binarypow(lhs, rhs) py_binaryop(lhs, rhs, __pow__, __rpow__)
  200. #define py_binarylshift(lhs, rhs) py_binaryop(lhs, rhs, __lshift__, 0)
  201. #define py_binaryrshift(lhs, rhs) py_binaryop(lhs, rhs, __rshift__, 0)
  202. #define py_binaryand(lhs, rhs) py_binaryop(lhs, rhs, __and__, 0)
  203. #define py_binaryor(lhs, rhs) py_binaryop(lhs, rhs, __or__, 0)
  204. #define py_binaryxor(lhs, rhs) py_binaryop(lhs, rhs, __xor__, 0)
  205. #define py_binarymatmul(lhs, rhs) py_binaryop(lhs, rhs, __matmul__, 0)
  206. /************* Stack Operations *************/
  207. /// Return a reference to the i-th object from the top of the stack.
  208. /// i should be negative, e.g. (-1) means TOS.
  209. py_StackRef py_peek(int i);
  210. /// Push the object to the stack.
  211. void py_push(py_Ref src);
  212. /// Push a nil object to the stack.
  213. void py_pushnil();
  214. /// Pop an object from the stack.
  215. void py_pop();
  216. /// Shrink the stack by n.
  217. void py_shrink(int n);
  218. /// Get a temporary variable from the stack and returns the reference to it.
  219. py_StackRef py_pushtmp();
  220. /// Gets the unbound method of the object.
  221. /// Assumes the object is located at the top of the stack.
  222. /// If returns true: [self] -> [unbound, self]
  223. /// If returns false: [self] -> [self] (no change)
  224. bool py_pushmethod(py_Name name);
  225. /// A stack operation that calls a function.
  226. /// It assumes `argc + kwargc` arguments are already pushed to the stack.
  227. /// The result will be set to `py_retval()`.
  228. /// The stack size will be reduced by `argc + kwargc`.
  229. bool py_vectorcall(uint16_t argc, uint16_t kwargc) PY_RAISE;
  230. /************* Modules *************/
  231. py_TmpRef py_newmodule(const char* path);
  232. py_TmpRef py_getmodule(const char* path);
  233. /// Import a module.
  234. /// The result will be set to `py_retval()`.
  235. /// -1: error, 0: not found, 1: success
  236. int py_import(const char* path) PY_RAISE;
  237. /************* Errors *************/
  238. /// Raise an exception by name and message. Always returns false.
  239. bool py_exception(py_Type type, const char* fmt, ...) PY_RAISE;
  240. /// Raise an expection object. Always returns false.
  241. bool py_raise(py_Ref) PY_RAISE;
  242. /// Print the current exception.
  243. void py_printexc();
  244. /// Format the current exception.
  245. char* py_formatexc();
  246. /// Check if an exception is raised.
  247. bool py_checkexc();
  248. /// Check if the exception is an instance of the given type.
  249. bool py_matchexc(py_Type type);
  250. /// Clear the current exception.
  251. void py_clearexc(py_StackRef p0);
  252. #define IOError(...) py_exception(tp_IOError, __VA_ARGS__)
  253. #define OSError(...) py_exception(tp_OSError, __VA_ARGS__)
  254. #define NameError(n) py_exception(tp_NameError, "name '%n' is not defined", (n))
  255. #define TypeError(...) py_exception(tp_TypeError, __VA_ARGS__)
  256. #define RuntimeError(...) py_exception(tp_RuntimeError, __VA_ARGS__)
  257. #define ValueError(...) py_exception(tp_ValueError, __VA_ARGS__)
  258. #define IndexError(...) py_exception(tp_IndexError, __VA_ARGS__)
  259. #define ImportError(...) py_exception(tp_ImportError, __VA_ARGS__)
  260. #define NotImplementedError() py_exception(tp_NotImplementedError, "")
  261. #define AttributeError(self, n) \
  262. py_exception(tp_AttributeError, "'%t' object has no attribute '%n'", (self)->type, (n))
  263. #define UnboundLocalError(n) \
  264. py_exception(tp_UnboundLocalError, "local variable '%n' referenced before assignment", (n))
  265. bool StopIteration();
  266. bool KeyError(py_Ref key) PY_RAISE;
  267. /************* Operators *************/
  268. int py_equal(py_Ref lhs, py_Ref rhs) PY_RAISE;
  269. int py_less(py_Ref lhs, py_Ref rhs) PY_RAISE;
  270. /// Equivalent to `bool(val)`.
  271. /// Returns 1 if `val` is truthy, otherwise 0.
  272. /// Returns -1 if an error occurred.
  273. int py_bool(py_Ref val) PY_RAISE;
  274. #define py_eq(lhs, rhs) py_binaryop(lhs, rhs, __eq__, __eq__)
  275. #define py_ne(lhs, rhs) py_binaryop(lhs, rhs, __ne__, __ne__)
  276. #define py_lt(lhs, rhs) py_binaryop(lhs, rhs, __lt__, __gt__)
  277. #define py_le(lhs, rhs) py_binaryop(lhs, rhs, __le__, __ge__)
  278. #define py_gt(lhs, rhs) py_binaryop(lhs, rhs, __gt__, __lt__)
  279. #define py_ge(lhs, rhs) py_binaryop(lhs, rhs, __ge__, __le__)
  280. bool py_hash(py_Ref, py_i64* out) PY_RAISE;
  281. /// Get the iterator of the object.
  282. bool py_iter(py_Ref) PY_RAISE;
  283. /// Get the next element from the iterator.
  284. /// 1: success, 0: StopIteration, -1: error
  285. int py_next(py_Ref) PY_RAISE;
  286. /// Python equivalent to `lhs is rhs`.
  287. bool py_isidentical(py_Ref, py_Ref);
  288. /// Call a function.
  289. /// It prepares the stack and then performs a `vectorcall(argc, 0, false)`.
  290. /// The result will be set to `py_retval()`.
  291. /// The stack remains unchanged after the operation.
  292. bool py_call(py_Ref f, int argc, py_Ref argv) PY_RAISE;
  293. /// Call a non-magic method.
  294. /// It prepares the stack and then performs a `vectorcall(argc+1, 0, false)`.
  295. /// The result will be set to `py_retval()`.
  296. /// The stack remains unchanged after the operation.
  297. bool py_callmethod(py_Ref self, py_Name name, int argc, py_Ref argv) PY_RAISE;
  298. bool py_str(py_Ref val) PY_RAISE;
  299. bool py_repr(py_Ref val) PY_RAISE;
  300. bool py_len(py_Ref val) PY_RAISE;
  301. /************* Unchecked Functions *************/
  302. py_ObjectRef py_tuple__data(py_Ref self);
  303. py_ObjectRef py_tuple__getitem(py_Ref self, int i);
  304. void py_tuple__setitem(py_Ref self, int i, py_Ref val);
  305. int py_tuple__len(py_Ref self);
  306. py_TmpRef py_list__data(py_Ref self);
  307. py_TmpRef py_list__getitem(py_Ref self, int i);
  308. void py_list__setitem(py_Ref self, int i, py_Ref val);
  309. void py_list__delitem(py_Ref self, int i);
  310. int py_list__len(py_Ref self);
  311. void py_list__append(py_Ref self, py_Ref val);
  312. void py_list__clear(py_Ref self);
  313. void py_list__insert(py_Ref self, int i, py_Ref val);
  314. void py_list__reverse(py_Ref self);
  315. py_TmpRef py_dict__getitem(py_Ref self, py_Ref key) PY_RAISE;
  316. void py_dict__setitem(py_Ref self, py_Ref key, py_Ref val) PY_RAISE;
  317. void py_dict__delitem(py_Ref self, py_Ref key) PY_RAISE;
  318. bool py_dict__contains(py_Ref self, py_Ref key);
  319. int py_dict__len(py_Ref self);
  320. bool py_dict__apply(py_Ref self, bool (*f)(py_Ref key, py_Ref val, void* ctx), void* ctx);
  321. /************* Others *************/
  322. int py_replinput(char* buf, int max_size);
  323. /// Python favored string formatting. (just put here, not for users)
  324. /// %d: int
  325. /// %i: py_i64 (int64_t)
  326. /// %f: py_f64 (double)
  327. /// %s: const char*
  328. /// %q: c11_sv
  329. /// %v: c11_sv
  330. /// %c: char
  331. /// %p: void*
  332. /// %t: py_Type
  333. /// %n: py_Name
  334. enum py_MagicNames {
  335. py_MagicNames__NULL, // 0 is reserved
  336. #define MAGIC_METHOD(x) x,
  337. #include "pocketpy/xmacros/magics.h"
  338. #undef MAGIC_METHOD
  339. };
  340. enum py_PredefinedTypes {
  341. tp_object = 1,
  342. tp_type, // py_Type
  343. tp_int,
  344. tp_float,
  345. tp_bool,
  346. tp_str,
  347. tp_str_iterator,
  348. tp_list, // c11_vector
  349. tp_tuple, // N slots
  350. tp_array_iterator,
  351. tp_slice, // 3 slots (start, stop, step)
  352. tp_range,
  353. tp_range_iterator,
  354. tp_module,
  355. tp_function,
  356. tp_nativefunc,
  357. tp_boundmethod,
  358. tp_super, // 1 slot + py_Type
  359. tp_BaseException,
  360. tp_Exception,
  361. tp_bytes,
  362. tp_mappingproxy,
  363. tp_dict,
  364. tp_dict_items, // 1 slot
  365. tp_property, // 2 slots (getter + setter)
  366. tp_star_wrapper, // 1 slot + int level
  367. tp_staticmethod, // 1 slot
  368. tp_classmethod, // 1 slot
  369. tp_NoneType,
  370. tp_NotImplementedType,
  371. tp_ellipsis,
  372. tp_SyntaxError,
  373. tp_StopIteration,
  374. /* builtin exceptions */
  375. tp_StackOverflowError,
  376. tp_IOError,
  377. tp_OSError,
  378. tp_NotImplementedError,
  379. tp_TypeError,
  380. tp_IndexError,
  381. tp_ValueError,
  382. tp_RuntimeError,
  383. tp_ZeroDivisionError,
  384. tp_NameError,
  385. tp_UnboundLocalError,
  386. tp_AttributeError,
  387. tp_ImportError,
  388. tp_AssertionError,
  389. tp_KeyError,
  390. };
  391. #ifdef __cplusplus
  392. }
  393. #endif
  394. /*
  395. Some notes:
  396. ## Macros
  397. 1. Function macros are partial functions. They can be used as normal expressions. Use the same
  398. naming convention as functions.
  399. 2. Snippet macros are `do {...} while(0)` blocks. They cannot be used as expressions. Use
  400. `UPPER_CASE` naming convention.
  401. 3. Constant macros are used for global constants. Use `UPPER_CASE` or k-prefix naming convention.
  402. */