pocketpy.h 34 KB

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