pocketpy.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. #pragma once
  2. #include <stdint.h>
  3. #include <stdbool.h>
  4. #include <stddef.h>
  5. #include "pocketpy/config.h"
  6. #include "pocketpy/export.h"
  7. #include "pocketpy/linalg.h"
  8. #ifdef __cplusplus
  9. extern "C" {
  10. #endif
  11. /************* Public Types *************/
  12. /// A opaque type that represents a python object. You cannot access its members directly.
  13. typedef struct py_TValue py_TValue;
  14. /// An integer that represents a python identifier. This is to achieve string pooling and fast name
  15. /// resolution.
  16. typedef uint16_t py_Name;
  17. /// An integer that represents a python type. `0` is invalid.
  18. typedef int16_t py_Type;
  19. /// A 64-bit integer type. Corresponds to `int` in python.
  20. typedef int64_t py_i64;
  21. /// A 64-bit floating-point type. Corresponds to `float` in python.
  22. typedef double py_f64;
  23. /// A generic destructor function.
  24. typedef void (*py_Dtor)(void*);
  25. /// A string view type. It is helpful for passing strings which are not null-terminated.
  26. typedef struct c11_sv {
  27. const char* data;
  28. int size;
  29. } c11_sv;
  30. /// A struct contains the callbacks of the VM.
  31. typedef struct py_Callbacks {
  32. /// Used by `__import__` to load source code of a module.
  33. char* (*importfile)(const char*);
  34. /// Used by `print` to output a string.
  35. void (*print)(const char*);
  36. } py_Callbacks;
  37. #define PY_RAISE
  38. #define PY_RETURN
  39. /// A generic reference to a python object.
  40. typedef py_TValue* py_Ref;
  41. /// A reference which has the same lifespan as the python object.
  42. typedef py_TValue* py_ObjectRef;
  43. /// A global reference which has the same lifespan as the VM.
  44. typedef py_TValue* py_GlobalRef;
  45. /// A specific location in the value stack of the VM.
  46. typedef py_TValue* py_StackRef;
  47. /// An item reference to a container object. It invalidates when the container is modified.
  48. typedef py_TValue* py_ItemRef;
  49. /// An output reference for returning a value.
  50. typedef py_TValue* py_OutRef;
  51. /// Native function signature.
  52. /// @param argc number of arguments.
  53. /// @param argv array of arguments. Use `py_arg(i)` macro to get the i-th argument.
  54. /// @return `true` if the function is successful or `false` if an exception is raised.
  55. typedef bool (*py_CFunction)(int argc, py_StackRef argv) PY_RAISE PY_RETURN;
  56. /// Python compiler modes.
  57. /// + `EXEC_MODE`: for statements.
  58. /// + `EVAL_MODE`: for expressions.
  59. /// + `SINGLE_MODE`: for REPL or jupyter notebook execution.
  60. enum py_CompileMode { EXEC_MODE, EVAL_MODE, SINGLE_MODE };
  61. /// A shorthand for `True`.
  62. PK_EXPORT extern py_GlobalRef py_True;
  63. /// A shorthand for `False`.
  64. PK_EXPORT extern py_GlobalRef py_False;
  65. /// A shorthand for `None`.
  66. PK_EXPORT extern py_GlobalRef py_None;
  67. /// A shorthand for `nil`. `nil` is not a valid python object.
  68. PK_EXPORT extern py_GlobalRef py_NIL;
  69. /************* Global Setup *************/
  70. /// Initialize pocketpy and the default VM.
  71. PK_EXPORT void py_initialize();
  72. /// Finalize pocketpy and free all VMs.
  73. PK_EXPORT void py_finalize();
  74. /// Get the current VM index.
  75. PK_EXPORT int py_currentvm();
  76. /// Switch to a VM.
  77. /// @param index index of the VM ranging from 0 to 16 (exclusive). `0` is the default VM.
  78. PK_EXPORT void py_switchvm(int index);
  79. /// Reset the current VM.
  80. PK_EXPORT void py_resetvm();
  81. /// Get the current VM context. This is used for user-defined data.
  82. PK_EXPORT void* py_getvmctx();
  83. /// Set the current VM context. This is used for user-defined data.
  84. PK_EXPORT void py_setvmctx(void* ctx);
  85. /// Set `sys.argv`. Used for storing command-line arguments.
  86. PK_EXPORT void py_sys_setargv(int argc, char** argv);
  87. /// Setup the callbacks for the current VM.
  88. PK_EXPORT py_Callbacks* py_callbacks();
  89. /// Run a source string.
  90. /// @param source source string.
  91. /// @param filename filename (for error messages).
  92. /// @param mode compile mode. Use `EXEC_MODE` for statements `EVAL_MODE` for expressions.
  93. /// @param module target module. Use NULL for the main module.
  94. /// @return `true` if the execution is successful or `false` if an exception is raised.
  95. PK_EXPORT bool py_exec(const char* source,
  96. const char* filename,
  97. enum py_CompileMode mode,
  98. py_Ref module) PY_RAISE PY_RETURN;
  99. /// Evaluate a source string. Equivalent to `py_exec(source, "<string>", EVAL_MODE, module)`.
  100. PK_EXPORT bool py_eval(const char* source, py_Ref module) PY_RAISE PY_RETURN;
  101. /// Run a source string with smart interpretation.
  102. /// Example:
  103. /// `py_newstr(py_r0(), "abc");`
  104. /// `py_newint(py_r1(), 123);`
  105. /// `py_smartexec("print(_0, _1)", NULL, py_r0(), py_r1());`
  106. /// `// "abc 123" will be printed`.
  107. PK_EXPORT bool py_smartexec(const char* source, py_Ref module, ...) PY_RAISE PY_RETURN;
  108. /// Evaluate a source string with smart interpretation.
  109. /// Example:
  110. /// `py_newstr(py_r0(), "abc");`
  111. /// `py_smarteval("len(_)", NULL, py_r0());`
  112. /// `int res = py_toint(py_retval());`
  113. /// `// res will be 3`.
  114. PK_EXPORT bool py_smarteval(const char* source, py_Ref module, ...) PY_RAISE PY_RETURN;
  115. /// Compile a source string into a code object.
  116. /// Use python's `exec()` or `eval()` to execute it.
  117. PK_EXPORT bool py_compile(const char* source,
  118. const char* filename,
  119. enum py_CompileMode mode,
  120. bool is_dynamic) PY_RAISE PY_RETURN;
  121. /// Python equivalent to `globals()`.
  122. PK_EXPORT void py_newglobals(py_OutRef);
  123. /// Python equivalent to `locals()`.
  124. /// @return a temporary object, which expires on the associated function return.
  125. PK_EXPORT void py_newlocals(py_OutRef);
  126. /************* Values Creation *************/
  127. /// Create an `int` object.
  128. PK_EXPORT void py_newint(py_OutRef, py_i64);
  129. /// Create a `float` object.
  130. PK_EXPORT void py_newfloat(py_OutRef, py_f64);
  131. /// Create a `bool` object.
  132. PK_EXPORT void py_newbool(py_OutRef, bool);
  133. /// Create a `str` object from a null-terminated string (utf-8).
  134. PK_EXPORT void py_newstr(py_OutRef, const char*);
  135. /// Create a `str` object from a char array (utf-8).
  136. PK_EXPORT void py_newstrn(py_OutRef, const char*, int);
  137. /// Create a `bytes` object with `n` UNINITIALIZED bytes.
  138. PK_EXPORT unsigned char* py_newbytes(py_OutRef, int n);
  139. /// Create a `None` object.
  140. PK_EXPORT void py_newnone(py_OutRef);
  141. /// Create a `NotImplemented` object.
  142. PK_EXPORT void py_newnotimplemented(py_OutRef);
  143. /// Create a `...` object.
  144. PK_EXPORT void py_newellipsis(py_OutRef);
  145. /// Create a `nil` object. `nil` is an invalid representation of an object.
  146. /// Don't use it unless you know what you are doing.
  147. PK_EXPORT void py_newnil(py_OutRef);
  148. /// Create a `tuple` with `n` UNINITIALIZED elements.
  149. /// You should initialize all elements before using it.
  150. PK_EXPORT void py_newtuple(py_OutRef, int n);
  151. /// Create an empty `list`.
  152. PK_EXPORT void py_newlist(py_OutRef);
  153. /// Create a `list` with `n` UNINITIALIZED elements.
  154. /// You should initialize all elements before using it.
  155. PK_EXPORT void py_newlistn(py_OutRef, int n);
  156. /// Create an empty `dict`.
  157. PK_EXPORT void py_newdict(py_OutRef);
  158. /// Create an UNINITIALIZED `slice` object.
  159. /// You should use `py_setslot()` to set `start`, `stop`, and `step`.
  160. PK_EXPORT void py_newslice(py_OutRef);
  161. /// Create a `nativefunc` object.
  162. PK_EXPORT void py_newnativefunc(py_OutRef, py_CFunction);
  163. /// Create a `function` object.
  164. PK_EXPORT py_Name py_newfunction(py_OutRef out,
  165. const char* sig,
  166. py_CFunction f,
  167. const char* docstring,
  168. int slots);
  169. /// Create a `boundmethod` object.
  170. PK_EXPORT void py_newboundmethod(py_OutRef out, py_Ref self, py_Ref func);
  171. /************* Name Convertions *************/
  172. /// Convert a null-terminated string to a name.
  173. PK_EXPORT py_Name py_name(const char*);
  174. /// Convert a name to a null-terminated string.
  175. PK_EXPORT const char* py_name2str(py_Name);
  176. /// Convert a `c11_sv` to a name.
  177. PK_EXPORT py_Name py_namev(c11_sv);
  178. /// Convert a name to a `c11_sv`.
  179. PK_EXPORT c11_sv py_name2sv(py_Name);
  180. #define py_ismagicname(name) (name <= __missing__)
  181. /************* Meta Operations *************/
  182. /// Create a new type.
  183. /// @param name name of the type.
  184. /// @param base base type.
  185. /// @param module module where the type is defined. Use `NULL` for built-in types.
  186. /// @param dtor destructor function. Use `NULL` if not needed.
  187. PK_EXPORT py_Type py_newtype(const char* name,
  188. py_Type base,
  189. const py_GlobalRef module,
  190. py_Dtor dtor);
  191. /// Create a new object.
  192. /// @param out output reference.
  193. /// @param type type of the object.
  194. /// @param slots number of slots. Use `-1` to create a `__dict__`.
  195. /// @param udsize size of your userdata.
  196. /// @return pointer to the userdata.
  197. PK_EXPORT void* py_newobject(py_OutRef out, py_Type type, int slots, int udsize);
  198. /************* Type Cast *************/
  199. /// Convert an `int` object in python to `int64_t`.
  200. PK_EXPORT py_i64 py_toint(py_Ref);
  201. /// Convert a `float` object in python to `double`.
  202. PK_EXPORT py_f64 py_tofloat(py_Ref);
  203. /// Cast a `int` or `float` object in python to `double`.
  204. /// If successful, return true and set the value to `out`.
  205. /// Otherwise, return false and raise `TypeError`.
  206. PK_EXPORT bool py_castfloat(py_Ref, py_f64* out) PY_RAISE;
  207. /// Cast a `int` object in python to `int64_t`.
  208. PK_EXPORT bool py_castint(py_Ref, py_i64* out) PY_RAISE;
  209. /// Convert a `bool` object in python to `bool`.
  210. PK_EXPORT bool py_tobool(py_Ref);
  211. /// Convert a `type` object in python to `py_Type`.
  212. PK_EXPORT py_Type py_totype(py_Ref);
  213. /// Convert a `str` object in python to null-terminated string.
  214. PK_EXPORT const char* py_tostr(py_Ref);
  215. /// Convert a `str` object in python to char array.
  216. PK_EXPORT const char* py_tostrn(py_Ref, int* size);
  217. /// Convert a `str` object in python to `c11_sv`.
  218. PK_EXPORT c11_sv py_tosv(py_Ref);
  219. /// Convert a `bytes` object in python to char array.
  220. PK_EXPORT unsigned char* py_tobytes(py_Ref, int* size);
  221. /// Convert a user-defined object to its userdata.
  222. PK_EXPORT void* py_touserdata(py_Ref);
  223. #define py_isint(self) py_istype(self, tp_int)
  224. #define py_isfloat(self) py_istype(self, tp_float)
  225. #define py_isbool(self) py_istype(self, tp_bool)
  226. #define py_isstr(self) py_istype(self, tp_str)
  227. #define py_islist(self) py_istype(self, tp_list)
  228. #define py_istuple(self) py_istype(self, tp_tuple)
  229. #define py_isdict(self) py_istype(self, tp_dict)
  230. #define py_isnil(self) py_istype(self, 0)
  231. #define py_isnone(self) py_istype(self, tp_NoneType)
  232. /// Get the type of the object.
  233. PK_EXPORT py_Type py_typeof(py_Ref self);
  234. /// Get type by module and name. e.g. `py_gettype("time", py_name("struct_time"))`.
  235. /// Return `0` if not found.
  236. PK_EXPORT py_Type py_gettype(const char* module, py_Name name);
  237. /// Check if the object is exactly the given type.
  238. PK_EXPORT bool py_istype(py_Ref, py_Type);
  239. /// Check if the object is an instance of the given type.
  240. PK_EXPORT bool py_isinstance(py_Ref obj, py_Type type);
  241. /// Check if the derived type is a subclass of the base type.
  242. PK_EXPORT bool py_issubclass(py_Type derived, py_Type base);
  243. /// Get the magic method from the given type only.
  244. /// The returned reference is always valid. However, its value may be `nil`.
  245. PK_EXPORT py_GlobalRef py_tpgetmagic(py_Type type, py_Name name);
  246. /// Search the magic method from the given type to the base type.
  247. /// Return `NULL` if not found.
  248. PK_EXPORT py_GlobalRef py_tpfindmagic(py_Type, py_Name name);
  249. /// Search the name from the given type to the base type.
  250. /// Return `NULL` if not found.
  251. PK_EXPORT py_ItemRef py_tpfindname(py_Type, py_Name name);
  252. /// Get the type object of the given type.
  253. PK_EXPORT py_GlobalRef py_tpobject(py_Type type);
  254. /// Get the type name.
  255. PK_EXPORT const char* py_tpname(py_Type type);
  256. /// Call a type to create a new instance.
  257. PK_EXPORT bool py_tpcall(py_Type type, int argc, py_Ref argv) PY_RAISE PY_RETURN;
  258. /// Check if the object is an instance of the given type.
  259. /// Raise `TypeError` if the check fails.
  260. PK_EXPORT bool py_checktype(py_Ref self, py_Type type) PY_RAISE;
  261. #define py_checkint(self) py_checktype(self, tp_int)
  262. #define py_checkfloat(self) py_checktype(self, tp_float)
  263. #define py_checkbool(self) py_checktype(self, tp_bool)
  264. #define py_checkstr(self) py_checktype(self, tp_str)
  265. /************* References *************/
  266. /// Get the i-th register.
  267. /// All registers are located in a contiguous memory.
  268. PK_EXPORT py_GlobalRef py_getreg(int i);
  269. /// Set the i-th register.
  270. PK_EXPORT void py_setreg(int i, py_Ref val);
  271. #define py_r0() py_getreg(0)
  272. #define py_r1() py_getreg(1)
  273. #define py_r2() py_getreg(2)
  274. #define py_r3() py_getreg(3)
  275. #define py_r4() py_getreg(4)
  276. #define py_r5() py_getreg(5)
  277. #define py_r6() py_getreg(6)
  278. #define py_r7() py_getreg(7)
  279. /// Get variable in the `__main__` module.
  280. PK_EXPORT py_ItemRef py_getglobal(py_Name name);
  281. /// Set variable in the `__main__` module.
  282. PK_EXPORT void py_setglobal(py_Name name, py_Ref val);
  283. /// Get variable in the `builtins` module.
  284. PK_EXPORT py_ItemRef py_getbuiltin(py_Name name);
  285. /// Equivalent to `*dst = *src`.
  286. PK_EXPORT void py_assign(py_Ref dst, py_Ref src);
  287. /// Get the last return value.
  288. PK_EXPORT py_GlobalRef py_retval();
  289. /// Get an item from the object's `__dict__`.
  290. /// Return `NULL` if not found.
  291. PK_EXPORT py_ItemRef py_getdict(py_Ref self, py_Name name);
  292. /// Set an item to the object's `__dict__`.
  293. PK_EXPORT void py_setdict(py_Ref self, py_Name name, py_Ref val);
  294. /// Delete an item from the object's `__dict__`.
  295. /// Return `true` if the deletion is successful.
  296. PK_EXPORT bool py_deldict(py_Ref self, py_Name name);
  297. /// Prepare an insertion to the object's `__dict__`.
  298. PK_EXPORT py_ItemRef py_emplacedict(py_Ref self, py_Name name);
  299. /// Apply a function to all items in the object's `__dict__`.
  300. /// Return `true` if the function is successful for all items.
  301. /// NOTE: Be careful if `f` modifies the object's `__dict__`.
  302. PK_EXPORT bool
  303. py_applydict(py_Ref self, bool (*f)(py_Name name, py_Ref val, void* ctx), void* ctx) PY_RAISE;
  304. /// Get the i-th slot of the object.
  305. /// The object must have slots and `i` must be in valid range.
  306. PK_EXPORT py_ObjectRef py_getslot(py_Ref self, int i);
  307. /// Set the i-th slot of the object.
  308. PK_EXPORT void py_setslot(py_Ref self, int i, py_Ref val);
  309. /************* Inspection *************/
  310. /// Get the current `function` object on the stack.
  311. /// Return `NULL` if not available.
  312. /// NOTE: This function should be placed at the beginning of your decl-based bindings.
  313. PK_EXPORT py_StackRef py_inspect_currentfunction();
  314. /// Get the current `module` object where the code is executed.
  315. /// Return `NULL` if not available.
  316. PK_EXPORT py_GlobalRef py_inspect_currentmodule();
  317. /************* Bindings *************/
  318. /// Bind a function to the object via "decl-based" style.
  319. /// @param obj the target object.
  320. /// @param sig signature of the function. e.g. `add(x, y)`.
  321. /// @param f function to bind.
  322. PK_EXPORT void py_bind(py_Ref obj, const char* sig, py_CFunction f);
  323. /// Bind a method to type via "argc-based" style.
  324. /// @param type the target type.
  325. /// @param name name of the method.
  326. /// @param f function to bind.
  327. PK_EXPORT void py_bindmethod(py_Type type, const char* name, py_CFunction f);
  328. /// Bind a function to the object via "argc-based" style.
  329. /// @param obj the target object.
  330. /// @param name name of the function.
  331. /// @param f function to bind.
  332. PK_EXPORT void py_bindfunc(py_Ref obj, const char* name, py_CFunction f);
  333. /// Bind a property to type.
  334. /// @param type the target type.
  335. /// @param name name of the property.
  336. /// @param getter getter function.
  337. /// @param setter setter function. Use `NULL` if not needed.
  338. PK_EXPORT void
  339. py_bindproperty(py_Type type, const char* name, py_CFunction getter, py_CFunction setter);
  340. #define py_bindmagic(type, __magic__, f) py_newnativefunc(py_tpgetmagic((type), __magic__), (f))
  341. #define PY_CHECK_ARGC(n) \
  342. if(argc != n) return TypeError("expected %d arguments, got %d", n, argc)
  343. #define PY_CHECK_ARG_TYPE(i, type) \
  344. if(!py_checktype(py_arg(i), type)) return false
  345. #define py_offset(p, i) ((py_Ref)((char*)p + ((i) << 4)))
  346. #define py_arg(i) py_offset(argv, i)
  347. /************* Python Equivalents *************/
  348. /// Python equivalent to `getattr(self, name)`.
  349. PK_EXPORT bool py_getattr(py_Ref self, py_Name name) PY_RAISE PY_RETURN;
  350. /// Python equivalent to `setattr(self, name, val)`.
  351. PK_EXPORT bool py_setattr(py_Ref self, py_Name name, py_Ref val) PY_RAISE;
  352. /// Python equivalent to `delattr(self, name)`.
  353. PK_EXPORT bool py_delattr(py_Ref self, py_Name name) PY_RAISE;
  354. /// Python equivalent to `self[key]`.
  355. PK_EXPORT bool py_getitem(py_Ref self, py_Ref key) PY_RAISE PY_RETURN;
  356. /// Python equivalent to `self[key] = val`.
  357. PK_EXPORT bool py_setitem(py_Ref self, py_Ref key, py_Ref val) PY_RAISE;
  358. /// Python equivalent to `del self[key]`.
  359. PK_EXPORT bool py_delitem(py_Ref self, py_Ref key) PY_RAISE;
  360. /// Perform a binary operation.
  361. /// The result will be set to `py_retval()`.
  362. /// The stack remains unchanged after the operation.
  363. PK_EXPORT bool py_binaryop(py_Ref lhs, py_Ref rhs, py_Name op, py_Name rop) PY_RAISE PY_RETURN;
  364. #define py_binaryadd(lhs, rhs) py_binaryop(lhs, rhs, __add__, __radd__)
  365. #define py_binarysub(lhs, rhs) py_binaryop(lhs, rhs, __sub__, __rsub__)
  366. #define py_binarymul(lhs, rhs) py_binaryop(lhs, rhs, __mul__, __rmul__)
  367. #define py_binarytruediv(lhs, rhs) py_binaryop(lhs, rhs, __truediv__, __rtruediv__)
  368. #define py_binaryfloordiv(lhs, rhs) py_binaryop(lhs, rhs, __floordiv__, __rfloordiv__)
  369. #define py_binarymod(lhs, rhs) py_binaryop(lhs, rhs, __mod__, __rmod__)
  370. #define py_binarypow(lhs, rhs) py_binaryop(lhs, rhs, __pow__, __rpow__)
  371. #define py_binarylshift(lhs, rhs) py_binaryop(lhs, rhs, __lshift__, 0)
  372. #define py_binaryrshift(lhs, rhs) py_binaryop(lhs, rhs, __rshift__, 0)
  373. #define py_binaryand(lhs, rhs) py_binaryop(lhs, rhs, __and__, 0)
  374. #define py_binaryor(lhs, rhs) py_binaryop(lhs, rhs, __or__, 0)
  375. #define py_binaryxor(lhs, rhs) py_binaryop(lhs, rhs, __xor__, 0)
  376. #define py_binarymatmul(lhs, rhs) py_binaryop(lhs, rhs, __matmul__, 0)
  377. /************* Stack Operations *************/
  378. /// Get the i-th object from the top of the stack.
  379. /// `i` should be negative, e.g. (-1) means TOS.
  380. PK_EXPORT py_StackRef py_peek(int i);
  381. /// Push the object to the stack.
  382. PK_EXPORT void py_push(py_Ref src);
  383. /// Push a `nil` object to the stack.
  384. PK_EXPORT void py_pushnil();
  385. /// Push a `None` object to the stack.
  386. PK_EXPORT void py_pushnone();
  387. /// Push a `py_Name` to the stack. This is used for keyword arguments.
  388. PK_EXPORT void py_pushname(py_Name name);
  389. /// Pop an object from the stack.
  390. PK_EXPORT void py_pop();
  391. /// Shrink the stack by n.
  392. PK_EXPORT void py_shrink(int n);
  393. /// Get a temporary variable from the stack.
  394. PK_EXPORT py_StackRef py_pushtmp();
  395. /// Get the unbound method of the object.
  396. /// Assume the object is located at the top of the stack.
  397. /// If return true: `[self] -> [unbound, self]`.
  398. /// If return false: `[self] -> [self]` (no change).
  399. PK_EXPORT bool py_pushmethod(py_Name name);
  400. /// Call a callable object.
  401. /// Assume `argc + kwargc` arguments are already pushed to the stack.
  402. /// The result will be set to `py_retval()`.
  403. /// The stack size will be reduced by `argc + kwargc`.
  404. PK_EXPORT bool py_vectorcall(uint16_t argc, uint16_t kwargc) PY_RAISE PY_RETURN;
  405. /// Evaluate an expression and push the result to the stack.
  406. /// This function is used for testing.
  407. PK_EXPORT bool py_pusheval(const char* expr, py_GlobalRef module) PY_RAISE;
  408. /************* Modules *************/
  409. /// Create a new module.
  410. PK_EXPORT py_GlobalRef py_newmodule(const char* path);
  411. /// Get a module by path.
  412. PK_EXPORT py_GlobalRef py_getmodule(const char* path);
  413. /// Import a module.
  414. /// The result will be set to `py_retval()`.
  415. /// -1: error, 0: not found, 1: success
  416. PK_EXPORT int py_import(const char* path) PY_RAISE;
  417. /************* Errors *************/
  418. /// Raise an exception by type and message. Always return false.
  419. PK_EXPORT bool py_exception(py_Type type, const char* fmt, ...) PY_RAISE;
  420. /// Raise an expection object. Always return false.
  421. PK_EXPORT bool py_raise(py_Ref) PY_RAISE;
  422. /// Print the current exception.
  423. /// The exception will be set as handled.
  424. PK_EXPORT void py_printexc();
  425. /// Format the current exception and return a null-terminated string.
  426. /// The result should be freed by the caller.
  427. /// The exception will be set as handled.
  428. PK_EXPORT char* py_formatexc();
  429. /// Check if an exception is raised.
  430. PK_EXPORT bool py_checkexc(bool ignore_handled);
  431. /// Check if the exception is an instance of the given type.
  432. /// This function is roughly equivalent to python's `except <T> as e:` block.
  433. /// If match, the exception will be stored in `py_retval()` as handled.
  434. PK_EXPORT bool py_matchexc(py_Type type) PY_RETURN;
  435. /// Clear the current exception.
  436. /// @param p0 the unwinding point. Use `NULL` if not needed.
  437. PK_EXPORT void py_clearexc(py_StackRef p0);
  438. #define NameError(n) py_exception(tp_NameError, "name '%n' is not defined", (n))
  439. #define TypeError(...) py_exception(tp_TypeError, __VA_ARGS__)
  440. #define RuntimeError(...) py_exception(tp_RuntimeError, __VA_ARGS__)
  441. #define ValueError(...) py_exception(tp_ValueError, __VA_ARGS__)
  442. #define IndexError(...) py_exception(tp_IndexError, __VA_ARGS__)
  443. #define ImportError(...) py_exception(tp_ImportError, __VA_ARGS__)
  444. #define ZeroDivisionError(...) py_exception(tp_ZeroDivisionError, __VA_ARGS__)
  445. #define AttributeError(self, n) \
  446. py_exception(tp_AttributeError, "'%t' object has no attribute '%n'", (self)->type, (n))
  447. #define UnboundLocalError(n) \
  448. py_exception(tp_UnboundLocalError, "local variable '%n' referenced before assignment", (n))
  449. PK_EXPORT bool StopIteration() PY_RAISE;
  450. PK_EXPORT bool KeyError(py_Ref key) PY_RAISE;
  451. /************* Operators *************/
  452. /// Python equivalent to `bool(val)`.
  453. /// 1: true, 0: false, -1: error
  454. PK_EXPORT int py_bool(py_Ref val) PY_RAISE;
  455. /// Compare two objects.
  456. /// 1: lhs == rhs, 0: lhs != rhs, -1: error
  457. PK_EXPORT int py_equal(py_Ref lhs, py_Ref rhs) PY_RAISE;
  458. /// Compare two objects.
  459. /// 1: lhs < rhs, 0: lhs >= rhs, -1: error
  460. PK_EXPORT int py_less(py_Ref lhs, py_Ref rhs) PY_RAISE;
  461. #define py_eq(lhs, rhs) py_binaryop(lhs, rhs, __eq__, __eq__)
  462. #define py_ne(lhs, rhs) py_binaryop(lhs, rhs, __ne__, __ne__)
  463. #define py_lt(lhs, rhs) py_binaryop(lhs, rhs, __lt__, __gt__)
  464. #define py_le(lhs, rhs) py_binaryop(lhs, rhs, __le__, __ge__)
  465. #define py_gt(lhs, rhs) py_binaryop(lhs, rhs, __gt__, __lt__)
  466. #define py_ge(lhs, rhs) py_binaryop(lhs, rhs, __ge__, __le__)
  467. /// Get the hash value of the object.
  468. PK_EXPORT bool py_hash(py_Ref, py_i64* out) PY_RAISE;
  469. /// Get the iterator of the object.
  470. PK_EXPORT bool py_iter(py_Ref) PY_RAISE PY_RETURN;
  471. /// Get the next element from the iterator.
  472. /// 1: success, 0: StopIteration, -1: error
  473. PK_EXPORT int py_next(py_Ref) PY_RAISE PY_RETURN;
  474. /// Python equivalent to `lhs is rhs`.
  475. PK_EXPORT bool py_isidentical(py_Ref, py_Ref);
  476. /// Call a function.
  477. /// It prepares the stack and then performs a `vectorcall(argc, 0, false)`.
  478. /// The result will be set to `py_retval()`.
  479. /// The stack remains unchanged after the operation.
  480. PK_EXPORT bool py_call(py_Ref f, int argc, py_Ref argv) PY_RAISE PY_RETURN;
  481. #ifndef NDEBUG
  482. /// Call a `py_CFunction` in a safe way.
  483. /// This function does extra checks to help you debug `py_CFunction`.
  484. PK_EXPORT bool py_callcfunc(py_CFunction f, int argc, py_Ref argv) PY_RAISE PY_RETURN;
  485. #else
  486. #define py_callcfunc(f, argc, argv) (f((argc), (argv)))
  487. #endif
  488. /// Python equivalent to `str(val)`.
  489. PK_EXPORT bool py_str(py_Ref val) PY_RAISE PY_RETURN;
  490. /// Python equivalent to `repr(val)`.
  491. PK_EXPORT bool py_repr(py_Ref val) PY_RAISE PY_RETURN;
  492. /// Python equivalent to `len(val)`.
  493. PK_EXPORT bool py_len(py_Ref val) PY_RAISE PY_RETURN;
  494. /// Python equivalent to `json.dumps(val)`.
  495. PK_EXPORT bool py_json_dumps(py_Ref val) PY_RAISE PY_RETURN;
  496. /// Python equivalent to `json.loads(val)`.
  497. PK_EXPORT bool py_json_loads(const char* source) PY_RAISE PY_RETURN;
  498. /************* Unchecked Functions *************/
  499. PK_EXPORT py_ObjectRef py_tuple_data(py_Ref self);
  500. PK_EXPORT py_ObjectRef py_tuple_getitem(py_Ref self, int i);
  501. PK_EXPORT void py_tuple_setitem(py_Ref self, int i, py_Ref val);
  502. PK_EXPORT int py_tuple_len(py_Ref self);
  503. PK_EXPORT py_ItemRef py_list_data(py_Ref self);
  504. PK_EXPORT py_ItemRef py_list_getitem(py_Ref self, int i);
  505. PK_EXPORT void py_list_setitem(py_Ref self, int i, py_Ref val);
  506. PK_EXPORT void py_list_delitem(py_Ref self, int i);
  507. PK_EXPORT int py_list_len(py_Ref self);
  508. PK_EXPORT void py_list_swap(py_Ref self, int i, int j);
  509. PK_EXPORT void py_list_append(py_Ref self, py_Ref val);
  510. PK_EXPORT py_ItemRef py_list_emplace(py_Ref self);
  511. PK_EXPORT void py_list_clear(py_Ref self);
  512. PK_EXPORT void py_list_insert(py_Ref self, int i, py_Ref val);
  513. /// -1: error, 0: not found, 1: found
  514. PK_EXPORT int py_dict_getitem(py_Ref self, py_Ref key) PY_RAISE PY_RETURN;
  515. /// true: success, false: error
  516. PK_EXPORT bool py_dict_setitem(py_Ref self, py_Ref key, py_Ref val) PY_RAISE;
  517. /// -1: error, 0: not found, 1: found (and deleted)
  518. PK_EXPORT int py_dict_delitem(py_Ref self, py_Ref key) PY_RAISE;
  519. /// -1: error, 0: not found, 1: found
  520. PK_EXPORT int py_dict_getitem_by_str(py_Ref self, const char* key) PY_RAISE PY_RETURN;
  521. /// true: success, false: error
  522. PK_EXPORT bool py_dict_setitem_by_str(py_Ref self, const char* key, py_Ref val) PY_RAISE;
  523. /// -1: error, 0: not found, 1: found (and deleted)
  524. PK_EXPORT int py_dict_delitem_by_str(py_Ref self, const char* key) PY_RAISE;
  525. /// true: success, false: error
  526. PK_EXPORT bool
  527. py_dict_apply(py_Ref self, bool (*f)(py_Ref key, py_Ref val, void* ctx), void* ctx) PY_RAISE;
  528. /// noexcept
  529. PK_EXPORT int py_dict_len(py_Ref self);
  530. /************* linalg module *************/
  531. void py_newvec2(py_OutRef out, c11_vec2);
  532. void py_newvec3(py_OutRef out, c11_vec3);
  533. void py_newvec2i(py_OutRef out, c11_vec2i);
  534. void py_newvec3i(py_OutRef out, c11_vec3i);
  535. c11_mat3x3* py_newmat3x3(py_OutRef out);
  536. c11_vec2 py_tovec2(py_Ref self);
  537. c11_vec3 py_tovec3(py_Ref self);
  538. c11_vec2i py_tovec2i(py_Ref self);
  539. c11_vec3i py_tovec3i(py_Ref self);
  540. c11_mat3x3* py_tomat3x3(py_Ref self);
  541. /************* Others *************/
  542. /// An utility function to read a line from stdin for REPL.
  543. PK_EXPORT int py_replinput(char* buf, int max_size);
  544. /// Python favored string formatting.
  545. /// %d: int
  546. /// %i: py_i64 (int64_t)
  547. /// %f: py_f64 (double)
  548. /// %s: const char*
  549. /// %q: c11_sv
  550. /// %v: c11_sv
  551. /// %c: char
  552. /// %p: void*
  553. /// %t: py_Type
  554. /// %n: py_Name
  555. enum py_MagicNames {
  556. py_MagicNames__NULL, // 0 is reserved
  557. #define MAGIC_METHOD(x) x,
  558. #include "pocketpy/xmacros/magics.h"
  559. #undef MAGIC_METHOD
  560. };
  561. enum py_PredefinedTypes {
  562. tp_nil = 0,
  563. tp_object = 1,
  564. tp_type, // py_Type
  565. tp_int,
  566. tp_float,
  567. tp_bool,
  568. tp_str,
  569. tp_str_iterator,
  570. tp_list, // c11_vector
  571. tp_tuple, // N slots
  572. tp_array_iterator,
  573. tp_slice, // 3 slots (start, stop, step)
  574. tp_range,
  575. tp_range_iterator,
  576. tp_module,
  577. tp_function,
  578. tp_nativefunc,
  579. tp_boundmethod,
  580. tp_super, // 1 slot + py_Type
  581. tp_BaseException, // 2 slots (arg + inner_exc)
  582. tp_Exception,
  583. tp_bytes,
  584. tp_namedict,
  585. tp_locals,
  586. tp_code,
  587. tp_dict,
  588. tp_dict_items, // 1 slot
  589. tp_property, // 2 slots (getter + setter)
  590. tp_star_wrapper, // 1 slot + int level
  591. tp_staticmethod, // 1 slot
  592. tp_classmethod, // 1 slot
  593. tp_NoneType,
  594. tp_NotImplementedType,
  595. tp_ellipsis,
  596. tp_generator,
  597. /* builtin exceptions */
  598. tp_SystemExit,
  599. tp_KeyboardInterrupt,
  600. tp_StopIteration,
  601. tp_SyntaxError,
  602. tp_StackOverflowError,
  603. tp_IOError,
  604. tp_OSError,
  605. tp_NotImplementedError,
  606. tp_TypeError,
  607. tp_IndexError,
  608. tp_ValueError,
  609. tp_RuntimeError,
  610. tp_ZeroDivisionError,
  611. tp_NameError,
  612. tp_UnboundLocalError,
  613. tp_AttributeError,
  614. tp_ImportError,
  615. tp_AssertionError,
  616. tp_KeyError,
  617. /* Extended */
  618. tp_vec2,
  619. tp_vec3,
  620. tp_vec2i,
  621. tp_vec3i,
  622. tp_mat3x3,
  623. };
  624. #ifdef __cplusplus
  625. }
  626. #endif