pocketpy.h 30 KB

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