pocketpy.h 35 KB

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