pocketpy.h 35 KB

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