pocketpy.h 36 KB

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