pocketpy.h 27 KB

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